import React, { useEffect, useMemo, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  X,
  Save,
  User,
  MapPin,
  Phone,
  Mail,
  Hash,
  Loader2,
  Briefcase,
  Globe,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Progress } from "@/components/ui/Progress";
import { Section } from "@/components/ui/Section";
import { InputField } from "@/components/ui/InputValidator";
import { toast } from "@/components/ui/use-toast";
import z from "zod";
import { useForm, Controller, type SubmitHandler } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Commercial } from "@/types/commercialType";

// ============================================
// SCHÉMA DE VALIDATION
// ============================================

const commercialSchema = z.object({
  numero: z.number().optional(),
  nom: z.string().min(1, "Le nom est requis"),
  prenom: z.string().min(1, "Le prénom est requis"),
  fonction: z.string().optional().or(z.literal("")),
  service: z.string().optional().or(z.literal("")),
  matricule: z.string().nullable().optional(),
  
  // Contact
  email: z.string().email("Email invalide").optional().or(z.literal("")),
  telephone: z.string().optional().or(z.literal("")),
  tel_portable: z.string().nullable().optional(),
  telecopie: z.string().nullable().optional(),
  
  // Adresse
  adresse: z.string().optional().or(z.literal("")),
  complement: z.string().nullable().optional(),
  code_postal: z.string().optional().or(z.literal("")),
  ville: z.string().optional().or(z.literal("")),
  region: z.string().nullable().optional(),
  pays: z.string().nullable().optional(),
  
  // Réseaux sociaux
  facebook: z.string().nullable().optional(),
  linkedin: z.string().nullable().optional(),
  skype: z.string().nullable().optional(),
  
  // Rôles
  est_vendeur: z.boolean().default(true),
  est_acheteur: z.boolean().default(false),
  est_caissier: z.boolean().default(false),
  est_chef_ventes: z.boolean().default(false),
  chef_ventes_numero: z.number().optional(),
  
  // Statut
  est_actif: z.boolean().default(true),
});

type CommercialFormData = z.infer<typeof commercialSchema>;

// ============================================
// TYPES
// ============================================

interface ModalCommercialProps {
  open: boolean;
  onClose: () => void;
  title?: string;
  editing?: Commercial | null;
}

// ============================================
// COMPOSANT PRINCIPAL
// ============================================

