import { type Salarie, type CPAM, type TypeCS, type MotifDerogationMutuelle, Arh } from "@/types/type";
import { formatAddress, formatIBAN, formatNSS, formatPhone, formatSingleLineAddress, formatDate, formatDateForInput } from "@/utils/formatter";
import { useParams } from "next/navigation";
import { useState, useEffect } from "react";


type EtatCivilProps = {
    salarie: Salarie | null;
};

const MUTUELLE_OPTIONS = [
    "Renonce",
    "Individuelle",
    "Salarié + 1",
    "Familiale",
];

function Field({
    label,
    value,
    onChange,
    readOnly = false,
    className = "",
    type = "text",
    max,
    min
}: {
    label: string;
    value?: string | number | null;
    onChange?: (value: string) => void;
    readOnly?: boolean;
    className?: string;
    type?: string;
    max?: string;
    min?: string;
}) {
    return (
        <div className={`grid grid-cols-[160px_1fr] items-center gap-2 ${className}`}>
            <label className="text-right text-xs font-semibold text-slate-700">
                {label}:
            </label>

            <input
                type={type}
                max={max}
                min={min}
                readOnly={readOnly}
                value={value ?? ""}
                onChange={(e) => onChange?.(e.target.value)}
                className="h-6 border border-slate-500 bg-sky-100 px-2 text-xs text-black"
            />
        </div>
    );
}
function calculateAge(date?: string | Date | null): string {
    if (!date) return "";

    const birthDate = new Date(date);
    const today = new Date();

    let age = today.getFullYear() - birthDate.getFullYear();

    const monthDiff = today.getMonth() - birthDate.getMonth();

    if (
        monthDiff < 0 ||
        (monthDiff === 0 && today.getDate() < birthDate.getDate())
    ) {
        age--;
    }

    return `${age} ans`;
}



