
import React, { useState, useEffect } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  X, ChevronDown, ChevronUp, CheckCircle2, AlertCircle, 
  Save, Building2, MapPin, Wallet, Zap, Shield, 
  Loader2
} from 'lucide-react';
import { toast } from '@/components/ui/use-toast';
import { Switch } from '@/components/ui/switch';
import { Progress } from '@/components/ui/progress';
import { cn } from '@/lib/utils';
import { mockUsers } from '@/data/mockData';

// --- Schema Validation ---
const clientSchema = z.object({
  type: z.enum(['entreprise', 'particulier']),
  name: z.string().min(2, "Le nom est requis"),
  companyName: z.string().optional(),
  siret: z.string().optional(),
  category: z.string().optional(),
  origin: z.string().optional(),
  assignedTo: z.string().optional(),
  address1: z.string().min(5, "L'adresse est requise"),
  address2: z.string().optional(),
  zipCode: z.string().min(4, "Code postal requis"),
  city: z.string().min(2, "Ville requise"),
  country: z.string().default('France'),
  civility: z.string().optional(),
  contactName: z.string().min(2, "Nom requis"),
  contactFirstName: z.string().min(2, "Prénom requis"),
  email: z.string().email("Email invalide"),
  phone: z.string().min(10, "Numéro invalide"),
  contactPref: z.enum(['email', 'phone', 'sms', 'whatsapp']).default('email'),
  legalForm: z.string().optional(),
  employees: z.string().optional(),
  revenue: z.string().optional(),
  sector: z.string().optional(),
  website: z.string().url("URL invalide").optional().or(z.literal('')),
  paymentMethod: z.string().optional(),
  paymentTerm: z.string().optional(),
  interestLevel: z.enum(['low', 'medium', 'high']).default('medium'),
  urgency: z.string().optional(),
  budget: z.string().optional(),
  notes: z.string().optional(),
  autoOpportunity: z.boolean().default(false),
  autoTask: z.boolean().default(false),
  sendWelcome: z.boolean().default(false),
  autoAssign: z.boolean().default(false),
  visibility: z.enum(['me', 'team', 'all']).default('team'),
}).refine((data) => {
  if (data.type === 'entreprise' && !data.companyName) return false;
  return true;
}, {
  message: "Raison sociale requise",
  path: ["companyName"],
});

// --- Internal Components ---