export function ModalCommercial({
  open,
  onClose,
  title,
  editing,
}: ModalCommercialProps) {
  const [completion, setCompletion] = useState(0);
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  const isEditing = !!editing;

  const {
    control,
    handleSubmit,
    watch,
    reset,
    formState: { errors },
  } = useForm<CommercialFormData>({
    resolver: zodResolver(commercialSchema),
    mode: "onChange",
    defaultValues: {
      numero: undefined,
      nom: "",
      prenom: "",
      fonction: "",
      service: "",
      matricule: "",
      email: "",
      telephone: "",
      tel_portable: "",
      telecopie: "",
      adresse: "",
      complement: "",
      code_postal: "",
      ville: "",
      region: "",
      pays: "France",
      facebook: "",
      linkedin: "",
      skype: "",
      est_vendeur: true,
      est_acheteur: false,
      est_caissier: false,
      est_chef_ventes: false,
      chef_ventes_numero: undefined,
      est_actif: true,
    },
  });

  const formValues = watch();

  // Reset form
  useEffect(() => {
    if (!open) return;
    
    if (editing) {
      reset({
        numero: editing.numero,
        nom: editing.nom || "",
        prenom: editing.prenom || "",
        fonction: editing.fonction || "",
        service: editing.service || "",
        matricule: editing.matricule || "",
        email: editing.email || "",
        telephone: editing.telephone || "",
        tel_portable: editing.tel_portable || "",
        telecopie: editing.telecopie || "",
        adresse: editing.adresse || "",
        complement: editing.complement || "",
        code_postal: editing.code_postal || "",
        ville: editing.ville || "",
        region: editing.region || "",
        pays: editing.pays || "France",
        facebook: editing.facebook || "",
        linkedin: editing.linkedin || "",
        skype: editing.skype || "",
        est_vendeur: editing.vendeur ?? true,
        est_acheteur: editing.acheteur ?? false,
        est_caissier: editing.caissier ?? false,
        est_chef_ventes: editing.chef_ventes ?? false,
        chef_ventes_numero: editing.chef_ventes_numero,
        est_actif: editing.est_actif ?? true,
      });
    } else {
      reset({
        numero: undefined,
        nom: "",
        prenom: "",
        fonction: "",
        service: "",
        matricule: "",
        email: "",
        telephone: "",
        tel_portable: "",
        telecopie: "",
        adresse: "",
        complement: "",
        code_postal: "",
        ville: "",
        region: "",
        pays: "France",
        facebook: "",
        linkedin: "",
        skype: "",
        est_vendeur: true,
        est_acheteur: false,
        est_caissier: false,
        est_chef_ventes: false,
        chef_ventes_numero: undefined,
        est_actif: true,
      });
    }
  }, [open, editing, reset]);

  // Calcul completion
  useEffect(() => {
    const requiredFields: (keyof CommercialFormData)[] = ["nom", "prenom", "email", "telephone"];
    const optionalFields: (keyof CommercialFormData)[] = ["fonction", "service", "adresse", "ville"];
    
    const filledRequired = requiredFields.filter((f) => !!formValues[f]);
    const filledOptional = optionalFields.filter((f) => !!formValues[f]);
    
    const completion = Math.round(
      ((filledRequired.length / requiredFields.length) * 70) +
      ((filledOptional.length / optionalFields.length) * 30)
    );
    setCompletion(completion);
  }, [formValues]);

  const canSave = useMemo(() => {
    return !!formValues.nom && !!formValues.prenom;
  }, [formValues.nom, formValues.prenom]);

  // Submit handler
  const onSave: SubmitHandler<CommercialFormData> = async (data) => {
    setIsSubmitting(true);
    
    try {
      if (isEditing) {
        // ✅ UPDATE - Console.log pour debug
        console.log("=== UPDATE COMMERCIAL ===");
        console.log("Numero:", editing?.numero);
        console.log("Data:", data);
        console.log("========================");
        
        // TODO: Implémenter le dispatch UPDATE ici
        // await dispatch(updateCommercial({ numero: editing.numero, data })).unwrap();
        
        toast({
          title: "Commercial mis à jour !",
          description: `${data.prenom} ${data.nom} a été mis à jour avec succès.`,
          className: "bg-green-500 text-white border-green-600",
        });
      } else {
        // ✅ CREATE - Console.log pour debug
        console.log("=== CREATE COMMERCIAL ===");
        console.log("Data:", data);
        console.log("=========================");
        
        // TODO: Implémenter le dispatch CREATE ici
        // await dispatch(addCommercial(data)).unwrap();
        
        toast({
          title: "Commercial créé !",
          description: `${data.prenom} ${data.nom} a été créé avec succès.`,
          className: "bg-green-500 text-white border-green-600",
        });
      }
      
      onClose();
    } catch (error) {
      console.error("Erreur:", error);
      toast({
        title: "Erreur",
        description: "Une erreur est survenue.",
        variant: "destructive",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const onError = (errors: any) => {
    console.log("Erreurs de validation:", errors);
  };

  if (!open) return null;

  return (
    <AnimatePresence>
      {open && (
        <>
          <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">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-[#007E45] text-white flex items-center justify-center">
                  <User className="w-5 h-5" />
                </div>
                <div>
                  <h2 className="text-lg font-bold text-gray-900 dark:text-white">
                    {title || (isEditing ? "Modifier le commercial" : "Nouveau commercial")}
                  </h2>
                  <p className="text-xs text-gray-500">{completion}% complété</p>
                </div>
              </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" />

            {/* Form */}
            <form
              onSubmit={handleSubmit(onSave, onError)}
              className="flex-1 flex flex-col overflow-hidden"
            >
              {/* Body scrollable */}
              <div className="flex-1 overflow-y-auto bg-gray-50/50 dark:bg-black/20">
                {/* Statut & Rôles */}
                <div className="p-4 border-b border-gray-100 dark:border-gray-800">
                  <div className="flex flex-wrap gap-4">
                    <Controller
                      name="est_actif"
                      control={control}
                      render={({ field }) => (
                        <label className="flex items-center gap-2 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={field.value}
                            onChange={(e) => field.onChange(e.target.checked)}
                            className="w-4 h-4 text-[#007E45] rounded border-gray-300 focus:ring-[#007E45]"
                          />
                          <span className="text-sm text-gray-700 dark:text-gray-300">Actif</span>
                        </label>
                      )}
                    />
                    <Controller
                      name="est_vendeur"
                      control={control}
                      render={({ field }) => (
                        <label className="flex items-center gap-2 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={field.value}
                            onChange={(e) => field.onChange(e.target.checked)}
                            className="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-600"
                          />
                          <span className="text-sm text-gray-700 dark:text-gray-300">Vendeur</span>
                        </label>
                      )}
                    />
                    <Controller
                      name="est_acheteur"
                      control={control}
                      render={({ field }) => (
                        <label className="flex items-center gap-2 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={field.value}
                            onChange={(e) => field.onChange(e.target.checked)}
                            className="w-4 h-4 text-purple-600 rounded border-gray-300 focus:ring-purple-600"
                          />
                          <span className="text-sm text-gray-700 dark:text-gray-300">Acheteur</span>
                        </label>
                      )}
                    />
                    <Controller
                      name="est_caissier"
                      control={control}
                      render={({ field }) => (
                        <label className="flex items-center gap-2 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={field.value}
                            onChange={(e) => field.onChange(e.target.checked)}
                            className="w-4 h-4 text-orange-500 rounded border-gray-300 focus:ring-orange-500"
                          />
                          <span className="text-sm text-gray-700 dark:text-gray-300">Caissier</span>
                        </label>
                      )}
                    />
                    <Controller
                      name="est_chef_ventes"
                      control={control}
                      render={({ field }) => (
                        <label className="flex items-center gap-2 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={field.value}
                            onChange={(e) => field.onChange(e.target.checked)}
                            className="w-4 h-4 text-yellow-500 rounded border-gray-300 focus:ring-yellow-500"
                          />
                          <span className="text-sm text-gray-700 dark:text-gray-300">Chef des ventes</span>
                        </label>
                      )}
                    />
                  </div>
                </div>

                {/* Section: Identification */}
                <Section title="Identification" icon={Hash} defaultOpen={true}>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <Controller
                      name="prenom"
                      control={control}
                      render={({ field }) => (
                        <InputField
                          {...field}
                          label="Prénom"
                          inputType="text"
                          required
                          placeholder="Jean"
                          error={errors.prenom?.message}
                        />
                      )}
                    />
                    <Controller
                      name="nom"
                      control={control}
                      render={({ field }) => (
                        <InputField
                          {...field}
                          label="Nom"
                          inputType="text"
                          required
                          placeholder="Dupont"
                          error={errors.nom?.message}
                        />
                      )}
                    />
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <Controller
                      name="fonction"
                      control={control}
                      render={({ field }) => (
                        <InputField
                          {...field}
                          label="Fonction"
                          inputType="text"
                          placeholder="Responsable commercial"
                        />
                      )}
                    />
                    <Controller
                      name="service"
                      control={control}
                      render={({ field }) => (
                        <InputField
                          {...field}
                          label="Service"
                          inputType="text"
                          placeholder="Commercial"
                        />
                      )}
                    />
                  </div>
                  <Controller
                    name="matricule"
                    control={control}
                    render={({ field }) => (
                      <InputField
                        {...field}
                        value={field.value || ""}
                        label="Matricule"
                        inputType="text"
                        placeholder="MAT001"
                      />
                    )}
                  />
                </Section>

                {/* Section: Contact */}
                <Section title="Contact" icon={Phone} defaultOpen={true}>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <Controller
                      name="email"
                      control={control}
                      render={({ field }) => (
                        <InputField
                          {...field}
                          label="Email"
                          inputType="email"
                          placeholder="jean.dupont@exemple.com"
                          error={errors.email?.message}
                          leftIcon={<Mail className="w-4 h-4" />}
                        />
                      )}
                    />
                    <Controller
                      name="telephone"
                      control={control}
                      render={({ field }) => (
                        <InputField
                          {...field}
                          label="Téléphone"
                          inputType="phone"
                          placeholder="01 23 45 67 89"
                          leftIcon={<Phone className="w-4 h-4" />}
                        />
                      )}
                    />
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <Controller
                      name="tel_portable"
                      control={control}
                      render={({ field }) => (
                        <InputField
                          {...field}
                          value={field.value || ""}
                          label="Portable"
                          inputType="phone"
                          placeholder="06 12 34 56 78"
                        />
                      )}
                    />
                    <Controller
                      name="telecopie"
                      control={control}
                      render={({ field }) => (
                        <InputField
                          {...field}
                          value={field.value || ""}
                          label="Fax"
                          inputType="text"
                          placeholder="01 23 45 67 90"
                        />
                      )}
                    />
                  </div>
                </Section>

                {/* Section: Adresse */}
                <Section title="Adresse" icon={MapPin} defaultOpen={false}>
                  <Controller
                    name="adresse"
                    control={control}
                    render={({ field }) => (
                      <InputField
                        {...field}
                        label="Adresse"
                        inputType="text"
                        placeholder="Numéro et nom de rue"
                      />
                    )}
                  />
                  <Controller
                    name="complement"
                    control={control}
                    render={({ field }) => (
                      <InputField
                        {...field}
                        value={field.value || ""}
                        label="Complément"
                        inputType="text"
                        placeholder="Bâtiment, étage..."
                      />
                    )}
                  />
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <Controller
                      name="code_postal"
                      control={control}
                      render={({ field }) => (
                        <InputField
                          {...field}
                          label="Code postal"
                          inputType="text"
                          placeholder="75001"
                        />
                      )}
                    />
                    <div className="md:col-span-2">
                      <Controller
                        name="ville"
                        control={control}
                        render={({ field }) => (
                          <InputField
                            {...field}
                            label="Ville"
                            inputType="text"
                            placeholder="Paris"
                          />
                        )}
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <Controller
                      name="region"
                      control={control}
                      render={({ field }) => (
                        <InputField
                          {...field}
                          value={field.value || ""}
                          label="Région"
                          inputType="text"
                          placeholder="Île-de-France"
                        />
                      )}
                    />
                    <Controller
                      name="pays"
                      control={control}
                      render={({ field }) => (
                        <InputField
                          {...field}
                          value={field.value || ""}
                          label="Pays"
                          inputType="text"
                          placeholder="France"
                        />
                      )}
                    />
                  </div>
                </Section>

                {/* Section: Réseaux sociaux */}
                <Section title="Réseaux sociaux" icon={Globe} defaultOpen={false}>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <Controller
                      name="linkedin"
                      control={control}
                      render={({ field }) => (
                        <InputField
                          {...field}
                          value={field.value || ""}
                          label="LinkedIn"
                          inputType="text"
                          placeholder="URL ou identifiant"
                        />
                      )}
                    />
                    <Controller
                      name="facebook"
                      control={control}
                      render={({ field }) => (
                        <InputField
                          {...field}
                          value={field.value || ""}
                          label="Facebook"
                          inputType="text"
                          placeholder="URL ou identifiant"
                        />
                      )}
                    />
                    <Controller
                      name="skype"
                      control={control}
                      render={({ field }) => (
                        <InputField
                          {...field}
                          value={field.value || ""}
                          label="Skype"
                          inputType="text"
                          placeholder="Identifiant Skype"
                        />
                      )}
                    />
                  </div>
                </Section>
              </div>

              {/* Footer */}
              <div className="p-4 border-t border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-950 flex justify-end gap-3">
                <button
                  type="button"
                  onClick={onClose}
                  className="px-4 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-xl transition-colors"
                >
                  Annuler
                </button>
                <button
                  type="submit"
                  disabled={!canSave || isSubmitting}
                  className={cn(
                    "inline-flex items-center gap-2 px-6 py-2.5 text-white text-sm font-medium rounded-xl shadow-lg shadow-emerald-900/20 transition-colors",
                    canSave && !isSubmitting
                      ? "bg-[#007E45] hover:bg-[#006838]"
                      : "bg-gray-400 cursor-not-allowed"
                  )}
                >
                  {isSubmitting ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <Save className="w-4 h-4" />
                  )}
                  {isEditing ? "Mettre à jour" : "Créer le commercial"}
                </button>
              </div>
            </form>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}

export default ModalCommercial;