/* global React, Icon */
// ============================================================================
// GeoPicker — picker en cascade Pays → Région → Département → Arrondissement
//             → Commune → Quartier
// ----------------------------------------------------------------------------
// Composant réutilisable. Utilisé par :
//   - Baseline · Nouveau site (saisie unitaire)
//   - Baseline · Importer un CSV (auto-mapping)
//   - Activités · saisie d'une activité (l'attache géo de l'activité)
//   - Définitions de base · panneau de gestion du référentiel
//
// API
// ---
// <GeoPicker
//   value={{
//     country_iso2: "SN",     // optionnel — défaut: pas de pré-sélection
//     region_id: "...",
//     department_id: "...",
//     arrondissement_id: "...",
//     commune_id: "...",
//     quartier_id: "...",      // optionnel
//   }}
//   onChange={(v) => setValue(v)}
//   lang="fr"
//   showQuartier={true}         // affiche le 6e niveau (par défaut false)
//   allowQuartierCreate={true}  // bouton "+ Nouveau quartier" inline
//   compact={false}             // false = grille 2x3, true = ligne horizontale
//   defaultCountry="SN"         // pré-sélection si value vide
// />
//
// onChange reçoit l'objet complet (pas un patch) ; quand un niveau supérieur
// change, tous les niveaux inférieurs sont remis à null automatiquement —
// sinon l'utilisateur garderait des incohérences (ex: Région Dakar mais
// département Saint-Louis).
//
// Le composant GeoBreadcrumb (en bas) affiche le chemin résolu en lecture
// seule, utile pour les listes / tableaux.
// ============================================================================

