import Link from "next/link";
import { notFound } from "next/navigation";
import { ExternalLink, FileDown } from "lucide-react";
import PropertyEditor from "@/components/admin/PropertyEditor";
import { emptyProperty, type PropertyForm } from "@/lib/adminForms";
import { adminFetch, requireAdminUser } from "@/lib/adminApi";

export const metadata = { title: "Editar propiedad" };

type ApiProperty = Omit<PropertyForm, "images"> & { id: number; images: { url: string; altEn: string; altEs: string }[] } & Record<string, unknown>;

const num = (v: unknown) => (v === null || v === undefined || v === "" ? null : Number(v));

export default async function EditProperty({ params }: { params: Promise<{ id: string }> }) {
  await requireAdminUser(["admin", "editor"]);
  const { id } = await params;
  const { data } = await adminFetch<{ property: ApiProperty }>(`/v1/admin/properties/${encodeURIComponent(id)}`);
  if (!data) notFound();
  const p = data.property;
  const initial: PropertyForm = {
    ...emptyProperty,
    ...Object.fromEntries(Object.keys(emptyProperty).map((k) => [k, p[k] ?? emptyProperty[k as keyof PropertyForm]])),
    id: p.id,
    priceCop: num(p.priceCop),
    adminFeeCop: num(p.adminFeeCop),
    propertyTaxCop: num(p.propertyTaxCop),
    builtAreaM2: num(p.builtAreaM2),
    lotAreaM2: num(p.lotAreaM2),
    lat: num(p.lat),
    lng: num(p.lng),
    distances: (p.distances as Record<string, number> | null) ?? {},
    images: p.images.map(({ url, altEn, altEs }) => ({ url, altEn, altEs })),
  } as PropertyForm;

  return (
    <div className="max-w-5xl">
      <div className="mb-8 flex flex-wrap items-end justify-between gap-4">
        <h1 className="font-serif text-4xl">{p.titleEs}</h1>
        {p.published ? (
          <div className="flex flex-wrap items-center gap-x-5 gap-y-2 text-sm text-forest">
            <Link href={`/es/propiedades/${p.slug}`} target="_blank" className="flex items-center gap-1.5 hover:underline">
              Ver en el sitio <ExternalLink size={14} />
            </Link>
            <a href={`/property-sheet/${p.slug}.pdf?lang=es`} target="_blank" rel="noopener" className="flex items-center gap-1.5 hover:underline">
              <FileDown size={14} /> Ficha PDF (ES)
            </a>
            <a href={`/property-sheet/${p.slug}.pdf?lang=en`} target="_blank" rel="noopener" className="flex items-center gap-1.5 hover:underline">
              <FileDown size={14} /> Ficha PDF (EN)
            </a>
          </div>
        ) : (
          <p className="text-sm text-stone">La ficha PDF estará disponible cuando la propiedad esté publicada.</p>
        )}
      </div>
      {p.isSample ? <p className="mb-6 border-l-2 border-gold pl-4 text-sm text-stone">Ficha de ejemplo. Al guardarla deja de ser ejemplo y se trata como una propiedad real.</p> : null}
      <PropertyEditor initial={initial} />
    </div>
  );
}
