"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Plus, Trash2 } from "lucide-react";
import { badgeKeys, featureKeys, locationSlugs, operations, propertyStatuses, propertyTypes } from "@alterra/shared";
import { Field, Gallery, Panel, SaveBar, TwoCols, inputClass, sendJson } from "./ui";
import type { PropertyForm } from "@/lib/adminForms";


const labels = {
  types: { villa: "Villa", country_house: "Casa campestre", apartment: "Apartamento", penthouse: "Penthouse", lot: "Lote", commercial: "Comercial" },
  statuses: { available: "Disponible", reserved: "Reservada", sold: "Vendida", rented: "Arrendada" },
  operations: { sale: "Venta", rent: "Arriendo" },
  features: { view: "Vista", pool: "Piscina", stable: "Pesebrera", gated: "En condominio", new_build: "Para estrenar" },
  badges: { exclusive: "Exclusiva", off_market: "Fuera de mercado", new: "Nueva" },
  distances: { airportMin: "Aeropuerto JMC", medellinMin: "Medellín", schoolsMin: "Colegios", mallsMin: "Centros comerciales", hospitalsMin: "Hospitales" },
} as const;

const zoneNames: Record<string, string> = {
  "llanogrande-rionegro": "Llanogrande y Rionegro",
  "el-retiro": "El Retiro",
  "alto-de-las-palmas": "Alto de Las Palmas",
  envigado: "Envigado",
  "el-poblado": "El Poblado",
  guatape: "Guatapé",
};


