"use client";

import { useEditMode } from "@/context/EditModeContext";
import { useState, useEffect, useCallback } from "react";
import { X, Save, Loader2 } from "lucide-react";

type FormData = Record<string, string>;

function getApis(sectionId: string): { fetchUrl: string; saveUrl: string; collectionId?: string } | null {
  if (["hero", "president-quote", "map-stats", "partners-header", "bottom-cta"].includes(sectionId)) {
    return { fetchUrl: "/api/site-settings", saveUrl: "/api/admin/site-settings" };
  }
  if (sectionId === "about") {
    return { fetchUrl: "/api/about", saveUrl: "/api/admin/about" };
  }
  if (sectionId === "president-message") {
    return { fetchUrl: "/api/president-message", saveUrl: "/api/admin/president-message" };
  }
  if (sectionId.startsWith("mission-")) {
    return { fetchUrl: "/api/mission-content", saveUrl: "/api/admin/mission-content" };
  }
  if (sectionId.startsWith("value-")) {
    return { fetchUrl: "/api/core-values", saveUrl: "/api/admin/core-values", collectionId: sectionId.slice(6) };
  }
  if (sectionId.startsWith("domain-")) {
    return { fetchUrl: "/api/domains", saveUrl: "/api/admin/domains", collectionId: sectionId.slice(7) };
  }
  if (sectionId.startsWith("timeline-")) {
    return { fetchUrl: "/api/timeline", saveUrl: "/api/admin/timeline", collectionId: sectionId.slice(9) };
  }
  return null;
}

const inputClass = "w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#4A7C59]/40 focus:border-[#4A7C59] bg-white";
const labelClass = "block text-xs font-semibold text-gray-600 mb-1.5 uppercase tracking-wide";
const fieldClass = "mb-4";
const sectionTitleClass = "text-xs font-bold text-gray-400 uppercase tracking-widest mb-3 mt-5 first:mt-0 pb-1 border-b border-gray-100";
const hintClass = "text-[11px] text-gray-400 mt-1";

