"use client";

import { useState } from "react";
import { ArrowDown, ArrowUp, ImagePlus, Loader2, Trash2 } from "lucide-react";
import type { GalleryImage } from "@/lib/adminForms";

/** Small building blocks for the admin editors. */

export const inputClass = "mt-1.5 w-full border border-ink/15 bg-white px-3 py-2 text-sm outline-none transition focus:border-gold";

export function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
  return (
    <label className="block text-sm">
      <span className="font-medium text-ink/80">{label}</span>
      {children}
      {hint && <span className="mt-1 block text-xs text-stone">{hint}</span>}
    </label>
  );
}

export function Panel({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section className="border border-ink/10 bg-white p-6">
      <h2 className="font-serif text-2xl">{title}</h2>
      <div className="mt-5 space-y-5">{children}</div>
    </section>
  );
}

export function TwoCols({ children }: { children: React.ReactNode }) {
  return <div className="grid gap-5 md:grid-cols-2">{children}</div>;
}

export const apiErrors: Record<string, string> = {
  invalid_request: "Revisa los campos marcados: hay datos incompletos o con formato incorrecto.",
  slug_or_reference_taken: "Ya existe otra propiedad con ese slug o código de referencia.",
  slug_taken: "Ya existe otro artículo con ese slug.",
  invalid_image: "El archivo no es una imagen válida (JPG, PNG o WebP, máximo 10 MB).",
  unauthenticated: "Tu sesión expiró. Vuelve a iniciar sesión.",
  forbidden: "Tu rol no tiene permiso para esta acción.",
};

/** Sends JSON to the admin API and returns a readable error message (or null on success). */
export const sendJson = async (url: string, method: "POST" | "PUT" | "PATCH", body: unknown) => {
  try {
    const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
    const data = (await res.json().catch(() => ({}))) as { error?: string; id?: number; issues?: { path: string; message: string }[] };
    if (res.ok) return { ok: true as const, data };
    const detail = data.issues?.map((i) => i.path).filter(Boolean).join(", ");
    return { ok: false as const, error: `${apiErrors[data.error ?? ""] ?? "No se pudo guardar."}${detail ? ` (${detail})` : ""}` };
  } catch {
    return { ok: false as const, error: "No se pudo conectar con el servidor." };
  }
};

export const uploadImage = async (file: File, folder: "properties" | "articles" | "locations") => {
  const body = new FormData();
  body.append("file", file);
  const res = await fetch(`/api/v1/admin/uploads?folder=${folder}`, { method: "POST", body });
  const data = (await res.json().catch(() => ({}))) as { url?: string; error?: string };
  if (!res.ok || !data.url) throw new Error(apiErrors[data.error ?? ""] ?? "No se pudo subir la imagen.");
  return data.url;
};

/** Single image field (cover / hero). */
export function SingleImage({ value, onChange, folder }: { value: string | null; onChange: (url: string | null) => void; folder: "articles" | "locations" }) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  return (
    <div>
      {value && (
        // eslint-disable-next-line @next/next/no-img-element
        <img src={value} alt="" className="mb-3 aspect-[16/9] w-full max-w-md object-cover" />
      )}
      <div className="flex flex-wrap items-center gap-3">
        <label className="flex cursor-pointer items-center gap-2 border border-ink/20 px-4 py-2 text-sm hover:border-ink">
          {busy ? <Loader2 size={15} className="animate-spin" /> : <ImagePlus size={15} strokeWidth={1.5} />} Subir imagen
          <input
            type="file"
            accept="image/jpeg,image/png,image/webp"
            className="sr-only"
            onChange={async (e) => {
              const file = e.target.files?.[0];
              if (!file) return;
              setBusy(true);
              setError("");
              try {
                onChange(await uploadImage(file, folder));
              } catch (err) {
                setError((err as Error).message);
              } finally {
                setBusy(false);
                e.target.value = "";
              }
            }}
          />
        </label>
        {value && (
          <button type="button" onClick={() => onChange(null)} className="text-sm text-stone hover:text-red-700">
            Quitar
          </button>
        )}
      </div>
      {error && <p className="mt-2 text-sm text-red-700">{error}</p>}
    </div>
  );
}


