import { useEffect, useMemo } from 'react';
import { useForm, Controller, type SubmitHandler } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import FormModal from '@/components/ui/FormModal';
import { cn } from '@/lib/utils';
import { Client, Contacts } from '@/types/clientType';
import { Fournisseur } from '@/types/fournisseurType';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { addContactClient, addContactFournisseur, updateContactClient, updateContactFournisseur } from '@/store/features/contact/thunk';
import { toast } from '../ui/use-toast';
import { contactStatus } from '@/store/features/contact/selectors';
import { getClientSelected } from '@/store/features/client/selectors';
import { getfournisseurSelected } from '@/store/features/fournisseur/selectors';
import { InternationalPhoneInput } from '../ui/InternationalPhoneInput';

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

const contactSchema = z.object({
  numero: z.string().optional().or(z.literal("")),
  civilite: z.string().optional().or(z.literal("")),
  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_code: z.number().optional(),
  telephone: z.string().optional().or(z.literal("")),
  portable: z.string().optional().or(z.literal("")),
  telecopie: z.string().optional().or(z.literal("")),
  email: z
    .string()
    .refine(
      (val) => !val || val.trim() === "" || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val),
      { message: "Format email invalide" }
    )
    .optional()
    .or(z.literal("")),
  facebook: z.string().optional().or(z.literal("")),
  linkedin: z.string().optional().or(z.literal("")),
  skype: z.string().optional().or(z.literal("")),
  est_defaut: z.boolean().default(false),
});

export type ContactFormData = z.infer<typeof contactSchema>;

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

type EntityType = 'client' | 'fournisseur';

interface ModalContactProps {
  open: boolean;
  onClose: () => void;
  title?: string;
  editing?: Contacts | null;
  entityType: EntityType;
}

// ============================================
// OPTIONS
// ============================================

const CIVILITE_OPTIONS = [
  { value: "", label: "-- Sélectionner --" },
  { value: "M.", label: "M." },
  { value: "Mme", label: "Mme" },
];

const SERVICE_OPTIONS = [
  { value: undefined, label: "-- Sélectionner --" },
  { value: 1, label: "Direction" },
  { value: 2, label: "Commercial" },
  { value: 3, label: "Achats" },
  { value: 4, label: "Comptabilité" },
  { value: 5, label: "Technique" },
  { value: 6, label: "SAV" },
  { value: 7, label: "RH" },
  { value: 8, label: "Logistique" },
];

// ============================================
// LABELS PAR TYPE D'ENTITÉ
// ============================================

const ENTITY_LABELS: Record<EntityType, { singular: string; addTitle: string; editTitle: string }> = {
  client: {
    singular: "client",
    addTitle: "Ajouter un contact",
    editTitle: "Modifier le contact",
  },
  fournisseur: {
    singular: "fournisseur",
    addTitle: "Ajouter un contact",
    editTitle: "Modifier le contact",
  },
};

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

