import React, { useState, useEffect } from 'react';
import { User, Mail, Phone, Send, ChevronRight, Check, Edit3 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Client, Contacts } from '@/types/clientType';
import { DevisListItem } from '@/types/devisType';
import FormModal, { FormField, FormSection } from '../ui/FormModal';

interface SignatureData {
  emailSignataire: string;
  nomSignataire: string;
}

interface SendSignatureRequestModalProps {
  isOpen: boolean;
  onClose: () => void;
  client: Client;
  quote: DevisListItem;
  onConfirm: (data: SignatureData) => void;
  loading?: boolean;
}

export const ModalSendSignatureRequest: React.FC<SendSignatureRequestModalProps> = ({
  isOpen,
  onClose,
  client,
  quote,
  onConfirm,
  loading
}) => {
  const [step, setStep] = useState<1 | 2>(1);
  const [selectedContact, setSelectedContact] = useState<Contacts | null>(null)
  const [useManualEntry, setUseManualEntry] = useState(false);
  const [email, setEmail] = useState('');
  const [nomSignataire, setNomSignataire] = useState('');

  // Réinitialiser quand le modal s'ouvre
  useEffect(() => {
    if (isOpen) {
      setStep(1);
      setSelectedContact(null);
      setUseManualEntry(false);
      setEmail(client?.email || '');
      setNomSignataire(client?.intitule || '');
    }
  }, [isOpen, client]);

  // Mettre à jour les champs quand un contact est sélectionné
  useEffect(() => {
    if (selectedContact) {
      setEmail(selectedContact.email || '');
      setNomSignataire(`${selectedContact.nom || ''} ${selectedContact.prenom || ''}`.trim());
      setUseManualEntry(false);
    }
  }, [selectedContact]);

  const isValidEmail = (e: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);
  
  const canProceed = email.trim() && nomSignataire.trim() && isValidEmail(email);

  const handleSelectContact = (contact: Contacts) => {
    if (selectedContact?.contact_numero === contact.contact_numero) {
      // Désélectionner si on clique sur le même contact
      setSelectedContact(null);
    } else {
      setSelectedContact(contact);
    }
  };

  const handleManualEntry = () => {
    setSelectedContact(null);
    setUseManualEntry(true);
    setEmail('');
    setNomSignataire('');
  };

  const handleNext = () => {
    if (canProceed) {
      setStep(2);
    }
  };

  const handleBack = () => {
    setStep(1);
  };

  const handleConfirm = () => {
    onConfirm({ emailSignataire: email, nomSignataire });
  };

  const handleClose = () => {
    setStep(1);
    setSelectedContact(null);
    setUseManualEntry(false);
    setEmail(client?.email || '');
    setNomSignataire(client?.intitule || '');
    onClose();
  };

  const hasContacts = client?.contacts && client.contacts.length > 0;

  return (
    <FormModal
      isOpen={isOpen}
      onClose={handleClose}
      title={step === 1 ? "Envoyer le devis pour signature" : "Confirmer l'envoi"}
      size="md"
      onSubmit={step === 1 ? handleNext : handleConfirm}
      submitLabel={step === 1 ? "Suivant" : "Envoyer pour signature"}
      loading={loading}
      disabled={!canProceed}
      showBackButton={step === 2}
      onBack={handleBack}
    >
      {step === 1 ? (
        <>
          {/* Section Sélection de contact */}
          {hasContacts && (
            <FormSection 
              title="Sélectionner un contact" 
              description={`Choisissez le contact de ${client?.intitule} qui signera ce devis`}
            >
              <div className="col-span-2 space-y-2 max-h-[200px] overflow-y-auto custom-scrollbar">
                {client.contacts!.map((contact, index) => (
                  <div 
                    key={index}
                    onClick={() => handleSelectContact(contact)}
                    className={cn(
                      "flex items-center gap-4 p-3 rounded-xl border cursor-pointer transition-all",
                      selectedContact?.contact_numero === contact.contact_numero
                        ? "border-[#007E45] bg-green-50 dark:bg-green-900/20 ring-1 ring-[#007E45]"
                        : "border-gray-200 dark:border-gray-800 hover:border-gray-300 dark:hover:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-900"
                    )}
                  >
                    <div className={cn(
                      "w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold flex-shrink-0",
                      selectedContact?.contact_numero === contact.contact_numero 
                        ? "bg-[#007E45] text-white" 
                        : "bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400"
                    )}>
                      {contact.nom?.charAt(0)}{contact.prenom?.charAt(0)}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-gray-900 dark:text-white truncate">
                        {contact.nom} {contact.prenom}
                      </p>
                      <p className="text-xs text-gray-500 truncate">
                        {contact.email || 'Aucun email'}
                      </p>
                    </div>
                    {selectedContact?.contact_numero === contact.contact_numero && (
                      <div className="w-6 h-6 rounded-full bg-[#007E45] flex items-center justify-center">
                        <Check className="w-4 h-4 text-white" />
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </FormSection>
          )}

          {/* Séparateur OU */}
          {hasContacts && (
            <div className="flex items-center gap-4 my-2">
              <div className="flex-1 h-px bg-gray-200 dark:bg-gray-700" />
              <span className="text-sm text-gray-500 font-medium">OU</span>
              <div className="flex-1 h-px bg-gray-200 dark:bg-gray-700" />
            </div>
          )}

          {/* Section Saisie manuelle */}
          <FormSection 
            title={hasContacts ? "Saisir manuellement" : "Informations du signataire"}
            description={hasContacts 
              ? "Entrez les coordonnées d'un nouveau signataire" 
              : `Renseignez les coordonnées du signataire pour le devis de ${client?.intitule}`
            }
          >
            {hasContacts && !useManualEntry && !selectedContact && (
              <div className="col-span-2">
                <button
                  type="button"
                  onClick={handleManualEntry}
                  className="w-full flex items-center justify-center gap-2 p-4 rounded-xl border-2 border-dashed border-gray-200 dark:border-gray-700 hover:border-[#007E45] hover:bg-green-50 dark:hover:bg-green-900/10 transition-all text-gray-500 hover:text-[#007E45]"
                >
                  <Edit3 className="w-5 h-5" />
                  <span className="font-medium">Saisir un nouveau contact</span>
                </button>
              </div>
            )}

            {(useManualEntry || !hasContacts || selectedContact) && (
              <>
                <FormField label="Nom du signataire" required>
                  <div className="relative">
                    <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <input
                      type="text"
                      value={nomSignataire}
                      onChange={(e) => {
                        setNomSignataire(e.target.value);
                        if (selectedContact) setSelectedContact(null);
                      }}
                      placeholder="Nom complet du signataire"
                      className={cn(
                        "w-full pl-10 pr-4 text-sm  py-2.5 rounded-lg border bg-white dark:bg-gray-900 text-gray-900 dark:text-white placeholder-gray-400",
                        "focus:outline-none focus:ring-2 focus:ring-[#007E45] focus:border-transparent",
                        "border-gray-200 dark:border-gray-700"
                      )}
                    />
                  </div>
                </FormField>

                <FormField label="Email du signataire" required>
                  <div className="relative">
                    <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <input
                      type="email"
                      value={email}
                      onChange={(e) => {
                        setEmail(e.target.value);
                        if (selectedContact) setSelectedContact(null);
                      }}
                      placeholder="email@exemple.com"
                      className={cn(
                        "w-full pl-10 pr-4 py-2.5  text-sm rounded-lg border bg-white dark:bg-gray-900 text-gray-900 dark:text-white placeholder-gray-400",
                        "focus:outline-none focus:ring-2 focus:ring-[#007E45] focus:border-transparent",
                        email && !isValidEmail(email) 
                          ? "border-red-300 dark:border-red-700" 
                          : "border-gray-200 dark:border-gray-700"
                      )}
                    />
                  </div>
                  {email && !isValidEmail(email) && (
                    <p className="mt-1 text-xs text-red-500">Veuillez entrer un email valide</p>
                  )}
                </FormField>
              </>
            )}
          </FormSection>
        </>
      ) : (
        /* Step 2: Confirmation */
        <FormSection 
          title="Vérification avant envoi" 
          description="Confirmez les informations du signataire"
        >
          <div className="col-span-2 space-y-4">
            {/* Info banner */}
            <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-100 dark:border-blue-800 rounded-xl p-4 flex gap-4">
              <div className="w-10 h-10 bg-blue-100 dark:bg-blue-800 rounded-full flex items-center justify-center flex-shrink-0 text-blue-600 dark:text-blue-200">
                <Send className="w-5 h-5" />
              </div>
              <div>
                <h4 className="font-medium text-blue-900 dark:text-blue-100 mb-1">Prêt à envoyer</h4>
                <p className="text-sm text-blue-700 dark:text-blue-300">
                  Le devis <strong>{quote?.numero}</strong> sera envoyé par email pour signature électronique.
                </p>
              </div>
            </div>

            {/* Récapitulatif signataire */}
            <div className="bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-xl p-4">
              <div className="flex items-center gap-3 mb-4 pb-4 border-b border-gray-200 dark:border-gray-700">
                <div className="w-12 h-12 rounded-full bg-[#007E45] text-white flex items-center justify-center font-bold text-sm">
                  {nomSignataire.split(' ').map(n => n.charAt(0)).join('').slice(0, 2).toUpperCase()}
                </div>
                <div>
                  <p className="font-semibold text-gray-900 dark:text-white text-lg">{nomSignataire}</p>
                  <p className="text-sm text-gray-500">{client?.intitule}</p>
                </div>
              </div>
              
              <div className="space-y-3">
                <div className="flex items-center gap-3 text-sm">
                  <div className="w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-800 flex items-center justify-center">
                    <Mail className="w-4 h-4 text-gray-500" />
                  </div>
                  <div>
                    <p className="text-xs text-gray-500 uppercase tracking-wide">Email</p>
                    <p className="text-gray-900 dark:text-white font-medium">{email}</p>
                  </div>
                </div>
                
                {client?.telephone && (
                  <div className="flex items-center gap-3 text-sm">
                    <div className="w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-800 flex items-center justify-center">
                      <Phone className="w-4 h-4 text-gray-500" />
                    </div>
                    <div>
                      <p className="text-xs text-gray-500 uppercase tracking-wide">Téléphone</p>
                      <p className="text-gray-900 dark:text-white font-medium">{client.telephone}</p>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* Avertissement */}
            <p className="text-xs text-gray-500 text-center">
              En cliquant sur "Envoyer pour signature", un email sera envoyé au signataire avec un lien sécurisé pour signer le devis.
            </p>
          </div>
        </FormSection>
      )}
    </FormModal>
  );
};

export default ModalSendSignatureRequest;