'use client';

import { X, Mail, User, Send, CheckCircle2 } from 'lucide-react';
import { useState } from 'react';
import { useTranslations } from 'next-intl';

interface Affiliate {
  id: number;
  name: string;
  country: string;
  verified: number;
  created_at: string;
  updated_at: string;
}

interface InviteAffiliatePopupProps {
  affiliate: Affiliate;
  isOpen: boolean;
  onClose: () => void;
}

export function InviteAffiliatePopup({
  affiliate,
  isOpen,
  onClose,
}: InviteAffiliatePopupProps) {
  const t = useTranslations('myAffiliates.invitePopup');
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSendInvitation = async () => {
    setSending(true);
    setError(null);
    
    try {
      const response = await fetch('/api/invitations', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          invited_user_id: affiliate.id,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Failed to send invitation');
      }

      setSending(false);
      setSent(true);
      
      // Fermer après 2 secondes
      setTimeout(() => {
        setSent(false);
        onClose();
      }, 2000);
    } catch (err) {
      setSending(false);
      setError(err instanceof Error ? err.message : 'An error occurred');
      console.error('Error sending invitation:', err);
    }
  };

  if (!isOpen) return null;

  // Réinitialiser l'état d'erreur quand le popup s'ouvre
  const handleClose = () => {
    setError(null);
    setSent(false);
    onClose();
  };

  return (
    <>
      {/* Overlay */}
      <div
        className="fixed inset-0 bg-black/50 z-50"
        onClick={handleClose}
      />

      {/* Popup */}
      <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
        <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl w-full max-w-md animate-in fade-in zoom-in duration-200">
          {/* Header */}
          <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white flex items-center gap-2">
              <User className="w-5 h-5" />
              {t('title')}
            </h2>
            <button
              onClick={handleClose}
              className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-xl transition-colors"
              aria-label="Fermer"
            >
              <X className="w-5 h-5 text-gray-500 dark:text-gray-400" />
            </button>
          </div>

          {/* Content */}
          <div className="p-6">
            {!sent ? (
              <>
                {/* Message d'erreur */}
                {error && (
                  <div className="mb-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl p-4">
                    <div className="flex items-start space-x-3">
                      <X className="w-5 h-5 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
                      <div className="flex-1">
                        <p className="text-sm text-red-900 dark:text-red-200 font-medium mb-1">
                          Erreur lors de l'envoi
                        </p>
                        <p className="text-xs text-red-700 dark:text-red-300">
                          {error}
                        </p>
                      </div>
                    </div>
                  </div>
                )}

                <div className="mb-6">
                  <div className="flex items-center space-x-4 mb-4">
                    <div className="w-16 h-16 bg-teal-500 rounded-2xl flex items-center justify-center text-white font-bold text-2xl">
                      {affiliate.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
                    </div>
                    <div>
                      <h3 className="font-semibold text-lg text-gray-900 dark:text-white">
                        {affiliate.name}
                      </h3>
                      <p className="text-sm text-gray-500 dark:text-gray-400">
                        {t('subtitle')}
                      </p>
                    </div>
                  </div>

                  <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-xl p-4 mb-4">
                    <div className="flex items-start space-x-3">
                      <Mail className="w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5" />
                      <div className="flex-1">
                        <p className="text-sm text-blue-900 dark:text-blue-200 font-medium mb-1">
                          {t('emailTitle')}
                        </p>
                        <p className="text-xs text-blue-700 dark:text-blue-300">
                          {t('emailDescription')}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Actions */}
                <div className="flex gap-3">
                  <button
                    onClick={handleClose}
                    className="flex-1 px-4 py-3 rounded-xl border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                  >
                    {t('cancelButton')}
                  </button>
                  <button
                    onClick={handleSendInvitation}
                    disabled={sending}
                    className="flex-1 px-4 py-3 rounded-xl bg-teal-500 text-white hover:bg-teal-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2"
                  >
                    {sending ? (
                      <>
                        <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                        {t('sendingButton')}
                      </>
                    ) : (
                      <>
                        <Send className="w-4 h-4" />
                        {t('sendButton')}
                      </>
                    )}
                  </button>
                </div>
              </>
            ) : (
              <div className="text-center py-8">
                <div className="w-16 h-16 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center mx-auto mb-4">
                  <CheckCircle2 className="w-8 h-8 text-green-600 dark:text-green-400" />
                </div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                  {t('successTitle')}
                </h3>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  {t('successMessage', { name: affiliate.name })}
                </p>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}