function GeoPicker({
  value,
  onChange,
  lang = "fr",
  showQuartier = false,
  allowQuartierCreate = false,
  compact = false,
  defaultCountry = "SN",
  showLabels = true,
}) {
  const { useEffect, useState } = React;
  const v = value || {};
  const cIso = v.country_iso2 || null;

  // Pré-sélection du pays par défaut une fois au montage si rien n'est défini.
  useEffect(() => {
    if (!v.country_iso2 && defaultCountry) {
      onChange({ ...v, country_iso2: defaultCountry });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Hooks de fetch — chacun retourne { data, loading }
  const { data: countries }       = window.melr.useCountries();
  const { data: regions }         = window.melr.useGeoRegions(cIso);
  const { data: departments }     = window.melr.useGeoDepartments(v.region_id || null);
  const { data: arrondissements } = window.melr.useGeoArrondissements(v.department_id || null);
  const { data: communes }        = window.melr.useGeoCommunes(v.arrondissement_id || null);
  const { data: quartiers }       = window.melr.useGeoQuartiers(v.commune_id || null);

  // Setters · quand on change un niveau, on efface tous les niveaux inférieurs
  // pour éviter les incohérences (Région Dakar mais Département Saint-Louis).
  const setCountry = (iso) => onChange({
    country_iso2: iso || null,
    region_id: null, department_id: null, arrondissement_id: null,
    commune_id: null, quartier_id: null,
  });
  const setRegion = (id) => onChange({
    ...v, region_id: id || null,
    department_id: null, arrondissement_id: null,
    commune_id: null, quartier_id: null,
  });
  const setDepartment = (id) => onChange({
    ...v, department_id: id || null,
    arrondissement_id: null,
    commune_id: null, quartier_id: null,
  });
  const setArrondissement = (id) => onChange({
    ...v, arrondissement_id: id || null,
    commune_id: null, quartier_id: null,
  });
  const setCommune = (id) => onChange({
    ...v, commune_id: id || null,
    quartier_id: null,
  });
  const setQuartier = (id) => onChange({ ...v, quartier_id: id || null });

  // ── Création inline d'un quartier ─────────────────────────────────────
  const [creatingQuartier, setCreatingQuartier] = useState(false);
  const [newQuartierName, setNewQuartierName] = useState("");
  const [creating, setCreating] = useState(false);
  const [createErr, setCreateErr] = useState(null);
  const onCreateQuartier = async () => {
    setCreateErr(null);
    if (!newQuartierName.trim()) { setCreateErr(lang === "fr" ? "Nom requis." : "Name required."); return; }
    if (!v.commune_id) return;
    setCreating(true);
    try {
      const row = await window.melr.geoQuartiersCrud.create({
        commune_id: v.commune_id,
        name_fr: newQuartierName.trim(),
      });
      setQuartier(row.id);
      setCreatingQuartier(false);
      setNewQuartierName("");
    } catch (e) { setCreateErr(e.message); }
    finally { setCreating(false); }
  };

  // ── Styles ─────────────────────────────────────────────────────────────
  const inp = {
    padding: "7px 9px", borderRadius: 6, border: "1px solid var(--line)",
    fontSize: 12.5, background: "var(--bg, white)", color: "var(--text)",
    width: "100%", boxSizing: "border-box",
  };
  const lbl = {
    display: "block", fontSize: 10.5, color: "var(--text-faint)",
    marginBottom: 3, textTransform: "uppercase", letterSpacing: "0.04em",
  };

  const wrapStyle = compact
    ? { display: "flex", gap: 8, flexWrap: "wrap", alignItems: "flex-end" }
    : { display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 };

  const Field = ({ label, children }) => (
    <div>
      {showLabels && <label style={lbl}>{label}</label>}
      {children}
    </div>
  );

  return (
    <div style={wrapStyle}>
      <Field label={lang === "fr" ? "Pays" : "Country"}>
        <select style={inp} value={cIso || ""} onChange={(e) => setCountry(e.target.value || null)}>
          <option value="">— {lang === "fr" ? "Sélectionner" : "Select"} —</option>
          {(countries || []).map((c) => (
            <option key={c.iso2} value={c.iso2}>{c.name_fr}</option>
          ))}
        </select>
      </Field>

      <Field label={lang === "fr" ? "Région" : "Region"}>
        <select style={inp} value={v.region_id || ""} disabled={!cIso}
          onChange={(e) => setRegion(e.target.value || null)}>
          <option value="">— {lang === "fr" ? "Sélectionner" : "Select"} —</option>
          {(regions || []).map((r) => (
            <option key={r.id} value={r.id}>{r.name_fr}</option>
          ))}
        </select>
      </Field>

      <Field label={lang === "fr" ? "Département" : "Department"}>
        <select style={inp} value={v.department_id || ""} disabled={!v.region_id}
          onChange={(e) => setDepartment(e.target.value || null)}>
          <option value="">— {lang === "fr" ? "Sélectionner" : "Select"} —</option>
          {(departments || []).map((d) => (
            <option key={d.id} value={d.id}>{d.name_fr}</option>
          ))}
        </select>
      </Field>

      <Field label={lang === "fr" ? "Arrondissement" : "Arrondissement"}>
        <select style={inp} value={v.arrondissement_id || ""} disabled={!v.department_id}
          onChange={(e) => setArrondissement(e.target.value || null)}>
          <option value="">— {lang === "fr" ? "Sélectionner" : "Select"} —</option>
          {(arrondissements || []).map((a) => (
            <option key={a.id} value={a.id}>{a.name_fr}</option>
          ))}
        </select>
      </Field>

      <Field label={lang === "fr" ? "Commune" : "Commune"}>
        <select style={inp} value={v.commune_id || ""} disabled={!v.arrondissement_id}
          onChange={(e) => setCommune(e.target.value || null)}>
          <option value="">— {lang === "fr" ? "Sélectionner" : "Select"} —</option>
          {(communes || []).map((c) => (
            <option key={c.id} value={c.id}>
              {c.name_fr}{c.type ? " · " + c.type.replace("Commune ", "") : ""}
            </option>
          ))}
        </select>
      </Field>

      {showQuartier && (
        <Field label={lang === "fr" ? "Quartier" : "Neighborhood"}>
          {!creatingQuartier ? (
            <div style={{ display: "flex", gap: 6 }}>
              <select style={{ ...inp, flex: 1 }} value={v.quartier_id || ""} disabled={!v.commune_id}
                onChange={(e) => setQuartier(e.target.value || null)}>
                <option value="">— {lang === "fr" ? "Sélectionner" : "Select"} —</option>
                {(quartiers || []).map((q) => (
                  <option key={q.id} value={q.id}>{q.name_fr}</option>
                ))}
              </select>
              {allowQuartierCreate && v.commune_id && (
                <button type="button" className="btn xs ghost" onClick={() => setCreatingQuartier(true)}
                  title={lang === "fr" ? "Ajouter un quartier" : "Add a neighborhood"}>
                  <Icon.plus />
                </button>
              )}
            </div>
          ) : (
            <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
              <input style={{ ...inp, flex: 1 }} autoFocus
                placeholder={lang === "fr" ? "Nom du quartier" : "Neighborhood name"}
                value={newQuartierName}
                onChange={(e) => setNewQuartierName(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); onCreateQuartier(); } }} />
              <button type="button" className="btn xs primary" onClick={onCreateQuartier} disabled={creating}>
                {creating ? "…" : (lang === "fr" ? "Créer" : "Create")}
              </button>
              <button type="button" className="btn xs ghost" onClick={() => { setCreatingQuartier(false); setNewQuartierName(""); setCreateErr(null); }}>
                <Icon.x />
              </button>
            </div>
          )}
          {createErr && <div style={{ color: "#b91c1c", fontSize: 11, marginTop: 4 }}>{createErr}</div>}
        </Field>
      )}
    </div>
  );
}

// ============================================================================
// GeoBreadcrumb — affichage en lecture seule du chemin Commune → Arr → Dépt → Région → Pays
// Utilise resolveCommuneBreadcrumb (cache). Idéal pour les listes /
// tableaux de sites où l'on ne veut pas re-fetcher 5 niveaux à chaque ligne.
// ============================================================================
function GeoBreadcrumb({ communeId, quartierId, lang = "fr" }) {
  const { useState, useEffect } = React;
  const [bc, setBc] = useState(null);
  const [quartierName, setQuartierName] = useState(null);
  useEffect(() => {
    let mounted = true;
    if (!communeId) { setBc(null); return; }
    window.melr.resolveCommuneBreadcrumb(communeId).then((r) => { if (mounted) setBc(r); });
    return () => { mounted = false; };
  }, [communeId]);
  useEffect(() => {
    let mounted = true;
    if (!quartierId) { setQuartierName(null); return; }
    (async () => {
      const sb = window.melr && window.melr.supabase;
      if (!sb) return;
      const r = await sb.from("geo_quartiers").select("name_fr").eq("id", quartierId).single();
      if (mounted && r.data) setQuartierName(r.data.name_fr);
    })();
    return () => { mounted = false; };
  }, [quartierId]);
  if (!bc) return <span className="text-faint" style={{ fontSize: 11 }}>—</span>;
  const parts = [quartierName, bc.commune.name, bc.arrondissement.name, bc.department.name, bc.region.name, bc.country.name].filter(Boolean);
  return <span style={{ fontSize: 12 }}>{parts.join(" · ")}</span>;
}

// Expose globally for screens that load this file.
window.GeoPicker = GeoPicker;
window.GeoBreadcrumb = GeoBreadcrumb;
