import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Loader2, Smartphone, CreditCard, ExternalLink, CheckCircle, XCircle } from 'lucide-react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { apiRequest } from '@/lib/queryClient';

interface PaymentChannel {
  code: string;
  name: string;
  description: string;
}

interface PaymentModalProps {
  isOpen: boolean;
  onClose: () => void;
  orderId: string;
  amount: number;
  customerInfo: {
    email: string;
    firstName: string;
    lastName: string;
    phone: string;
  };
}

export function PaymentModal({ isOpen, onClose, orderId, amount, customerInfo }: PaymentModalProps) {
  const [selectedChannel, setSelectedChannel] = useState<string>('');
  const [paymentStep, setPaymentStep] = useState<'select' | 'processing' | 'success' | 'error'>('select');
  const [paymentUrl, setPaymentUrl] = useState<string>('');

  // Récupérer les canaux de paiement disponibles
  const { data: channels = [], isLoading: channelsLoading } = useQuery<PaymentChannel[]>({
    queryKey: ['/api/payments/channels'],
    enabled: isOpen
  });

  // Mutation pour initialiser le paiement
  const initPaymentMutation = useMutation({
    mutationFn: async ({ orderId, amount, channel, customerInfo }: {
      orderId: string;
      amount: number;
      channel: string;
      customerInfo: any;
    }) => {
      const response = await fetch('/api/payments/initialize', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ orderId, amount, channel, customerInfo })
      });
      
      if (!response.ok) {
        throw new Error('Erreur lors de l\'initialisation du paiement');
      }
      
      return response.json();
    },
    onSuccess: (data) => {
      if (data.code === 0 && data.redirectUrl) {
        setPaymentUrl(data.redirectUrl);
        setPaymentStep('processing');
      } else {
        setPaymentStep('error');
      }
    },
    onError: () => {
      setPaymentStep('error');
    }
  });

  const handlePaymentInit = () => {
    if (!selectedChannel) return;
    
    initPaymentMutation.mutate({
      orderId,
      amount,
      channel: selectedChannel,
      customerInfo
    });
  };

  const getChannelIcon = (code: string) => {
    if (code === 'CARD') return <CreditCard className="w-6 h-6" />;
    return <Smartphone className="w-6 h-6" />;
  };

  const getChannelColor = (code: string) => {
    switch (code) {
      case 'OMCIV2': return 'bg-orange-500';
      case 'MOMO': return 'bg-yellow-500';
      case 'FLOOZ': return 'bg-blue-500';
      case 'CARD': return 'bg-gray-700';
      default: return 'bg-gray-500';
    }
  };

  const formatAmount = (amount: number) => {
    return new Intl.NumberFormat('fr-CI', {
      style: 'currency',
      currency: 'XOF',
      minimumFractionDigits: 0
    }).format(amount);
  };

  // Reset state when modal opens/closes
  useEffect(() => {
    if (isOpen) {
      setPaymentStep('select');
      setSelectedChannel('');
      setPaymentUrl('');
    }
  }, [isOpen]);

  // Écouter les messages de retour de paiement
  useEffect(() => {
    const handlePaymentReturn = (event: MessageEvent) => {
      if (event.data?.type === 'payment-completed') {
        setPaymentStep('success');
      } else if (event.data?.type === 'payment-failed') {
        setPaymentStep('error');
      }
    };

    window.addEventListener('message', handlePaymentReturn);
    return () => window.removeEventListener('message', handlePaymentReturn);
  }, []);

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-md mx-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Smartphone className="w-5 h-5" />
            Paiement Mobile Money
          </DialogTitle>
        </DialogHeader>

        {paymentStep === 'select' && (
          <div className="space-y-4">
            <div className="text-center p-4 bg-blue-50 rounded-lg">
              <p className="text-sm text-gray-600">Montant à payer</p>
              <p className="text-2xl font-bold text-blue-600">{formatAmount(amount)}</p>
              <p className="text-xs text-gray-500">Commande #{orderId}</p>
            </div>

            <div className="space-y-3">
              <h3 className="font-medium text-gray-900">Choisissez votre mode de paiement :</h3>
              
              {channelsLoading ? (
                <div className="flex justify-center py-4">
                  <Loader2 className="w-6 h-6 animate-spin" />
                </div>
              ) : (
                <div className="grid gap-2">
                  {channels.map((channel) => (
                    <Card 
                      key={channel.code} 
                      className={`cursor-pointer transition-all hover:shadow-md ${
                        selectedChannel === channel.code ? 'ring-2 ring-blue-500 bg-blue-50' : ''
                      }`}
                      onClick={() => setSelectedChannel(channel.code)}
                    >
                      <CardContent className="flex items-center gap-3 p-3">
                        <div className={`w-10 h-10 rounded-lg flex items-center justify-center text-white ${getChannelColor(channel.code)}`}>
                          {getChannelIcon(channel.code)}
                        </div>
                        <div className="flex-1">
                          <p className="font-medium text-sm">{channel.name}</p>
                          <p className="text-xs text-gray-500">{channel.description}</p>
                        </div>
                        {selectedChannel === channel.code && (
                          <CheckCircle className="w-5 h-5 text-blue-500" />
                        )}
                      </CardContent>
                    </Card>
                  ))}
                </div>
              )}
            </div>

            <div className="flex gap-2">
              <Button variant="outline" onClick={onClose} className="flex-1">
                Annuler
              </Button>
              <Button 
                onClick={handlePaymentInit}
                disabled={!selectedChannel || initPaymentMutation.isPending}
                className="flex-1"
              >
                {initPaymentMutation.isPending ? (
                  <Loader2 className="w-4 h-4 animate-spin mr-2" />
                ) : null}
                Payer
              </Button>
            </div>
          </div>
        )}

        {paymentStep === 'processing' && (
          <div className="text-center space-y-4 py-6">
            <div className="w-16 h-16 mx-auto bg-blue-100 rounded-full flex items-center justify-center">
              <Loader2 className="w-8 h-8 text-blue-600 animate-spin" />
            </div>
            <div>
              <h3 className="font-medium text-gray-900">Redirection en cours...</h3>
              <p className="text-sm text-gray-600 mt-1">
                Vous allez être redirigé vers la plateforme de paiement sécurisée
              </p>
            </div>
            {paymentUrl && (
              <Button 
                onClick={() => window.open(paymentUrl, '_blank')}
                className="w-full"
              >
                <ExternalLink className="w-4 h-4 mr-2" />
                Ouvrir la page de paiement
              </Button>
            )}
            <Button variant="outline" onClick={onClose} size="sm">
              Fermer
            </Button>
          </div>
        )}

        {paymentStep === 'success' && (
          <div className="text-center space-y-4 py-6">
            <div className="w-16 h-16 mx-auto bg-green-100 rounded-full flex items-center justify-center">
              <CheckCircle className="w-8 h-8 text-green-600" />
            </div>
            <div>
              <h3 className="font-medium text-green-900">Paiement réussi !</h3>
              <p className="text-sm text-gray-600 mt-1">
                Votre paiement de {formatAmount(amount)} a été traité avec succès
              </p>
            </div>
            <Button onClick={onClose} className="w-full">
              Continuer
            </Button>
          </div>
        )}

        {paymentStep === 'error' && (
          <div className="text-center space-y-4 py-6">
            <div className="w-16 h-16 mx-auto bg-red-100 rounded-full flex items-center justify-center">
              <XCircle className="w-8 h-8 text-red-600" />
            </div>
            <div>
              <h3 className="font-medium text-red-900">Erreur de paiement</h3>
              <p className="text-sm text-gray-600 mt-1">
                Une erreur s'est produite lors du traitement de votre paiement
              </p>
            </div>
            <div className="flex gap-2">
              <Button variant="outline" onClick={() => setPaymentStep('select')} className="flex-1">
                Réessayer
              </Button>
              <Button variant="outline" onClick={onClose} className="flex-1">
                Fermer
              </Button>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}