export default function EtatCivil({ salarie }: EtatCivilProps) {
    const [form, setForm] = useState<Salarie | null>(null);
    const [savedSnapshot, setSavedSnapshot] = useState<Salarie | null>(null);
    const [cpams, setCpams] = useState<CPAM[]>([]);
    const [motifDerogationMutuelles, setMotifDerogationMutuelles] = useState<MotifDerogationMutuelle[]>([]);
    const [typecs, setTypeCS] = useState<TypeCS[]>([]);
    const [cisps, setCisps] = useState<Arh[]>([]);
    const [villes, setVilles] = useState<string[]>([]);
    const [loadingVilles, setLoadingVilles] = useState(false);

    const mutuelleValue = Number(form?.Mutuelle ?? 0);
    const derogationDisabled = mutuelleValue !== 0;

    const selectedCpam = cpams.find(
        cpam => cpam.adresse === form?.ADRCPAM
    );

    const selectedCisp = cisps.find(
        cisp => cisp.nom === form?.ARH
    )

    const selectedMotifDerogationMutulle = motifDerogationMutuelles.find(
        motifDerogationMutuelle => motifDerogationMutuelle.motifsderogation === form?.MotifDerogationMutuelle
    );

    useEffect(() => {
        async function fetchCpams() {
            const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/cpam`);
            const data = await res.json();
            setCpams(data.items);
        }

        fetchCpams();
    }, []);

     useEffect(() => {
        async function fetchCisps() {
            const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/arh`);
            const data = await res.json();
            setCisps(data.items);
        }

        fetchCisps();
    }, []);


    useEffect(() => {
        async function fetchMotifsDerogationMutuelle() {
            const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/motifs-derogation-mutuelle`);
            const data = await res.json();
            setMotifDerogationMutuelles(data.items);
        }

        fetchMotifsDerogationMutuelle();
    }, []);

    useEffect(() => {
        async function fetchTypeCS() {
            const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/types-cs`)
            const data = await res.json();
            console.log("TYPECS DATA =", data);
            console.log("TYPECS ITEMS =", data.items);
            setTypeCS(Array.isArray(data.items) ? data.items : []);
        }
        fetchTypeCS();
    }, [])

    useEffect(() => {
        console.log("SET FORM", salarie);

        setForm(salarie);
        setSavedSnapshot(salarie);
    }, [salarie]);

    const isDirty = JSON.stringify(form) !== JSON.stringify(savedSnapshot);

    function updateField<K extends keyof Salarie>(
        field: K,
        value: Salarie[K]
    ) {
        setForm((prev) => {
            if (!prev) return prev;

            return {
                ...prev,
                [field]: value,
            };
        });
    }

    async function handleSave() {
        if (!form) return;

        const token = localStorage.getItem("token");

        const response = await fetch(
            `${process.env.NEXT_PUBLIC_API_URL}/api/employes/${form.COS}`,
            {
                method: "PUT",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${token}`,
                },
                body: JSON.stringify(form),
            }
        );

        const data = await response.json().catch(() => null);

        if (!response.ok) {
            alert(data?.message ?? data?.error ?? "Erreur lors de la sauvegarde");
            return;
        }

        const updatedEmploye = data?.employe ?? form;

        setForm(updatedEmploye);
        setSavedSnapshot(updatedEmploye);

        alert("Employé mis à jour");
    }
    async function handleCodePostalChange(value: string) {
        updateField("COP", value);

        if (value.length !== 5) {
            setVilles([]);
            return;
        }

        setLoadingVilles(true);

        try {
            const res = await fetch(
                `https://geo.api.gouv.fr/communes?codePostal=${value}&fields=nom&format=json`
            );

            if (!res.ok) {
                throw new Error("Erreur API communes");
            }

            const data = await res.json();
            const noms = data.map((commune: { nom: string }) => commune.nom);

            setVilles(noms);

            if (noms.length === 1) {
                updateField("VIL", noms[0]);
            } else {
                updateField("VIL", "");
            }
        } catch (error) {
            console.error("Impossible de récupérer les villes", error);
            setVilles([]);
        } finally {
            setLoadingVilles(false);
        }
    }
    return (
        <div className="h-full overflow-hidden bg-white p-4 text-xs text-black">
            <div className="mb-3 flex justify-end gap-2">
                {isDirty && (
                    <>
                        <button
                            type="button"
                            onClick={() => setForm(salarie)}
                            className="rounded border border-slate-400 bg-white px-3 py-1 text-xs"
                        >
                            Annuler
                        </button>

                        <button
                            type="button"
                            onClick={handleSave}
                            className="rounded bg-blue-600 px-3 py-1 text-xs font-semibold text-white"
                        >
                            Enregistrer
                        </button>
                    </>
                )}
            </div>
            <div className="grid grid-cols-2 gap-12">
                <section className="space-y-2">
                    <div className="grid grid-cols-[160px_1fr_80px_1fr] items-center gap-2">
                        <label className="text-right text-xs font-semibold text-slate-700">
                            Code salarié:
                        </label>
                        <input
                            readOnly
                            value={salarie?.COS ?? ""}
                            className="h-6 border border-slate-500 bg-sky-100 px-2 text-xs text-black"
                        />

                        <label className="text-right text-xs font-semibold text-slate-700">
                            Matricule:
                        </label>
                        <input
                            readOnly
                            value={salarie?.Matricule ?? ""}
                            className="h-6 border border-slate-500 bg-sky-100 px-2 text-xs text-black"
                        />
                    </div>
                    <div className="grid grid-cols-[160px_1fr] items-center gap-2">
                        <label className="text-right text-xs font-semibold text-slate-700">
                            Civilité:
                        </label>

                        <select
                            value={form?.TIT ?? ""}
                            onChange={(e) => updateField("TIT", e.target.value)}
                            className="h-6 border border-slate-500 bg-sky-100 px-2 text-xs text-black"
                        >
                            <option value="Monsieur">Monsieur</option>
                            <option value="Madame">Madame</option>
                        </select>
                    </div>
                    <Field
                        label="Nom"
                        value={form?.NSA}
                        onChange={(value) => updateField("NSA", value)}
                    />

                    <Field
                        label="Prénom"
                        value={form?.PRE}
                        onChange={(value) => updateField("PRE", value)}
                    />

                    <Field
                        label="Nom de jeune fille"
                        value={form?.NJF}
                        onChange={(value) => updateField("NJF", value)}
                    />

                    <div className="grid grid-cols-[160px_1fr_auto] items-center gap-2">
                        <label className="text-right text-xs font-semibold text-slate-700">
                            Date de naissance:
                        </label>

                        <input
                            type="date"
                            max={new Date().toISOString().split("T")[0]}
                            value={formatDateForInput(form?.DAN)}
                            onChange={(e) => updateField("DAN", e.target.value)}
                            className="h-6 border border-slate-500 bg-sky-100 px-2 text-xs text-black"
                        />

                        <span className="w-12 text-xs text-slate-700">
                            {calculateAge(form?.DAN)}
                        </span>
                    </div>
                    <Field
                        label="Lieu de naissance"
                        value={form?.LNA}
                        onChange={(value) => updateField("LNA", value)}
                    />
                    <Field
                        label="Nationalité"
                        value={form?.NAT}
                        onChange={(value) => updateField("NAT", value)}
                    />

                    <div className="grid grid-cols-[160px_1fr] items-start gap-2">
                        <label className="text-right text-xs font-semibold text-slate-700">
                            Adresse:
                        </label>

                        <textarea
                            value={(form?.ADR ?? "")
                                .replace(/\\r\\n/g, "\n")
                                .replace(/\\n/g, "\n")}
                            onChange={(e) => updateField("ADR", e.target.value)}
                            rows={2}
                            className="border border-slate-500 bg-sky-100 px-2 py-1 text-xs text-black resize-none"
                        />
                    </div>
                    <div className="grid grid-cols-[160px_90px_40px_1fr] items-center gap-2">
                        <label className="text-right text-xs font-semibold text-slate-700">
                            Code postal:
                        </label>

                        <input
                            value={form?.COP ?? ""}
                            onChange={(e) => handleCodePostalChange(e.target.value)}
                            className="h-6 border border-slate-500 bg-sky-100 px-2 text-xs text-black"
                        />

                        <span className="text-right text-xs font-semibold text-slate-700">
                            Ville:
                        </span>

                        <select
                            value={form?.VIL ?? ""}
                            onChange={(e) => updateField("VIL", e.target.value)}
                            disabled={loadingVilles}
                            className="h-6 w-full border border-slate-500 bg-sky-100 px-2 text-xs text-black"
                        >
                            <option value="">
                                {loadingVilles ? "Chargement..." : "Sélectionner une ville"}
                            </option>

                            {form?.VIL && !villes.includes(form.VIL) && (
                                <option value={form.VIL}>{form.VIL}</option>
                            )}

                            {villes.map((ville) => (
                                <option key={ville} value={ville}>
                                    {ville}
                                </option>
                            ))}
                        </select>
                    </div>

                    <div className="grid grid-cols-[160px_1fr_80px_1fr] items-center gap-2">
                        <label className="text-right text-xs font-semibold text-slate-700">
                            Téléphone:
                        </label>
                        <input readOnly value={formatPhone(salarie?.TEL)} className="h-6 border border-slate-500 bg-sky-100 px-2 text-xs text-black" />

                        <label className="text-right text-xs font-semibold text-slate-700">
                            Portable:
                        </label>
                        <input readOnly value={formatPhone(salarie?.GSM)} className="h-6 border border-slate-500 bg-sky-100 px-2 text-xs text-black" />
                    </div>

                    <Field
                        label="Mail Perso"
                        value={form?.EmailPerso}
                        onChange={(value) => updateField("EmailPerso", value)}
                    />
                    <Field
                        label="Mail E2e"
                        value={form?.EmailE2e}
                        onChange={(value) => updateField("EmailE2e", value)}
                    />
                    <div className="grid grid-cols-[160px_1fr] items-center gap-2">
                        <label className="text-right text-xs font-semibold text-slate-700">
                            Type Titre séjour:
                        </label>

                        <select
                            value={form?.TypeCS ?? ""}
                            onChange={(e) => updateField("TypeCS", e.target.value)}
                            className="h-6 w-full border border-slate-500 bg-sky-100 px-2 text-xs text-black"
                        >
                            <option value="">Sélectionner un type de carte de séjour</option>

                            {typecs.map((item) => (
                                <option key={item.id} value={item.typecs ?? ""}>
                                    {item.typecs}
                                </option>
                            ))}
                        </select>
                    </div>
                    <Field
                        label="N°CS"
                        value={form?.NCJ}
                        onChange={(value) => updateField("NCJ", value)}
                    />
                    <Field
                        label="Expiration CS"
                        type="date"
                        min={new Date().toISOString().split("T")[0]}
                        value={
                            form?.EXJ
                                ? String(form.EXJ).slice(0, 10)
                                : ""
                        }
                        onChange={(value) => updateField("EXJ", value)}
                    />
                    <div className="grid grid-cols-[160px_1fr] items-center gap-2">
                        <label className="text-right text-xs font-semibold text-slate-700">
                            CISP:
                        </label>
                        <select
                                value={selectedCisp?.nom ?? form?.ARH ?? ""}
                                onChange={(e) => updateField("ARH", e.target.value)}
                                className="h-6 w-full border border-slate-500 bg-sky-100 px-2 text-xs text-black"
                            >
                                <option value="">Sélectionner un CISP</option>

                                {cisps.map((cisp) => (
                                    <option
                                        key={cisp.id}
                                        value={cisp.nom ?? ""}
                                    >
                                        {cisp.nom}
                                    </option>
                                ))}
                            </select>
                    </div>
                    <Field
                        label="Date d'entrée Groupe"
                        type="date"
                        max={new Date().toISOString().split("T")[0]}
                        value={
                            form?.DateEntreeGroupe
                                ? String(form.DateEntreeGroupe).slice(0, 10)
                                : ""
                        }
                        onChange={(value) => updateField("DateEntreeGroupe", value)}
                    />
                </section>

                <section className="space-y-6">
                    <Field label="N° SS" value={formatNSS(salarie?.NSS)} />

                    <fieldset className="border border-slate-400 p-3">
                        <legend className="px-2 text-sm font-semibold">
                            CPAM et Cotorep
                        </legend>

                        <div className="space-y-2">
                            <select
                                value={selectedCpam?.adresse ?? form?.ADRCPAM ?? ""}
                                onChange={(e) => updateField("ADRCPAM", e.target.value)}
                                className="h-6 w-full border border-slate-500 bg-sky-100 px-2 text-xs text-black"
                            >
                                <option value="">Sélectionner une CPAM</option>

                                {cpams.map((cpam) => (
                                    <option
                                        key={cpam.id}
                                        value={cpam.adresse ?? ""}
                                    >
                                        {cpam.localite}
                                        {cpam.adresse ? ` - ${cpam.adresse}` : ""}
                                    </option>
                                ))}
                            </select>

                            <div className="grid grid-cols-[150px_1fr] gap-2">
                                <div className="flex items-center gap-2">
                                    <input
                                        type="checkbox"
                                        checked={Boolean(form?.Cotorep)}
                                        onChange={(e) =>
                                            updateField("Cotorep", e.target.checked)
                                        }
                                    />
                                    <label className="text-xs font-semibold">
                                        MDPH
                                    </label>
                                </div>

                                <Field
                                    label=" Date fin attestation"
                                    type="date"
                                    min={new Date().toISOString().split("T")[0]}
                                    value={
                                        form?.FinCotorep
                                            ? String(form.FinCotorep).slice(0, 10)
                                            : ""
                                    }
                                    onChange={(value) => updateField("FinCotorep", value)}
                                />
                            </div>
                        </div>
                    </fieldset>
                    <Field
                        label="Date Fin CMU"
                        type="date"
                        min={new Date().toISOString().split("T")[0]}
                        value={
                            form?.DateFinCMU
                                ? String(form.DateFinCMU).slice(0, 10)
                                : ""
                        }
                        onChange={(value) => updateField("DateFinCMU", value)}
                    />
                    <fieldset className="border border-slate-400 p-3">
                        <legend className="px-2 text-sm font-semibold">
                            Mutuelle
                        </legend>

                        <div className="mb-3 grid grid-cols-4 gap-2">
                            {MUTUELLE_OPTIONS.map((option, index) => (
                                <button
                                    key={option}
                                    type="button"
                                    onClick={() => {
                                        updateField("Mutuelle", index);
                                    }}
                                    className={`h-7 border px-3 text-xs ${Number(form?.Mutuelle ?? 0) === index
                                            ? "border-slate-600 bg-slate-300 font-semibold text-black"
                                            : "border-slate-400 bg-slate-100 text-slate-700 hover:bg-slate-200"
                                        }`}
                                >
                                    {option}
                                </button>
                            ))}
                        </div>

                        <div className="grid grid-cols-[120px_1fr] items-center gap-2">
                            <label className="text-right text-xs font-semibold text-slate-700">
                                Dérogation :
                            </label>

                            <select
                                disabled={Number(form?.Mutuelle ?? 0) !== 0}
                                value={
                                    selectedMotifDerogationMutulle?.motifsderogation ??
                                    form?.MotifDerogationMutuelle ??
                                    ""
                                }
                                onChange={(e) =>
                                    updateField("MotifDerogationMutuelle", e.target.value)
                                }
                                className={`h-6 w-full border border-slate-500 px-2 text-xs text-black ${Number(form?.Mutuelle ?? 0) !== 0
                                        ? "cursor-not-allowed bg-slate-300"
                                        : "bg-sky-100"
                                    }`}
                            >
                                <option value="">Sélectionner une dérogation</option>

                                {motifDerogationMutuelles.map((motifDerogationMutuelle) => (
                                    <option
                                        key={motifDerogationMutuelle.id}
                                        value={motifDerogationMutuelle.motifsderogation ?? ""}
                                    >
                                        {motifDerogationMutuelle.motifsderogation}
                                    </option>
                                ))}
                            </select>
                        </div>

                        <div className="mt-2 grid grid-cols-[120px_1fr] items-center gap-2">
                            <label className="text-right text-xs font-semibold text-slate-700">
                                Date de fin :
                            </label>

                            <input
                                type="date"
                                disabled={Number(form?.Mutuelle ?? 0) !== 0}
                                value={
                                    form?.DateFinDerogationMutuelle
                                        ? String(form.DateFinDerogationMutuelle).slice(0, 10)
                                        : ""
                                }
                                onChange={(e) =>
                                    updateField("DateFinDerogationMutuelle", e.target.value)
                                }
                                className={`h-6 border border-slate-500 px-2 text-xs text-black ${Number(form?.Mutuelle ?? 0) !== 0
                                        ? "cursor-not-allowed bg-slate-300"
                                        : "bg-sky-100"
                                    }`}
                            />
                        </div>
                    </fieldset>

                    <Field
                        label="IBAN"
                        value={formatIBAN(form?.IBAN)}
                        onChange={(value) => updateField("IBAN", value)}
                    />

                </section>
            </div>
            <div className="mt-4 flex items-start justify-center gap-24">
                {/* Urgence */}
                <fieldset className="w-[420px] border border-red-500 bg-red-200 p-3">
                    <legend className="px-2 font-bold text-red-700">URGENCE</legend>

                    <div className="space-y-1">
                        <div className="grid grid-cols-[50px_1fr_35px_1fr] items-center gap-2">
                            <label className="text-xs font-bold">Nom:</label>
                            <input
                                value={form?.PersonnelAppelUrgence1 ?? ""}
                                onChange={(e) =>
                                    updateField("PersonnelAppelUrgence1", e.target.value)
                                }
                                className="h-6 border border-slate-500 bg-sky-100 px-2 text-xs font-bold text-red-600"
                            />

                            <label className="text-xs font-bold">Tél:</label>
                            <input
                                value={formatPhone(form?.TelAppelUrgence1 ?? "")}
                                onChange={(e) =>
                                    updateField("TelAppelUrgence1", e.target.value)
                                }
                                className="h-6 border border-slate-500 bg-sky-100 px-2 text-xs font-bold text-red-600"
                            />
                        </div>

                        <div className="grid grid-cols-[50px_1fr_35px_1fr] items-center gap-2">
                            <label className="text-xs font-bold">Nom:</label>
                            <input
                                value={form?.PersonnelAppelUrgence2 ?? ""}
                                onChange={(e) =>
                                    updateField("PersonnelAppelUrgence2", e.target.value)
                                }
                                className="h-6 border border-slate-500 bg-sky-100 px-2 text-xs text-black"
                            />

                            <label className="text-xs font-bold">Tél:</label>
                            <input
                                value={formatPhone(form?.TelAppelUrgence2 ?? "")}
                                onChange={(e) =>
                                    updateField("TelAppelUrgence2", e.target.value)
                                }
                                className="h-6 border border-slate-500 bg-sky-100 px-2 text-xs text-black"
                            />
                        </div>

                        <div className="grid grid-cols-[50px_1fr_35px_1fr] items-center gap-2">
                            <label className="text-xs font-bold">Nom:</label>
                            <input
                                value={form?.PersonnelAppelUrgence3 ?? ""}
                                onChange={(e) =>
                                    updateField("PersonnelAppelUrgence3", e.target.value)
                                }
                                className="h-6 border border-slate-500 bg-sky-100 px-2 text-xs text-black"
                            />

                            <label className="text-xs font-bold">Tél:</label>
                            <input
                                value={formatPhone(form?.TelAppelUrgence3 ?? "")}
                                onChange={(e) =>
                                    updateField("TelAppelUrgence3", e.target.value)
                                }
                                className="h-6 border border-slate-500 bg-sky-100 px-2 text-xs text-black"
                            />
                        </div>
                    </div>
                </fieldset>


                {/* Adresse mise en forme */}
                <div className="w-[430px] -mt-4 space-y-1">
                    <p className="text-xs font-semibold">Adresses Mise en forme:</p>

                    <textarea
                        readOnly
                        value={formatAddress(salarie)}
                        className="h-20 w-full resize-none border border-slate-600 bg-white p-1 text-xs text-black"
                    />

                    <input
                        readOnly
                        value={formatSingleLineAddress(salarie)}
                        className="h-7 w-full border border-slate-600 bg-white px-1 text-xs text-black"
                    />
                </div>
            </div>
        </div>
    );
}