const slugify = (s: string) =>
  s
    .toLowerCase()
    .normalize("NFD")
    .replace(/[̀-ͯ]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");

const toNumber = (value: string) => (value.trim() === "" ? null : Number(value.replace(/[^\d.]/g, "")));

export default function PropertyEditor({ initial }: { initial: PropertyForm }) {
  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 PropertyForm>(key: K, value: PropertyForm[K]) => setForm((f) => ({ ...f, [key]: value }));
  const toggle = (key: "features" | "badges", value: string) =>
    set(key, form[key].includes(value) ? form[key].filter((v) => v !== value) : [...form[key], value]);

  const number = (key: keyof PropertyForm, label: string, hint?: string) => (
    <Field label={label} hint={hint}>
      <input
        inputMode="decimal"
        value={(form[key] as number | null) ?? ""}
        onChange={(e) => set(key, toNumber(e.target.value) as never)}
        className={inputClass}
      />
    </Field>
  );
  const textInput = (key: keyof PropertyForm, 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 textArea = (key: keyof PropertyForm, label: string, rows = 5, required = false) => (
    <Field label={label}>
      <textarea required={required} rows={rows} value={(form[key] as string | null) ?? ""} onChange={(e) => set(key, e.target.value as never)} className={inputClass} />
    </Field>
  );

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setMessage("");
    setError("");
    const { id, ...payload } = form;
    const result = id ? await sendJson(`/api/v1/admin/properties/${id}`, "PUT", payload) : await sendJson("/api/v1/admin/properties", "POST", payload);
    setSaving(false);
    if (!result.ok) return setError(result.error);
    setMessage("Cambios guardados. El sitio público se actualiza en menos de un minuto.");
    if (!id && result.data.id) router.replace(`/admin/properties/${result.data.id}`);
    router.refresh();
  };

  return (
    <form onSubmit={onSubmit} className="space-y-6">
      <Panel title="Identificación">
        <TwoCols>
          {textInput("titleEs", "Título (ES)", true)}
          {textInput("titleEn", "Title (EN)", true)}
          <Field label="Slug (URL)" hint="Minúsculas y guiones. Ej: villa-los-arrayanes">
            <div className="flex gap-2">
              <input required value={form.slug} onChange={(e) => set("slug", slugify(e.target.value))} className={inputClass} />
              <button type="button" onClick={() => set("slug", slugify(form.titleEs || form.titleEn))} className="mt-1.5 shrink-0 border border-ink/20 px-3 text-xs hover:border-ink">
                Desde título
              </button>
            </div>
          </Field>
          <Field label="Código de referencia" hint="Mayúsculas, números y guiones. Ej: AE-0009">
            <input required value={form.referenceCode} onChange={(e) => set("referenceCode", e.target.value.toUpperCase())} className={inputClass} />
          </Field>
          <Field label="Zona">
            <select value={form.locationSlug} onChange={(e) => set("locationSlug", e.target.value)} className={inputClass}>
              {locationSlugs.map((z) => (
                <option key={z} value={z}>
                  {zoneNames[z]}
                </option>
              ))}
            </select>
          </Field>
          <Field label="Tipo">
            <select value={form.type} onChange={(e) => set("type", e.target.value)} className={inputClass}>
              {propertyTypes.map((t) => (
                <option key={t} value={t}>
                  {labels.types[t]}
                </option>
              ))}
            </select>
          </Field>
          <Field label="Operación">
            <select value={form.operation} onChange={(e) => set("operation", e.target.value)} className={inputClass}>
              {operations.map((o) => (
                <option key={o} value={o}>
                  {labels.operations[o]}
                </option>
              ))}
            </select>
          </Field>
          <Field label="Estado">
            <select value={form.status} onChange={(e) => set("status", e.target.value)} className={inputClass}>
              {propertyStatuses.map((s) => (
                <option key={s} value={s}>
                  {labels.statuses[s]}
                </option>
              ))}
            </select>
          </Field>
        </TwoCols>
      </Panel>

      <Panel title="Precio y datos">
        <TwoCols>
          {number("priceCop", "Precio (COP)", "Vacío = precio bajo consulta. El valor en USD se calcula con la tasa vigente.")}
          {number("adminFeeCop", "Administración mensual (COP)")}
          {number("propertyTaxCop", "Impuesto predial anual (COP)")}
          {number("yearBuilt", "Año de construcción")}
          {number("bedrooms", "Habitaciones")}
          {number("bathrooms", "Baños")}
          {number("parking", "Parqueaderos")}
          {number("builtAreaM2", "Área construida (m²)")}
          {number("lotAreaM2", "Área de lote (m²)")}
        </TwoCols>
      </Panel>

      <Panel title="Descripción">
        <TwoCols>
          {textArea("descriptionEs", "Descripción (ES)", 8, true)}
          {textArea("descriptionEn", "Description (EN)", 8, true)}
        </TwoCols>
      </Panel>

      <Panel title="Fotos">
        <Gallery images={form.images} onChange={(images) => set("images", images)} />
      </Panel>

      <Panel title="Características, amenidades y etiquetas">
        <div>
          <p className="text-sm font-medium text-ink/80">Características (filtrables)</p>
          <div className="mt-2 flex flex-wrap gap-2">
            {featureKeys.map((f) => (
              <button key={f} type="button" onClick={() => toggle("features", f)} className={`border px-3 py-1.5 text-sm ${form.features.includes(f) ? "border-forest bg-forest text-cream" : "border-ink/20"}`}>
                {labels.features[f]}
              </button>
            ))}
          </div>
        </div>
        <div>
          <p className="text-sm font-medium text-ink/80">Etiquetas</p>
          <div className="mt-2 flex flex-wrap gap-2">
            {badgeKeys.map((b) => (
              <button key={b} type="button" onClick={() => toggle("badges", b)} className={`border px-3 py-1.5 text-sm ${form.badges.includes(b) ? "border-gold bg-gold-light text-ink" : "border-ink/20"}`}>
                {labels.badges[b]}
              </button>
            ))}
          </div>
        </div>
        <div>
          <p className="text-sm font-medium text-ink/80">Amenidades</p>
          <ul className="mt-2 space-y-2">
            {form.amenities.map((a, i) => (
              <li key={i} className="flex gap-2">
                <input value={a.es} onChange={(e) => set("amenities", form.amenities.map((x, j) => (j === i ? { ...x, es: e.target.value } : x)))} placeholder="ES" className={inputClass} />
                <input value={a.en} onChange={(e) => set("amenities", form.amenities.map((x, j) => (j === i ? { ...x, en: e.target.value } : x)))} placeholder="EN" className={inputClass} />
                <button type="button" onClick={() => set("amenities", form.amenities.filter((_, j) => j !== i))} aria-label="Eliminar" className="mt-1.5 px-2 text-stone hover:text-red-700">
                  <Trash2 size={16} />
                </button>
              </li>
            ))}
          </ul>
          <button type="button" onClick={() => set("amenities", [...form.amenities, { en: "", es: "" }])} className="mt-2 flex items-center gap-1 text-sm text-forest">
            <Plus size={15} /> Agregar amenidad
          </button>
        </div>
        <label className="flex items-center gap-3 text-sm">
          <input type="checkbox" checked={form.featured} onChange={(e) => set("featured", e.target.checked)} /> Destacada en la portada
        </label>
      </Panel>

      <Panel title="Ubicación aproximada y distancias">
        <TwoCols>
          {number("lat", "Latitud aproximada", "Nunca la dirección exacta.")}
          {number("lng", "Longitud aproximada")}
          {Object.entries(labels.distances).map(([key, label]) => (
            <Field key={key} label={`${label} (minutos)`}>
              <input
                inputMode="numeric"
                value={form.distances[key] ?? ""}
                onChange={(e) => {
                  const next = { ...form.distances };
                  const n = toNumber(e.target.value);
                  if (n === null) delete next[key];
                  else next[key] = n;
                  set("distances", next);
                }}
                className={inputClass}
              />
            </Field>
          ))}
        </TwoCols>
      </Panel>

      <Panel title="Video, tour e inversión">
        <TwoCols>
          {textInput("videoUrl", "URL del video")}
          {textInput("tour360Url", "URL del tour 360°")}
          {textArea("investmentNotesEs", "Visión de inversión (ES)", 4)}
          {textArea("investmentNotesEn", "Investment view (EN)", 4)}
        </TwoCols>
      </Panel>

      <Panel title="SEO (opcional)">
        <TwoCols>
          {textInput("seoTitleEs", "Título SEO (ES)")}
          {textInput("seoTitleEn", "SEO title (EN)")}
          {textArea("seoDescriptionEs", "Descripción SEO (ES)", 3)}
          {textArea("seoDescriptionEn", "SEO description (EN)", 3)}
        </TwoCols>
      </Panel>

      <SaveBar saving={saving} message={message} error={error}>
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" checked={form.published} onChange={(e) => set("published", e.target.checked)} /> Publicada
        </label>
      </SaveBar>
    </form>
  );
}