const Section = ({ title, icon: Icon, children, defaultOpen = true, error }) => {
  const [isOpen, setIsOpen] = useState(defaultOpen);
  return (
    <div className={cn("border-b border-gray-100 dark:border-gray-800 last:border-0", error && "bg-red-50/30 dark:bg-red-900/10")}>
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="w-full flex items-center justify-between p-4 hover:bg-gray-50 dark:hover:bg-gray-900/50 transition-colors text-left"
      >
        <div className="flex items-center gap-3">
          <Icon className={cn("w-4 h-4", error ? "text-red-500" : "text-gray-500")} />
          <span className={cn("font-semibold text-sm", error ? "text-red-600" : "text-gray-900 dark:text-white")}>
            {title}
          </span>
        </div>
        {isOpen ? <ChevronUp className="w-4 h-4 text-gray-400" /> : <ChevronDown className="w-4 h-4 text-gray-400" />}
      </button>
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            className="overflow-hidden"
          >
            <div className="p-4 pt-0 space-y-4">
              {children}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};

const InputGroup = ({ label, error, required, children, className }) => (
  <div className={cn("space-y-1.5", className)}>
    <div className="flex justify-between">
      <label className="text-xs font-medium text-gray-700 dark:text-gray-300">
        {label} {required && <span className="text-[#941403]">*</span>}
      </label>
      {error && <span className="text-[10px] text-red-500 font-medium">{error.message}</span>}
    </div>
    <div className="relative">
      {children}
      {!error && required && children?.props?.value && (
        <CheckCircle2 className="absolute right-3 top-1/2 -translate-y-1/2 w-3 h-3 text-green-500 pointer-events-none" />
      )}
      {error && (
        <AlertCircle className="absolute right-3 top-1/2 -translate-y-1/2 w-3 h-3 text-red-500 pointer-events-none" />
      )}
    </div>
  </div>
);

const ClientFormModal = ({ isOpen, onClose, initialData = null }) => {
  const [isLoading, setIsLoading] = useState(false);
  const [completion, setCompletion] = useState(0);

  const { register, handleSubmit, watch, control, formState: { errors, isValid }, reset } = useForm({
    resolver: zodResolver(clientSchema),
    mode: "onChange",
    defaultValues: {
      type: 'entreprise',
      contactPref: 'email',
      country: 'France',
      visibility: 'team',
      ...initialData
    }
  });

  useEffect(() => {
    if (isOpen) {
      if (initialData) reset(initialData);
      else reset({
        type: 'entreprise',
        contactPref: 'email',
        country: 'France',
        visibility: 'team'
      });
    }
  }, [isOpen, initialData, reset]);

  const watchAll = watch();
  const type = watch('type');

  useEffect(() => {
    const requiredFields = ['name', 'address1', 'zipCode', 'city', 'contactName', 'contactFirstName', 'email', 'phone'];
    if (type === 'entreprise') requiredFields.push('companyName');
    const filled = requiredFields.filter(field => !!watchAll[field]);
    setCompletion(Math.round((filled.length / requiredFields.length) * 100));
  }, [watchAll, type]);

  const onSubmit = async (data) => {
    setIsLoading(true);
    await new Promise(resolve => setTimeout(resolve, 1500));
    console.log(data);
    toast({
      title: initialData ? "Client modifié" : "Client créé",
      description: `${data.name} a été ${initialData ? "mis à jour" : "ajouté"} avec succès.`,
      variant: "success"
    });
    setIsLoading(false);
    onClose();
  };

  const inputClass = (error) => cn(
    "w-full px-3 py-2 bg-white dark:bg-gray-950 border rounded-lg text-sm shadow-sm transition-all focus:outline-none focus:ring-2 pr-8",
    error 
      ? "border-red-300 focus:border-red-500 focus:ring-red-200" 
      : "border-gray-200 dark:border-gray-800 focus:border-[#941403] focus:ring-red-100/50"
  );

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
            className="fixed inset-0 bg-black/40 backdrop-blur-sm z-50"
          />
          <motion.div
            initial={{ x: "100%" }}
            animate={{ x: 0 }}
            exit={{ x: "100%" }}
            transition={{ type: "spring", damping: 25, stiffness: 200 }}
            className="fixed inset-y-0 right-0 w-full max-w-xl bg-white dark:bg-gray-950 shadow-2xl z-50 flex flex-col border-l border-gray-200 dark:border-gray-800"
          >
            {/* Header */}
            <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-white/80 dark:bg-gray-950/80 backdrop-blur-md z-10">
              <div>
                <h2 className="text-lg font-bold text-gray-900 dark:text-white">
                  {initialData ? "Modifier le client" : "Nouveau client"}
                </h2>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  {completion}% complété
                </p>
              </div>
              <button 
                onClick={onClose}
                className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors"
              >
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>
            <Progress value={completion} className="h-1 rounded-none" />

            {/* Body */}
            <div className="flex-1 overflow-y-auto custom-scrollbar bg-gray-50/50 dark:bg-black/20">
              <form id="client-form" onSubmit={handleSubmit(onSubmit)} className="pb-6">
                
                <Section title="Informations Générales" icon={Building2} error={errors.name || errors.companyName}>
                  <div className="flex gap-2 mb-4">
                    {['entreprise', 'particulier'].map((val) => (
                      <label key={val} className={cn(
                        "flex-1 flex items-center justify-center py-2 rounded-lg border cursor-pointer text-xs font-medium transition-colors",
                        type === val 
                          ? "bg-[#941403] text-white border-[#941403]" 
                          : "bg-white dark:bg-gray-900 text-gray-600 border-gray-200 dark:border-gray-800"
                      )}>
                        <input type="radio" value={val} {...register('type')} className="hidden" />
                        <span className="capitalize">{val}</span>
                      </label>
                    ))}
                  </div>

                  <div className="space-y-3">
                    <InputGroup label="Nom du client" error={errors.name} required>
                      <input {...register('name')} className={inputClass(errors.name)} placeholder="Nom d'affichage" />
                    </InputGroup>

                    {type === 'entreprise' && (
                      <InputGroup label="Raison sociale" error={errors.companyName} required>
                        <input {...register('companyName')} className={inputClass(errors.companyName)} placeholder="Raison sociale officielle" />
                      </InputGroup>
                    )}

                    <div className="grid grid-cols-2 gap-3">
                      <InputGroup label="SIRET" error={errors.siret}>
                        <input {...register('siret')} className={inputClass(errors.siret)} placeholder="14 chiffres" />
                      </InputGroup>
                      <InputGroup label="Catégorie">
                        <select {...register('category')} className={inputClass()}>
                          <option value="standard">Standard</option>
                          <option value="premium">Premium</option>
                          <option value="vip">VIP</option>
                        </select>
                      </InputGroup>
                    </div>

                    <InputGroup label="Commercial">
                      <select {...register('assignedTo')} className={inputClass()}>
                        <option value="">Sélectionner...</option>
                        {mockUsers.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
                      </select>
                    </InputGroup>
                  </div>
                </Section>

                <Section title="Coordonnées" icon={MapPin} error={errors.address1 || errors.zipCode || errors.city || errors.email}>
                  <div className="space-y-3">
                    <InputGroup label="Adresse" error={errors.address1} required>
                      <input {...register('address1')} className={inputClass(errors.address1)} />
                    </InputGroup>
                    <div className="grid grid-cols-2 gap-3">
                      <InputGroup label="Code Postal" error={errors.zipCode} required>
                        <input {...register('zipCode')} className={inputClass(errors.zipCode)} />
                      </InputGroup>
                      <InputGroup label="Ville" error={errors.city} required>
                        <input {...register('city')} className={inputClass(errors.city)} />
                      </InputGroup>
                    </div>

                    <div className="pt-2 border-t border-gray-100 dark:border-gray-800 mt-2"></div>

                    <div className="grid grid-cols-3 gap-3">
                      <InputGroup label="Civilité">
                        <select {...register('civility')} className={inputClass()}>
                          <option value="M.">M.</option>
                          <option value="Mme">Mme</option>
                        </select>
                      </InputGroup>
                      <InputGroup label="Prénom" className="col-span-2" error={errors.contactFirstName} required>
                        <input {...register('contactFirstName')} className={inputClass(errors.contactFirstName)} />
                      </InputGroup>
                    </div>
                    <InputGroup label="Nom" error={errors.contactName} required>
                      <input {...register('contactName')} className={inputClass(errors.contactName)} />
                    </InputGroup>
                    <div className="grid grid-cols-2 gap-3">
                      <InputGroup label="Email" error={errors.email} required>
                        <input {...register('email')} className={inputClass(errors.email)} />
                      </InputGroup>
                      <InputGroup label="Téléphone" error={errors.phone} required>
                        <input {...register('phone')} className={inputClass(errors.phone)} />
                      </InputGroup>
                    </div>
                  </div>
                </Section>

                {type === 'entreprise' && (
                  <Section title="Entreprise" icon={Building2} defaultOpen={false}>
                    <div className="grid grid-cols-2 gap-3">
                      <InputGroup label="Forme Juridique">
                        <select {...register('legalForm')} className={inputClass()}>
                          <option value="">Sélectionner...</option>
                          <option value="SARL">SARL</option>
                          <option value="SAS">SAS</option>
                        </select>
                      </InputGroup>
                      <InputGroup label="Effectif">
                        <select {...register('employees')} className={inputClass()}>
                          <option value="1-10">1-10</option>
                          <option value="11-50">11-50</option>
                          <option value="50+">50+</option>
                        </select>
                      </InputGroup>
                      <InputGroup label="CA (€)">
                         <input {...register('revenue')} className={inputClass()} />
                      </InputGroup>
                      <InputGroup label="Site Web" error={errors.website}>
                         <input {...register('website')} className={inputClass(errors.website)} />
                      </InputGroup>
                    </div>
                  </Section>
                )}

                <Section title="Comptabilité" icon={Wallet} defaultOpen={false}>
                  <div className="space-y-3">
                    <InputGroup label="Mode de règlement">
                       <select {...register('paymentMethod')} className={inputClass()}>
                         <option value="virement">Virement</option>
                         <option value="cb">Carte Bancaire</option>
                         <option value="cheque">Chèque</option>
                       </select>
                    </InputGroup>
                    <InputGroup label="Délai de paiement">
                       <select {...register('paymentTerm')} className={inputClass()}>
                         <option value="30">30 jours</option>
                         <option value="45">45 jours</option>
                         <option value="60">60 jours</option>
                       </select>
                    </InputGroup>
                  </div>
                </Section>

                <Section title="Automatisations" icon={Zap} defaultOpen={false}>
                  <div className="space-y-3">
                    <div className="flex items-center justify-between p-3 bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800">
                      <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Accès portail client</span>
                      <Controller name="sendWelcome" control={control} render={({ field }) => <Switch checked={field.value} onCheckedChange={field.onChange} />} />
                    </div>
                  </div>
                </Section>

                <Section title="Permissions" icon={Shield} defaultOpen={false}>
                   <div className="space-y-2">
                      {[
                        { val: 'me', label: 'Moi uniquement' },
                        { val: 'team', label: 'Mon équipe commerciale' },
                        { val: 'all', label: 'Toute l\'entreprise' }
                      ].map(opt => (
                        <label key={opt.val} className="flex items-center gap-3 p-3 border rounded-xl cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-900/50 dark:border-gray-800">
                           <input type="radio" value={opt.val} {...register('visibility')} className="w-4 h-4 text-[#941403]" />
                           <span className="text-sm font-medium text-gray-700 dark:text-gray-300">{opt.label}</span>
                        </label>
                      ))}
                   </div>
                </Section>

              </form>
            </div>

            {/* Footer */}
            <div className="p-4 border-t border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-950 z-10 flex justify-end gap-3">
               <button
                 type="button"
                 onClick={onClose}
                 className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
               >
                 Annuler
               </button>
               <button
                 form="client-form"
                 type="submit"
                 disabled={isLoading || !isValid}
                 className="inline-flex items-center gap-2 px-6 py-2 bg-[#941403] text-white text-sm font-medium rounded-lg hover:bg-[#7a1002] disabled:opacity-50 disabled:cursor-not-allowed transition-colors shadow-lg shadow-red-900/20"
               >
                 {isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                 {initialData ? "Mettre à jour" : "Créer le client"}
               </button>
            </div>

          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
};

export default ClientFormModal;
