import { useState } from 'react';
import { Wallet, Plus, CreditCard, Smartphone, Building, ArrowUpRight, ArrowDownLeft, Clock, CheckCircle, XCircle } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useToast } from '@/hooks/use-toast';
import { apiRequest } from '@/lib/queryClient';

interface Transaction {
  id: string;
  type: string;
  amount: number;
  balanceAfter: number;
  description: string;
  status: string;
  createdAt: string;
  orderId?: string;
}

interface PaymentMethod {
  id: string;
  type: string;
  provider?: string;
  accountNumber: string;
  accountName?: string;
  isDefault: boolean;
  isActive: boolean;
}

export function WalletDashboard() {
  const [isAddFundsOpen, setIsAddFundsOpen] = useState(false);
  const [isAddPaymentMethodOpen, setIsAddPaymentMethodOpen] = useState(false);
  const [addFundsForm, setAddFundsForm] = useState({
    amount: '',
    paymentMethodId: ''
  });
  const [paymentMethodForm, setPaymentMethodForm] = useState({
    type: 'mobile_money',
    provider: 'orange_money',
    accountNumber: '',
    accountName: '',
    isDefault: false
  });
  
  const { toast } = useToast();
  const queryClient = useQueryClient();

  // Get wallet balance
  const { data: walletData, isLoading: isLoadingBalance } = useQuery({
    queryKey: ['/api/wallet/balance'],
    staleTime: 30 * 1000, // 30 seconds
  });

  // Get transaction history
  const { data: transactions = [], isLoading: isLoadingTransactions } = useQuery<Transaction[]>({
    queryKey: ['/api/wallet/transactions'],
    staleTime: 60 * 1000, // 1 minute
  });

  // Get payment methods
  const { data: paymentMethods = [], isLoading: isLoadingPaymentMethods } = useQuery<PaymentMethod[]>({
    queryKey: ['/api/payment-methods'],
    staleTime: 5 * 60 * 1000, // 5 minutes
  });

  // Add funds mutation
  const addFundsMutation = useMutation({
    mutationFn: async (data: { amount: number; paymentMethodId: string }) => {
      return apiRequest('/api/wallet/add-funds', 'POST', data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/wallet/balance'] });
      queryClient.invalidateQueries({ queryKey: ['/api/wallet/transactions'] });
      setIsAddFundsOpen(false);
      setAddFundsForm({ amount: '', paymentMethodId: '' });
      toast({
        title: "Rechargement réussi",
        description: "Votre portefeuille a été rechargé avec succès",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Erreur",
        description: error.message || "Erreur lors du rechargement",
        variant: "destructive",
      });
    },
  });

  // Add payment method mutation
  const addPaymentMethodMutation = useMutation({
    mutationFn: async (data: any) => {
      return apiRequest('/api/payment-methods', 'POST', data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/payment-methods'] });
      setIsAddPaymentMethodOpen(false);
      setPaymentMethodForm({
        type: 'mobile_money',
        provider: 'orange_money',
        accountNumber: '',
        accountName: '',
        isDefault: false
      });
      toast({
        title: "Moyen de paiement ajouté",
        description: "Votre moyen de paiement a été ajouté avec succès",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Erreur",
        description: error.message || "Erreur lors de l'ajout du moyen de paiement",
        variant: "destructive",
      });
    },
  });

  const handleAddFunds = () => {
    const amount = parseInt(addFundsForm.amount);
    if (!amount || amount <= 0) {
      toast({
        title: "Erreur",
        description: "Veuillez saisir un montant valide",
        variant: "destructive",
      });
      return;
    }

    if (!addFundsForm.paymentMethodId) {
      toast({
        title: "Erreur",
        description: "Veuillez sélectionner un moyen de paiement",
        variant: "destructive",
      });
      return;
    }

    addFundsMutation.mutate({
      amount,
      paymentMethodId: addFundsForm.paymentMethodId
    });
  };

  const handleAddPaymentMethod = () => {
    if (!paymentMethodForm.accountNumber) {
      toast({
        title: "Erreur",
        description: "Veuillez saisir le numéro de compte",
        variant: "destructive",
      });
      return;
    }

    addPaymentMethodMutation.mutate(paymentMethodForm);
  };

  const formatAmount = (amount: number) => {
    return `${Math.abs(amount).toLocaleString()} FCFA`;
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('fr-FR', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const getTransactionIcon = (type: string) => {
    switch (type) {
      case 'deposit':
        return <ArrowDownLeft className="h-4 w-4 text-green-600" />;
      case 'payment':
        return <ArrowUpRight className="h-4 w-4 text-red-600" />;
      case 'earnings':
        return <ArrowDownLeft className="h-4 w-4 text-blue-600" />;
      case 'refund':
        return <ArrowDownLeft className="h-4 w-4 text-green-600" />;
      default:
        return <Clock className="h-4 w-4 text-gray-600" />;
    }
  };

  const getTransactionColor = (type: string) => {
    switch (type) {
      case 'deposit':
      case 'earnings':
      case 'refund':
        return 'text-green-600';
      case 'payment':
        return 'text-red-600';
      default:
        return 'text-gray-600';
    }
  };

  const getPaymentMethodIcon = (type: string) => {
    switch (type) {
      case 'mobile_money':
        return <Smartphone className="h-5 w-5" />;
      case 'bank_card':
        return <CreditCard className="h-5 w-5" />;
      case 'bank_transfer':
        return <Building className="h-5 w-5" />;
      default:
        return <CreditCard className="h-5 w-5" />;
    }
  };

  const getProviderName = (provider?: string) => {
    const providers: Record<string, string> = {
      'orange_money': 'Orange Money',
      'mtn_money': 'MTN Mobile Money',
      'moov_money': 'Moov Money',
      'visa': 'Visa',
      'mastercard': 'Mastercard'
    };
    return providers[provider || ''] || provider || '';
  };

  if (isLoadingBalance) {
    return (
      <div className="flex items-center justify-center py-8">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-red-600"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6" data-testid="wallet-dashboard">
      {/* Wallet Balance Card */}
      <Card className="bg-gradient-to-r from-red-600 to-red-700 text-white">
        <CardContent className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <div className="flex items-center gap-2 mb-2">
                <Wallet className="h-6 w-6" />
                <span className="text-red-100">Solde du portefeuille</span>
              </div>
              <p className="text-3xl font-bold" data-testid="wallet-balance">
                {formatAmount((walletData as any)?.balance || 0)}
              </p>
            </div>
            <Dialog open={isAddFundsOpen} onOpenChange={setIsAddFundsOpen}>
              <DialogTrigger asChild>
                <Button 
                  variant="secondary" 
                  className="bg-white text-red-600 hover:bg-red-50"
                  data-testid="button-add-funds"
                >
                  <Plus className="h-4 w-4 mr-2" />
                  Recharger
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Recharger le portefeuille</DialogTitle>
                </DialogHeader>
                <div className="space-y-4">
                  <div>
                    <Label htmlFor="amount">Montant (FCFA)</Label>
                    <Input
                      id="amount"
                      type="number"
                      value={addFundsForm.amount}
                      onChange={(e) => setAddFundsForm({ ...addFundsForm, amount: e.target.value })}
                      placeholder="Ex: 10000"
                      data-testid="input-add-funds-amount"
                    />
                  </div>
                  <div>
                    <Label htmlFor="paymentMethod">Moyen de paiement</Label>
                    <Select
                      value={addFundsForm.paymentMethodId}
                      onValueChange={(value) => setAddFundsForm({ ...addFundsForm, paymentMethodId: value })}
                    >
                      <SelectTrigger data-testid="select-payment-method">
                        <SelectValue placeholder="Sélectionner un moyen de paiement" />
                      </SelectTrigger>
                      <SelectContent>
                        {paymentMethods.map((method) => (
                          <SelectItem key={method.id} value={method.id}>
                            <div className="flex items-center gap-2">
                              {getPaymentMethodIcon(method.type)}
                              <span>{method.accountNumber} - {getProviderName(method.provider)}</span>
                              {method.isDefault && <Badge variant="secondary">Par défaut</Badge>}
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="flex justify-end gap-2">
                    <Button 
                      variant="outline" 
                      onClick={() => setIsAddFundsOpen(false)}
                      data-testid="button-cancel-add-funds"
                    >
                      Annuler
                    </Button>
                    <Button 
                      onClick={handleAddFunds}
                      disabled={addFundsMutation.isPending}
                      data-testid="button-confirm-add-funds"
                    >
                      {addFundsMutation.isPending ? 'Rechargement...' : 'Recharger'}
                    </Button>
                  </div>
                </div>
              </DialogContent>
            </Dialog>
          </div>
        </CardContent>
      </Card>

      {/* Wallet Management Tabs */}
      <Tabs defaultValue="transactions" className="w-full">
        <TabsList>
          <TabsTrigger value="transactions">Historique des transactions</TabsTrigger>
          <TabsTrigger value="payment-methods">Moyens de paiement</TabsTrigger>
        </TabsList>

        <TabsContent value="transactions">
          <Card>
            <CardHeader>
              <CardTitle>Historique des transactions</CardTitle>
            </CardHeader>
            <CardContent>
              {isLoadingTransactions ? (
                <div className="flex items-center justify-center py-8">
                  <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-red-600"></div>
                </div>
              ) : transactions.length === 0 ? (
                <div className="text-center py-8 text-gray-500">
                  <Clock className="mx-auto h-12 w-12 mb-4" />
                  <p>Aucune transaction</p>
                  <p className="text-sm">Vos transactions apparaîtront ici</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {transactions.map((transaction) => (
                    <div 
                      key={transaction.id}
                      className="flex items-center justify-between p-3 border rounded-lg"
                      data-testid={`transaction-${transaction.id}`}
                    >
                      <div className="flex items-center gap-3">
                        {getTransactionIcon(transaction.type)}
                        <div>
                          <p className="font-medium">{transaction.description}</p>
                          <p className="text-sm text-gray-600">{formatDate(transaction.createdAt)}</p>
                        </div>
                      </div>
                      <div className="text-right">
                        <p className={`font-medium ${getTransactionColor(transaction.type)}`}>
                          {transaction.amount > 0 ? '+' : ''}{formatAmount(transaction.amount)}
                        </p>
                        <p className="text-sm text-gray-600">
                          Solde: {formatAmount(transaction.balanceAfter)}
                        </p>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="payment-methods">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle>Moyens de paiement</CardTitle>
                <Dialog open={isAddPaymentMethodOpen} onOpenChange={setIsAddPaymentMethodOpen}>
                  <DialogTrigger asChild>
                    <Button data-testid="button-add-payment-method">
                      <Plus className="h-4 w-4 mr-2" />
                      Ajouter
                    </Button>
                  </DialogTrigger>
                  <DialogContent>
                    <DialogHeader>
                      <DialogTitle>Ajouter un moyen de paiement</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4">
                      <div>
                        <Label htmlFor="type">Type</Label>
                        <Select
                          value={paymentMethodForm.type}
                          onValueChange={(value) => setPaymentMethodForm({ ...paymentMethodForm, type: value })}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="mobile_money">Mobile Money</SelectItem>
                            <SelectItem value="bank_card">Carte bancaire</SelectItem>
                            <SelectItem value="bank_transfer">Virement bancaire</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      
                      {paymentMethodForm.type === 'mobile_money' && (
                        <div>
                          <Label htmlFor="provider">Opérateur</Label>
                          <Select
                            value={paymentMethodForm.provider}
                            onValueChange={(value) => setPaymentMethodForm({ ...paymentMethodForm, provider: value })}
                          >
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="orange_money">Orange Money</SelectItem>
                              <SelectItem value="mtn_money">MTN Mobile Money</SelectItem>
                              <SelectItem value="moov_money">Moov Money</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                      )}

                      <div>
                        <Label htmlFor="accountNumber">
                          {paymentMethodForm.type === 'mobile_money' ? 'Numéro de téléphone' : 'Numéro de compte'}
                        </Label>
                        <Input
                          id="accountNumber"
                          type="text"
                          value={paymentMethodForm.accountNumber}
                          onChange={(e) => setPaymentMethodForm({ ...paymentMethodForm, accountNumber: e.target.value })}
                          placeholder={paymentMethodForm.type === 'mobile_money' ? 'Ex: 77123456' : 'Ex: 1234567890'}
                          data-testid="input-account-number"
                        />
                      </div>

                      <div>
                        <Label htmlFor="accountName">Nom du titulaire (optionnel)</Label>
                        <Input
                          id="accountName"
                          type="text"
                          value={paymentMethodForm.accountName}
                          onChange={(e) => setPaymentMethodForm({ ...paymentMethodForm, accountName: e.target.value })}
                          placeholder="Ex: Jean Dupont"
                        />
                      </div>

                      <div className="flex justify-end gap-2">
                        <Button 
                          variant="outline" 
                          onClick={() => setIsAddPaymentMethodOpen(false)}
                        >
                          Annuler
                        </Button>
                        <Button 
                          onClick={handleAddPaymentMethod}
                          disabled={addPaymentMethodMutation.isPending}
                        >
                          {addPaymentMethodMutation.isPending ? 'Ajout...' : 'Ajouter'}
                        </Button>
                      </div>
                    </div>
                  </DialogContent>
                </Dialog>
              </div>
            </CardHeader>
            <CardContent>
              {isLoadingPaymentMethods ? (
                <div className="flex items-center justify-center py-8">
                  <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-red-600"></div>
                </div>
              ) : paymentMethods.length === 0 ? (
                <div className="text-center py-8 text-gray-500">
                  <CreditCard className="mx-auto h-12 w-12 mb-4" />
                  <p>Aucun moyen de paiement</p>
                  <p className="text-sm">Ajoutez un moyen de paiement pour recharger votre portefeuille</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {paymentMethods.map((method) => (
                    <div 
                      key={method.id}
                      className="flex items-center justify-between p-3 border rounded-lg"
                      data-testid={`payment-method-${method.id}`}
                    >
                      <div className="flex items-center gap-3">
                        {getPaymentMethodIcon(method.type)}
                        <div>
                          <p className="font-medium">{method.accountNumber}</p>
                          <p className="text-sm text-gray-600">
                            {getProviderName(method.provider)} 
                            {method.accountName && ` - ${method.accountName}`}
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        {method.isDefault && (
                          <Badge className="bg-green-100 text-green-800">Par défaut</Badge>
                        )}
                        <Badge variant="outline">{method.type}</Badge>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}