/** Ordered gallery with upload, alt texts, reorder and remove. The first image is the cover. */
export function Gallery({ images, onChange }: { images: GalleryImage[]; onChange: (images: GalleryImage[]) => void }) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");

  const move = (index: number, delta: number) => {
    const next = [...images];
    const [item] = next.splice(index, 1);
    next.splice(index + delta, 0, item!);
    onChange(next);
  };
  const update = (index: number, patch: Partial<GalleryImage>) => onChange(images.map((img, i) => (i === index ? { ...img, ...patch } : img)));

  return (
    <div>
      <ul className="space-y-3">
        {images.map((img, i) => (
          <li key={`${img.url}-${i}`} className="flex flex-wrap items-start gap-4 border border-ink/10 p-3">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={img.url} alt="" className="h-20 w-28 shrink-0 object-cover" />
            <div className="grid min-w-0 flex-1 gap-2 sm:grid-cols-2">
              <input value={img.altEs} onChange={(e) => update(i, { altEs: e.target.value })} placeholder="Texto alternativo (ES)" className={inputClass} />
              <input value={img.altEn} onChange={(e) => update(i, { altEn: e.target.value })} placeholder="Alt text (EN)" className={inputClass} />
              {i === 0 && <span className="text-xs text-gold-ink">Foto de portada</span>}
            </div>
            <div className="flex gap-1">
              <button type="button" disabled={i === 0} onClick={() => move(i, -1)} aria-label="Subir" className="p-2 text-stone hover:text-ink disabled:opacity-30">
                <ArrowUp size={16} />
              </button>
              <button type="button" disabled={i === images.length - 1} onClick={() => move(i, 1)} aria-label="Bajar" className="p-2 text-stone hover:text-ink disabled:opacity-30">
                <ArrowDown size={16} />
              </button>
              <button type="button" onClick={() => onChange(images.filter((_, j) => j !== i))} aria-label="Eliminar" className="p-2 text-stone hover:text-red-700">
                <Trash2 size={16} />
              </button>
            </div>
          </li>
        ))}
      </ul>
      <label className="mt-4 flex w-fit cursor-pointer items-center gap-2 border border-dashed border-ink/30 px-5 py-3 text-sm hover:border-gold">
        {busy ? <Loader2 size={16} className="animate-spin" /> : <ImagePlus size={16} strokeWidth={1.5} />} Agregar fotos
        <input
          type="file"
          accept="image/jpeg,image/png,image/webp"
          multiple
          className="sr-only"
          onChange={async (e) => {
            const files = [...(e.target.files ?? [])];
            if (!files.length) return;
            setBusy(true);
            setError("");
            const added: GalleryImage[] = [];
            for (const file of files) {
              try {
                added.push({ url: await uploadImage(file, "properties"), altEn: "", altEs: "" });
              } catch (err) {
                setError((err as Error).message);
              }
            }
            onChange([...images, ...added]);
            setBusy(false);
            e.target.value = "";
          }}
        />
      </label>
      {error && <p className="mt-2 text-sm text-red-700">{error}</p>}
    </div>
  );
}

export function SaveBar({ saving, message, error, children }: { saving: boolean; message: string; error: string; children?: React.ReactNode }) {
  return (
    <div className="sticky bottom-0 z-10 -mx-5 flex flex-wrap items-center gap-4 border-t border-ink/10 bg-cream/95 px-5 py-4 backdrop-blur md:-mx-10 md:px-10">
      <button type="submit" disabled={saving} className="bg-ink px-6 py-2.5 text-sm text-cream hover:bg-forest disabled:opacity-60">
        {saving ? "Guardando…" : "Guardar"}
      </button>
      {children}
      <p className={`text-sm ${error ? "text-red-700" : "text-forest"}`} role="status">
        {error || message}
      </p>
    </div>
  );
}
