"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Plus, Trash2 } from "lucide-react";
import { Field, Panel, SaveBar, SingleImage, TwoCols, inputClass, sendJson } from "./ui";

type Bi = { en: string; es: string };
export type LocationForm = {
  slug: string;
  nameEn: string;
  nameEs: string;
  commercialFocusEn: string;
  commercialFocusEs: string;
  contentEn: string | null;
  contentEs: string | null;
  investmentEn: string | null;
  investmentEs: string | null;
  heroImage: string | null;
  altitudeM: number | null;
  airportMin: number | null;
  medellinMin: number | null;
  highlights: { title: Bi; text: Bi }[];
  faqs: { q: Bi; a: Bi }[];
  seoTitleEn: string | null;
  seoTitleEs: string | null;
  seoDescriptionEn: string | null;
  seoDescriptionEs: string | null;
};

export default function LocationEditor({ initial }: { initial: LocationForm }) {
  const router = useRouter();
  const [form, setForm] = useState(initial);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const set = <K extends keyof LocationForm>(key: K, value: LocationForm[K]) => setForm((f) => ({ ...f, [key]: value }));

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setMessage("");
    setError("");
    const { slug, ...payload } = form;
    const result = await sendJson(`/api/v1/admin/locations/${slug}`, "PUT", payload);
    setSaving(false);
    if (!result.ok) return setError(result.error);
    setMessage("Zona guardada. El sitio se actualiza en menos de un minuto.");
    router.refresh();
  };

  const text = (key: keyof LocationForm, label: string, required = false) => (
    <Field label={label}>
      <input required={required} value={(form[key] as string | null) ?? ""} onChange={(e) => set(key, e.target.value as never)} className={inputClass} />
    </Field>
  );
  const area = (key: keyof LocationForm, label: string, rows = 12) => (
    <Field label={label} hint="Párrafos separados por una línea en blanco.">
      <textarea rows={rows} value={(form[key] as string | null) ?? ""} onChange={(e) => set(key, e.target.value as never)} className={inputClass} />
    </Field>
  );
  const num = (key: "altitudeM" | "airportMin" | "medellinMin", label: string) => (
    <Field label={label}>
      <input inputMode="numeric" value={form[key] ?? ""} onChange={(e) => set(key, e.target.value === "" ? null : Number(e.target.value))} className={inputClass} />
    </Field>
  );

  return (
    <form onSubmit={onSubmit} className="space-y-6">
      <Panel title="Nombre y enfoque">
        <TwoCols>
          {text("nameEs", "Nombre (ES)", true)}
          {text("nameEn", "Name (EN)", true)}
          {text("commercialFocusEs", "Enfoque comercial (ES)", true)}
          {text("commercialFocusEn", "Commercial focus (EN)", true)}
        </TwoCols>
        <Field label="Foto principal">
          <SingleImage value={form.heroImage} onChange={(url) => set("heroImage", url)} folder="locations" />
        </Field>
      </Panel>

      <Panel title="Datos aproximados">
        <div className="grid gap-5 md:grid-cols-3">
          {num("altitudeM", "Altitud (m)")}
          {num("airportMin", "Al aeropuerto (min)")}
          {num("medellinMin", "A Medellín (min)")}
        </div>
      </Panel>

      <Panel title="Contenido">
        <TwoCols>
          {area("contentEs", "Por qué vivir o invertir aquí (ES)")}
          {area("contentEn", "Why live or invest here (EN)")}
          {area("investmentEs", "Inversión y desarrollo (ES)", 6)}
          {area("investmentEn", "Investment & development (EN)", 6)}
        </TwoCols>
      </Panel>

      <Panel title="Destacados">
        {form.highlights.map((h, i) => (
          <div key={i} className="grid gap-2 border border-ink/10 p-3 md:grid-cols-2">
            {(["es", "en"] as const).map((l) => (
              <div key={l} className="space-y-2">
                <input value={h.title[l]} onChange={(e) => set("highlights", form.highlights.map((x, j) => (j === i ? { ...x, title: { ...x.title, [l]: e.target.value } } : x)))} placeholder={`Título (${l.toUpperCase()})`} className={inputClass} />
                <input value={h.text[l]} onChange={(e) => set("highlights", form.highlights.map((x, j) => (j === i ? { ...x, text: { ...x.text, [l]: e.target.value } } : x)))} placeholder={`Texto (${l.toUpperCase()})`} className={inputClass} />
              </div>
            ))}
            <button type="button" onClick={() => set("highlights", form.highlights.filter((_, j) => j !== i))} className="flex items-center gap-1 text-xs text-stone hover:text-red-700">
              <Trash2 size={14} /> Quitar
            </button>
          </div>
        ))}
        {form.highlights.length < 6 && (
          <button type="button" onClick={() => set("highlights", [...form.highlights, { title: { en: "", es: "" }, text: { en: "", es: "" } }])} className="flex items-center gap-1 text-sm text-forest">
            <Plus size={15} /> Agregar destacado
          </button>
        )}
      </Panel>

      <Panel title="Preguntas frecuentes">
        {form.faqs.map((f, i) => (
          <div key={i} className="grid gap-2 border border-ink/10 p-3 md:grid-cols-2">
            {(["es", "en"] as const).map((l) => (
              <div key={l} className="space-y-2">
                <input value={f.q[l]} onChange={(e) => set("faqs", form.faqs.map((x, j) => (j === i ? { ...x, q: { ...x.q, [l]: e.target.value } } : x)))} placeholder={`Pregunta (${l.toUpperCase()})`} className={inputClass} />
                <textarea rows={3} value={f.a[l]} onChange={(e) => set("faqs", form.faqs.map((x, j) => (j === i ? { ...x, a: { ...x.a, [l]: e.target.value } } : x)))} placeholder={`Respuesta (${l.toUpperCase()})`} className={inputClass} />
              </div>
            ))}
            <button type="button" onClick={() => set("faqs", form.faqs.filter((_, j) => j !== i))} className="flex items-center gap-1 text-xs text-stone hover:text-red-700">
              <Trash2 size={14} /> Quitar
            </button>
          </div>
        ))}
        <button type="button" onClick={() => set("faqs", [...form.faqs, { q: { en: "", es: "" }, a: { en: "", es: "" } }])} className="flex items-center gap-1 text-sm text-forest">
          <Plus size={15} /> Agregar pregunta
        </button>
      </Panel>

      <Panel title="SEO (opcional)">
        <TwoCols>
          {text("seoTitleEs", "Título SEO (ES)")}
          {text("seoTitleEn", "SEO title (EN)")}
          {text("seoDescriptionEs", "Descripción SEO (ES)")}
          {text("seoDescriptionEn", "SEO description (EN)")}
        </TwoCols>
      </Panel>

      <SaveBar saving={saving} message={message} error={error} />
    </form>
  );
}