export function ModalContact({
  open,
  onClose,
  title,
  editing,
  entityType,
}: ModalContactProps) {
  const isEditing = !!editing;
  const dispatch = useAppDispatch();
  const statusContact = useAppSelector(contactStatus);

  // Sélectionner l'entité selon le type
  const client = useAppSelector(getClientSelected) as Client | null;
  const fournisseur = useAppSelector(getfournisseurSelected) as Fournisseur | null;

  // Récupérer le numéro selon le type d'entité
  const entityNumero = useMemo(() => {
    if (entityType === 'client') {
      return client?.numero || "";
    }
    return fournisseur?.numero || "";
  }, [entityType, client, fournisseur]);

  const labels = ENTITY_LABELS[entityType];

  const {
    control,
    handleSubmit,
    reset,
    watch,
    formState: { errors },
  } = useForm<ContactFormData>({
    resolver: zodResolver(contactSchema),
    mode: "onChange",
    defaultValues: {
      numero: entityNumero,
      civilite: "",
      nom: "",
      prenom: "",
      fonction: "",
      service_code: undefined,
      telephone: "",
      portable: "",
      telecopie: "",
      email: "",
      facebook: "",
      linkedin: "",
      skype: "",
      est_defaut: false,
    },
  });

  const nom = watch("nom");
  const prenom = watch("prenom");

  // Reset form quand le contact est chargé ou modal ouverte
  useEffect(() => {
    if (open) {
      if (isEditing && editing) {
        reset({
          numero: entityNumero,
          civilite: editing.civilite || "",
          nom: editing.nom || "",
          prenom: editing.prenom || "",
          fonction: editing.fonction || "",
          service_code: editing.service_code || undefined,
          telephone: editing.telephone || "",
          portable: editing.portable || "",
          telecopie: editing.telecopie || "",
          email: editing.email || "",
          facebook: editing.facebook || "",
          linkedin: editing.linkedin || "",
          skype: editing.skype || "",
          est_defaut: editing.est_defaut ?? false,
        });
      } else {
        reset({
          numero: entityNumero,
          civilite: "",
          nom: "",
          prenom: "",
          fonction: "",
          service_code: undefined,
          telephone: "",
          portable: "",
          telecopie: "",
          email: "",
          facebook: "",
          linkedin: "",
          skype: "",
          est_defaut: false,
        });
      }
    }
  }, [editing, isEditing, reset, open, entityNumero]);

  const canSave = useMemo(() => {
    const hasNom = !!nom && nom.trim().length > 0;
    const hasPrenom = !!prenom && prenom.trim().length > 0;
    const hasNoErrors = Object.keys(errors).length === 0;
    return hasNom && hasPrenom && hasNoErrors;
  }, [nom, prenom, errors]);

  const onSubmit: SubmitHandler<ContactFormData> = async (data) => {
    try {
      if (editing) {
        const res = entityType === "client" 
        ? (await dispatch(updateContactClient({contact_numero: editing.contact_numero,data,})).unwrap()) as Contacts
        : (await dispatch(updateContactFournisseur({contact_numero: editing.contact_numero,data,})).unwrap()) as Contacts;
        toast({
          title: "Contact mis à jour avec succès !",
          description: `Le contact a été modifié pour le ${labels.singular} ${res.numero}.`,
          className: "bg-green-500 text-white border-green-600",
        });
        onClose();
      } else {
        const res = entityType === "client" 
            ? (await dispatch(addContactClient(data)).unwrap()) as Contacts
            : (await dispatch(addContactFournisseur(data)).unwrap()) as Contacts;

        toast({
          title: "Contact ajouté avec succès !",
          description: `Un nouveau contact a été ajouté au ${labels.singular} ${res.numero}.`,
          className: "bg-green-500 text-white border-green-600",
        });
        onClose();
      }
    } catch (error) {
      toast({
        title: "Erreur",
        description: "Une erreur est survenue lors de l'enregistrement.",
        variant: "destructive",
      });
      onClose();
    }
  };

  const inputClass = (error?: unknown) =>
    cn(
      "w-full px-3 py-2.5 bg-white dark:bg-gray-900 border rounded-xl text-sm transition-all focus:outline-none focus:ring-2 focus:ring-[#338660]/20 focus:border-[#338660]",
      error
        ? "border-red-300 focus:border-red-500 focus:ring-red-200"
        : "border-gray-200 dark:border-gray-700"
    );

  const selectClass = cn(
    "w-full px-3 py-2.5 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-xl text-sm transition-all focus:outline-none focus:ring-2 focus:ring-[#338660]/20 focus:border-[#338660]"
  );

  if (!open) return null;

  return (
    <FormModal
      isOpen={open}
      onClose={onClose}
      title={title || (isEditing ? labels.editTitle : labels.addTitle)}
      onSubmit={handleSubmit(onSubmit)}
      submitLabel={isEditing ? "Enregistrer" : "Ajouter"}
      size="md"
      loading={statusContact === "loading"}
    >
      <div className="space-y-4">
        {/* Civilité */}
        <Controller
          name="civilite"
          control={control}
          render={({ field }) => (
            <div className="space-y-1.5">
              <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Civilité
              </label>
              <select {...field} className={selectClass}>
                {CIVILITE_OPTIONS.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>
          )}
        />

        {/* Nom & Prénom */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <Controller
            name="prenom"
            control={control}
            render={({ field }) => (
              <div className="space-y-1.5">
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Prénom <span className="text-red-500">*</span>
                </label>
                <input
                  {...field}
                  placeholder="Pierre"
                  className={inputClass(errors.prenom)}
                />
                {errors.prenom && (
                  <p className="text-xs text-red-500">{errors.prenom.message}</p>
                )}
              </div>
            )}
          />
          <Controller
            name="nom"
            control={control}
            render={({ field }) => (
              <div className="space-y-1.5">
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Nom <span className="text-red-500">*</span>
                </label>
                <input
                  {...field}
                  placeholder="Martin"
                  className={inputClass(errors.nom)}
                />
                {errors.nom && (
                  <p className="text-xs text-red-500">{errors.nom.message}</p>
                )}
              </div>
            )}
          />
        </div>

        {/* Fonction & Service */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <Controller
            name="fonction"
            control={control}
            render={({ field }) => (
              <div className="space-y-1.5">
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Fonction
                </label>
                <input
                  {...field}
                  placeholder="Directeur des Ventes"
                  className={inputClass()}
                />
              </div>
            )}
          />
          <Controller
            name="service_code"
            control={control}
            render={({ field }) => (
              <div className="space-y-1.5">
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Service
                </label>
                <select
                  value={field.value ?? ""}
                  onChange={(e) => {
                    const val = e.target.value;
                    field.onChange(val === "" ? undefined : parseInt(val));
                  }}
                  className={selectClass}
                >
                  {SERVICE_OPTIONS.map((opt) => (
                    <option key={opt.value ?? "empty"} value={opt.value ?? ""}>
                      {opt.label}
                    </option>
                  ))}
                </select>
              </div>
            )}
          />
        </div>

        {/* Email & Téléphone */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <Controller
            name="email"
            control={control}
            render={({ field }) => (
              <div className="space-y-1.5">
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Email
                </label>
                <input
                  {...field}
                  type="email"
                  placeholder="p.martin@exemple.com"
                  className={inputClass(errors.email)}
                />
                {errors.email && (
                  <p className="text-xs text-red-500">{errors.email.message}</p>
                )}
              </div>
            )}
          />
          {/* <Controller
            name="telephone"
            control={control}
            render={({ field }) => (
              <div className="space-y-1.5">
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Téléphone fixe
                </label>
                <input
                  {...field}
                  type="tel"
                  placeholder="01 23 45 67 89"
                  className={inputClass()}
                />
              </div>
            )}
          /> */}
          <Controller
            name="telephone"
            control={control}
            render={({ field, fieldState }) => (
                <InternationalPhoneInput
                {...field}
                label="Téléphone"
                error={fieldState.error?.message}
                required={false}
                defaultCountry="FR" 
                />
            )}
        />
        </div>

        {/* Portable & Télécopie */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* <Controller
            name="portable"
            control={control}
            render={({ field }) => (
              <div className="space-y-1.5">
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Portable
                </label>
                <input
                  {...field}
                  type="tel"
                  placeholder="06 12 34 56 78"
                  className={inputClass()}
                />
              </div>
            )}
          /> */}
          <Controller
            name="portable"
            control={control}
            render={({ field, fieldState }) => (
                <InternationalPhoneInput
                {...field}
                label="Portable"
                error={fieldState.error?.message}
                required={false}
                defaultCountry="FR" // ou "MG" pour Madagascar
                />
            )}
        />
          <Controller
            name="telecopie"
            control={control}
            render={({ field }) => (
              <div className="space-y-1.5">
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Télécopie (Fax)
                </label>
                <input
                  {...field}
                  type="tel"
                  placeholder="01 23 45 67 90"
                  className={inputClass()}
                />
              </div>
            )}
          />
        </div>

        {/* Réseaux sociaux */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <Controller
            name="linkedin"
            control={control}
            render={({ field }) => (
              <div className="space-y-1.5">
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  LinkedIn
                </label>
                <input
                  {...field}
                  placeholder="URL ou identifiant"
                  className={inputClass()}
                />
              </div>
            )}
          />
          {/* <Controller
            name="facebook"
            control={control}
            render={({ field }) => (
              <div className="space-y-1.5">
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Facebook
                </label>
                <input
                  {...field}
                  placeholder="URL ou identifiant"
                  className={inputClass()}
                />
              </div>
            )}
          />
          <Controller
            name="skype"
            control={control}
            render={({ field }) => (
              <div className="space-y-1.5">
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Skype
                </label>
                <input
                  {...field}
                  placeholder="Identifiant Skype"
                  className={inputClass()}
                />
              </div>
            )}
          /> */}
        </div>

        {/* Contact par défaut */}
        <div className="pt-2">
          <Controller
            name="est_defaut"
            control={control}
            render={({ field }) => (
              <label className="flex items-center gap-3 p-3 border border-gray-200 dark:border-gray-800 rounded-xl cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-900/50 transition-colors">
                <input
                  type="checkbox"
                  checked={field.value || false}
                  onChange={(e) => field.onChange(e.target.checked)}
                  className="w-4 h-4 text-[#338660] rounded border-gray-300 focus:ring-[#338660]"
                />
                <div>
                  <p className="text-sm font-medium text-gray-900 dark:text-white">
                    Définir comme contact par défaut
                  </p>
                  <p className="text-xs text-gray-500">
                    Ce contact sera utilisé pour les envois automatiques
                  </p>
                </div>
              </label>
            )}
          />
        </div>
      </div>
    </FormModal>
  );
}

export default ModalContact;