export function EditDrawer() {
  const { drawerSection, drawerLabel, closeDrawer, refreshContent } = useEditMode();
  const [formData, setFormData] = useState<FormData>({});
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!drawerSection) return;
    const apis = getApis(drawerSection);
    if (!apis) return;

    setLoading(true);
    setError(null);

    fetch(apis.fetchUrl)
      .then((r) => r.json())
      .then((data) => {
        if (apis.collectionId) {
          const item = Array.isArray(data) ? data.find((d: FormData) => d.id === apis.collectionId) : null;
          setFormData(item ? { ...item } : {});
        } else {
          setFormData(data ? { ...data } : {});
        }
        setLoading(false);
      })
      .catch(() => {
        setError("Erreur lors du chargement");
        setLoading(false);
      });
  }, [drawerSection]);

  const handleChange = useCallback((field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  }, []);

  const handleSave = async () => {
    if (!drawerSection) return;
    const apis = getApis(drawerSection);
    if (!apis) return;

    setSaving(true);
    setError(null);

    try {
      const body = apis.collectionId ? { id: apis.collectionId, ...formData } : formData;
      const res = await fetch(apis.saveUrl, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });

      if (!res.ok) throw new Error("Erreur de sauvegarde");
      refreshContent();
      closeDrawer();
    } catch {
      setError("Erreur lors de la sauvegarde. Vérifiez que vous êtes connecté.");
    } finally {
      setSaving(false);
    }
  };

  if (!drawerSection) return null;

  return (
    <>
      <div className="fixed inset-0 bg-black/40 z-40 backdrop-blur-sm" onClick={closeDrawer} />

      <div className="fixed right-0 top-0 bottom-12 w-full sm:w-[480px] bg-white z-50 shadow-2xl flex flex-col">
        <div className="flex items-center justify-between px-5 py-4 border-b border-gray-100 bg-[#2C3E50] flex-shrink-0">
          <h2 className="text-white font-semibold text-sm">{drawerLabel}</h2>
          <button onClick={closeDrawer} className="text-white/60 hover:text-white transition-colors p-1 rounded">
            <X size={18} />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto p-5">
          {loading ? (
            <div className="flex items-center justify-center py-20">
              <Loader2 className="animate-spin text-gray-400" size={24} />
            </div>
          ) : (
            <>
              {/* ── HERO ────────────────────────────── */}
              {drawerSection === "hero" && (
                <div>
                  <p className={sectionTitleClass}>Texte du héros</p>
                  <div className={fieldClass}>
                    <label className={labelClass}>Titre principal</label>
                    <input className={inputClass} value={formData.heroTitle || ""} onChange={(e) => handleChange("heroTitle", e.target.value)} />
                    <p className={hintClass}>Entourez un mot de **astérisques** pour le mettre en surbrillance jaune</p>
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Sous-titre</label>
                    <textarea rows={3} className={inputClass} value={formData.heroSubtitle || ""} onChange={(e) => handleChange("heroSubtitle", e.target.value)} />
                    <p className={hintClass}>Supporté : **texte** pour mettre en surbrillance</p>
                  </div>
                  <p className={sectionTitleClass}>Boutons d'action</p>
                  <div className="grid grid-cols-2 gap-3 mb-4">
                    <div>
                      <label className={labelClass}>Bouton 1 — Texte</label>
                      <input className={inputClass} value={formData.heroCta1Text || ""} onChange={(e) => handleChange("heroCta1Text", e.target.value)} />
                    </div>
                    <div>
                      <label className={labelClass}>Bouton 1 — Lien</label>
                      <input className={inputClass} value={formData.heroCta1Link || ""} onChange={(e) => handleChange("heroCta1Link", e.target.value)} />
                    </div>
                    <div>
                      <label className={labelClass}>Bouton 2 — Texte</label>
                      <input className={inputClass} value={formData.heroCta2Text || ""} onChange={(e) => handleChange("heroCta2Text", e.target.value)} />
                    </div>
                    <div>
                      <label className={labelClass}>Bouton 2 — Lien</label>
                      <input className={inputClass} value={formData.heroCta2Link || ""} onChange={(e) => handleChange("heroCta2Link", e.target.value)} />
                    </div>
                  </div>
                </div>
              )}

              {/* ── ABOUT ───────────────────────────── */}
              {drawerSection === "about" && (
                <div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Titre de section</label>
                    <input className={inputClass} value={formData.title || ""} onChange={(e) => handleChange("title", e.target.value)} />
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Description</label>
                    <textarea rows={4} className={inputClass} value={formData.description || ""} onChange={(e) => handleChange("description", e.target.value)} />
                  </div>
                  <p className={sectionTitleClass}>Statistiques</p>
                  {[
                    { vKey: "stat1Value", lKey: "stat1Label", n: "1" },
                    { vKey: "stat2Value", lKey: "stat2Label", n: "2" },
                    { vKey: "stat3Value", lKey: "stat3Label", n: "3" },
                  ].map(({ vKey, lKey, n }) => (
                    <div key={n} className="grid grid-cols-2 gap-3 mb-3">
                      <div>
                        <label className={labelClass}>Stat {n} — Valeur</label>
                        <input className={inputClass} value={formData[vKey] || ""} onChange={(e) => handleChange(vKey, e.target.value)} />
                      </div>
                      <div>
                        <label className={labelClass}>Stat {n} — Libellé</label>
                        <input className={inputClass} value={formData[lKey] || ""} onChange={(e) => handleChange(lKey, e.target.value)} />
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* ── PRESIDENT MESSAGE PAGE ──────────── */}
              {drawerSection === "president-message" && (
                <div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Nom</label>
                    <input className={inputClass} value={formData.presidentName || ""} onChange={(e) => handleChange("presidentName", e.target.value)} />
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Titre / Fonction</label>
                    <input className={inputClass} value={formData.presidentTitle || ""} onChange={(e) => handleChange("presidentTitle", e.target.value)} />
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Texte d'introduction</label>
                    <textarea rows={3} className={inputClass} value={formData.introText || ""} onChange={(e) => handleChange("introText", e.target.value)} />
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Message complet</label>
                    <textarea rows={14} className={inputClass} value={formData.message || ""} onChange={(e) => handleChange("message", e.target.value)} />
                    <p className={hintClass}>Séparez les paragraphes par une ligne vide.</p>
                  </div>
                </div>
              )}

              {/* ── PRESIDENT QUOTE ─────────────────── */}
              {drawerSection === "president-quote" && (
                <div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Citation de la Présidente</label>
                    <textarea rows={5} className={inputClass} value={formData.presidentQuote || ""} onChange={(e) => handleChange("presidentQuote", e.target.value)} />
                    <p className={hintClass}>Cette citation apparaît en page d'accueil et peut renvoyer vers la page du message complet.</p>
                  </div>
                </div>
              )}

              {/* ── MAP STATS ───────────────────────── */}
              {drawerSection === "map-stats" && (
                <div>
                  <p className={sectionTitleClass}>Statistiques de la carte</p>
                  {[
                    { vKey: "mapStat1", lKey: "mapStat1Label", n: "1" },
                    { vKey: "mapStat2", lKey: "mapStat2Label", n: "2" },
                    { vKey: "mapStat3", lKey: "mapStat3Label", n: "3" },
                    { vKey: "mapStat4", lKey: "mapStat4Label", n: "4" },
                  ].map(({ vKey, lKey, n }) => (
                    <div key={n} className="grid grid-cols-2 gap-3 mb-3">
                      <div>
                        <label className={labelClass}>Stat {n} — Valeur</label>
                        <input className={inputClass} value={formData[vKey] || ""} onChange={(e) => handleChange(vKey, e.target.value)} />
                      </div>
                      <div>
                        <label className={labelClass}>Stat {n} — Libellé</label>
                        <input className={inputClass} value={formData[lKey] || ""} onChange={(e) => handleChange(lKey, e.target.value)} />
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* ── PARTNERS HEADER ─────────────────── */}
              {drawerSection === "partners-header" && (
                <div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Titre de la section</label>
                    <input className={inputClass} value={formData.partnersSectionTitle || ""} onChange={(e) => handleChange("partnersSectionTitle", e.target.value)} />
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Sous-titre</label>
                    <textarea rows={2} className={inputClass} value={formData.partnersSectionSubtitle || ""} onChange={(e) => handleChange("partnersSectionSubtitle", e.target.value)} />
                  </div>
                  <p className={sectionTitleClass}>Badges réseaux</p>
                  <div className={fieldClass}>
                    <label className={labelClass}>Badge réseau 1</label>
                    <input className={inputClass} value={formData.networkBadge1 || ""} onChange={(e) => handleChange("networkBadge1", e.target.value)} />
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Badge réseau 2</label>
                    <input className={inputClass} value={formData.networkBadge2 || ""} onChange={(e) => handleChange("networkBadge2", e.target.value)} />
                  </div>
                </div>
              )}

              {/* ── BOTTOM CTA ──────────────────────── */}
              {drawerSection === "bottom-cta" && (
                <div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Titre</label>
                    <textarea rows={2} className={inputClass} value={formData.bottomCtaTitle || ""} onChange={(e) => handleChange("bottomCtaTitle", e.target.value)} />
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Description</label>
                    <textarea rows={3} className={inputClass} value={formData.bottomCtaDescription || ""} onChange={(e) => handleChange("bottomCtaDescription", e.target.value)} />
                  </div>
                  <p className={sectionTitleClass}>Statistiques de bas de page</p>
                  {[
                    { vKey: "bottomStat1", lKey: "bottomStat1Label", n: "1" },
                    { vKey: "bottomStat2", lKey: "bottomStat2Label", n: "2" },
                    { vKey: "bottomStat3", lKey: "bottomStat3Label", n: "3" },
                  ].map(({ vKey, lKey, n }) => (
                    <div key={n} className="grid grid-cols-2 gap-3 mb-3">
                      <div>
                        <label className={labelClass}>Stat {n} — Valeur</label>
                        <input className={inputClass} value={formData[vKey] || ""} onChange={(e) => handleChange(vKey, e.target.value)} />
                      </div>
                      <div>
                        <label className={labelClass}>Stat {n} — Libellé</label>
                        <input className={inputClass} value={formData[lKey] || ""} onChange={(e) => handleChange(lKey, e.target.value)} />
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* ── CORE VALUE ──────────────────────── */}
              {drawerSection.startsWith("value-") && (
                <div>
                  <div className="grid grid-cols-2 gap-3 mb-4">
                    <div>
                      <label className={labelClass}>Numéro</label>
                      <input className={inputClass} value={formData.number || ""} onChange={(e) => handleChange("number", e.target.value)} placeholder="01" />
                    </div>
                    <div>
                      <label className={labelClass}>Ordre d'affichage</label>
                      <input type="number" className={inputClass} value={formData.order || ""} onChange={(e) => handleChange("order", e.target.value)} />
                    </div>
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Nom de la valeur</label>
                    <input className={inputClass} value={formData.name || ""} onChange={(e) => handleChange("name", e.target.value)} />
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Description</label>
                    <textarea rows={4} className={inputClass} value={formData.description || ""} onChange={(e) => handleChange("description", e.target.value)} />
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Couleur</label>
                    <div className="flex items-center gap-3">
                      <input type="color" className="h-9 w-14 rounded border border-gray-200 cursor-pointer p-0.5" value={formData.color || "#4A7C59"} onChange={(e) => handleChange("color", e.target.value)} />
                      <input className={`${inputClass} flex-1`} value={formData.color || ""} onChange={(e) => handleChange("color", e.target.value)} placeholder="#4A7C59" />
                    </div>
                  </div>
                </div>
              )}

              {/* ── MISSION HERO ────────────────────── */}
              {drawerSection === "mission-hero" && (
                <div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Titre de la page</label>
                    <input className={inputClass} value={formData.pageTitle || ""} onChange={(e) => handleChange("pageTitle", e.target.value)} />
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Sous-titre</label>
                    <textarea rows={3} className={inputClass} value={formData.pageSubtitle || ""} onChange={(e) => handleChange("pageSubtitle", e.target.value)} />
                  </div>
                  {/* <div className={fieldClass}>
                    <label className={labelClass}>Image de fond (chemin)</label>
                    <input className={inputClass} value={formData.heroImage || ""} onChange={(e) => handleChange("heroImage", e.target.value)} placeholder="/mission&vision.jpg" />
                  </div> */}
                </div>
              )}

              {/* ── MISSION STATS ───────────────────── */}
              {drawerSection === "mission-stats" && (
                <div>
                  <p className={sectionTitleClass}>4 statistiques de la page Mission</p>
                  {[
                    { vKey: "stat1Value", lKey: "stat1Label", n: "1" },
                    { vKey: "stat2Value", lKey: "stat2Label", n: "2" },
                    { vKey: "stat3Value", lKey: "stat3Label", n: "3" },
                    { vKey: "stat4Value", lKey: "stat4Label", n: "4" },
                  ].map(({ vKey, lKey, n }) => (
                    <div key={n} className="grid grid-cols-2 gap-3 mb-3">
                      <div>
                        <label className={labelClass}>Stat {n} — Valeur</label>
                        <input className={inputClass} value={formData[vKey] || ""} onChange={(e) => handleChange(vKey, e.target.value)} />
                      </div>
                      <div>
                        <label className={labelClass}>Stat {n} — Libellé</label>
                        <input className={inputClass} value={formData[lKey] || ""} onChange={(e) => handleChange(lKey, e.target.value)} />
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* ── MISSION & VISION TEXT ───────────── */}
              {drawerSection === "mission-vision" && (
                <div>
                  <p className={sectionTitleClass}>Mission</p>
                  <div className={fieldClass}>
                    <label className={labelClass}>Titre</label>
                    <input className={inputClass} value={formData.missionTitle || ""} onChange={(e) => handleChange("missionTitle", e.target.value)} />
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Texte</label>
                    <textarea rows={5} className={inputClass} value={formData.missionText || ""} onChange={(e) => handleChange("missionText", e.target.value)} />
                  </div>
                  <p className={sectionTitleClass}>Vision</p>
                  <div className={fieldClass}>
                    <label className={labelClass}>Titre</label>
                    <input className={inputClass} value={formData.visionTitle || ""} onChange={(e) => handleChange("visionTitle", e.target.value)} />
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Texte</label>
                    <textarea rows={5} className={inputClass} value={formData.visionText || ""} onChange={(e) => handleChange("visionText", e.target.value)} />
                  </div>
                </div>
              )}

              {/* ── MISSION CTA ─────────────────────── */}
              {drawerSection === "mission-cta" && (
                <div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Titre</label>
                    <textarea rows={2} className={inputClass} value={formData.ctaTitle || ""} onChange={(e) => handleChange("ctaTitle", e.target.value)} />
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Description</label>
                    <textarea rows={4} className={inputClass} value={formData.ctaDescription || ""} onChange={(e) => handleChange("ctaDescription", e.target.value)} />
                  </div>
                </div>
              )}

              {/* ── DOMAIN ──────────────────────────── */}
              {drawerSection.startsWith("domain-") && (
                <div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Nom du domaine</label>
                    <input className={inputClass} value={formData.name || ""} onChange={(e) => handleChange("name", e.target.value)} />
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Description</label>
                    <textarea rows={4} className={inputClass} value={formData.description || ""} onChange={(e) => handleChange("description", e.target.value)} />
                  </div>
                  <div className="grid grid-cols-2 gap-3 mb-4">
                    <div>
                      <label className={labelClass}>Couleur</label>
                      <div className="flex items-center gap-2">
                        <input type="color" className="h-9 w-10 rounded border border-gray-200 cursor-pointer p-0.5" value={formData.color || "#4A7C59"} onChange={(e) => handleChange("color", e.target.value)} />
                        <input className={`${inputClass} flex-1`} value={formData.color || ""} onChange={(e) => handleChange("color", e.target.value)} />
                      </div>
                    </div>
                    <div>
                      <label className={labelClass}>Ordre</label>
                      <input type="number" className={inputClass} value={formData.order || ""} onChange={(e) => handleChange("order", e.target.value)} />
                    </div>
                  </div>
                </div>
              )}

              {/* ── TIMELINE EVENT ──────────────────── */}
              {drawerSection.startsWith("timeline-") && (
                <div>
                  <div className="grid grid-cols-2 gap-3 mb-4">
                    <div>
                      <label className={labelClass}>Année</label>
                      <input className={inputClass} value={formData.year || ""} onChange={(e) => handleChange("year", e.target.value)} placeholder="2024" />
                    </div>
                    <div>
                      <label className={labelClass}>Ordre</label>
                      <input type="number" className={inputClass} value={formData.order || ""} onChange={(e) => handleChange("order", e.target.value)} />
                    </div>
                  </div>
                  <div className={fieldClass}>
                    <label className={labelClass}>Événement</label>
                    <textarea rows={4} className={inputClass} value={formData.text || ""} onChange={(e) => handleChange("text", e.target.value)} />
                  </div>
                </div>
              )}
            </>
          )}
        </div>

        <div className="px-5 py-4 border-t border-gray-100 bg-gray-50 flex-shrink-0">
          {error && <p className="text-red-500 text-xs mb-3">{error}</p>}
          <div className="flex gap-3">
            <button onClick={closeDrawer} className="flex-1 px-4 py-2.5 text-sm text-gray-600 border border-gray-200 rounded-lg hover:bg-gray-100 transition-colors">
              Annuler
            </button>
            <button
              onClick={handleSave}
              disabled={saving || loading}
              className="flex-1 px-4 py-2.5 text-sm text-white bg-[#4A7C59] hover:bg-[#3d6849] rounded-lg font-medium transition-colors flex items-center justify-center gap-2 disabled:opacity-60"
            >
              {saving ? (
                <><Loader2 size={14} className="animate-spin" /> Enregistrement...</>
              ) : (
                <><Save size={14} /> Enregistrer</>
              )}
            </button>
          </div>
        </div>
      </div>
    </>
  );
}
