import Link from "next/link";
import { Plus } from "lucide-react";
import { adminFetch, requireAdminUser } from "@/lib/adminApi";
import { formatDateTime } from "@/lib/adminLabels";
import { locations } from "@/lib/site";
import type { LocationSlug } from "@alterra/shared";

export const metadata = { title: "Propiedades" };

type Row = {
  id: number;
  slug: string;
  referenceCode: string;
  titleEs: string;
  locationSlug: string;
  type: string;
  priceCop: number | null;
  published: boolean;
  featured: boolean;
  isSample: boolean;
  updatedAt: string;
  images: { url: string }[];
};

const cop = (n: number | null) => (n === null ? "Bajo consulta" : new Intl.NumberFormat("es-CO", { style: "currency", currency: "COP", maximumFractionDigits: 0 }).format(n));

const zoneName = (slug: string) => locations[slug as LocationSlug]?.name.es ?? slug;

function Thumb({ url }: { url?: string }) {
  // eslint-disable-next-line @next/next/no-img-element
  return url ? <img src={url} alt="" className="h-14 w-20 shrink-0 object-cover" /> : <span className="h-14 w-20 shrink-0 bg-sand" />;
}

function Badges({ p }: { p: Row }) {
  return (
    <div className="flex flex-wrap gap-1.5">
      <span className={`rounded-full px-2.5 py-1 text-xs whitespace-nowrap ${p.published ? "bg-forest/15 text-forest" : "bg-ink/10 text-stone"}`}>{p.published ? "Publicada" : "Borrador"}</span>
      {p.featured && <span className="rounded-full bg-gold/25 px-2.5 py-1 text-xs whitespace-nowrap">Destacada</span>}
      {p.isSample && <span className="rounded-full bg-sand px-2.5 py-1 text-xs whitespace-nowrap">Ejemplo</span>}
    </div>
  );
}

export default async function PropertiesAdmin() {
  await requireAdminUser(["admin", "editor"]);
  const { data } = await adminFetch<{ items: Row[] }>("/v1/admin/properties");
  return (
    <div className="max-w-6xl">
      <div className="flex flex-wrap items-end justify-between gap-4">
        <h1 className="font-serif text-4xl">Propiedades</h1>
        <Link href="/admin/properties/new" className="flex items-center gap-2 bg-ink px-4 py-2 text-sm text-cream hover:bg-forest">
          <Plus size={15} /> Nueva propiedad
        </Link>
      </div>
      {data?.items.length === 0 && <p className="mt-8 border border-ink/10 bg-white px-4 py-6 text-stone">Todavía no hay propiedades.</p>}

      {/* Narrow screens: one card per property. */}
      <ul className="mt-8 space-y-3 xl:hidden">
        {data?.items.map((p) => (
          <li key={p.id}>
            <Link href={`/admin/properties/${p.id}`} className="flex gap-4 border border-ink/10 bg-white p-3 transition-colors hover:border-forest/40">
              <Thumb url={p.images[0]?.url} />
              <div className="min-w-0 flex-1">
                <p className="font-medium leading-snug">{p.titleEs}</p>
                <p className="mt-0.5 text-xs text-stone">
                  {p.referenceCode} · {zoneName(p.locationSlug)}
                </p>
                <p className="mt-1 text-sm">{cop(p.priceCop)}</p>
                <div className="mt-2">
                  <Badges p={p} />
                </div>
              </div>
            </Link>
          </li>
        ))}
      </ul>

      {/* Wide screens: table. */}
      {!!data?.items.length && (
        <div className="mt-8 hidden border border-ink/10 bg-white xl:block">
          <table className="w-full text-left text-sm">
            <thead className="border-b border-ink/10 text-xs tracking-wide text-stone uppercase">
              <tr>
                <th className="px-4 py-3 font-medium">Propiedad</th>
                <th className="px-4 py-3 font-medium">Zona</th>
                <th className="px-4 py-3 font-medium">Precio</th>
                <th className="px-4 py-3 font-medium">Estado</th>
                <th className="px-4 py-3 font-medium">Actualizada</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-ink/10">
              {data.items.map((p) => (
                <tr key={p.id}>
                  <td className="px-4 py-3">
                    <Link href={`/admin/properties/${p.id}`} className="flex items-center gap-3 hover:text-forest">
                      <Thumb url={p.images[0]?.url} />
                      <span className="min-w-0">
                        <span className="block font-medium">{p.titleEs}</span>
                        <span className="text-xs text-stone">{p.referenceCode}</span>
                      </span>
                    </Link>
                  </td>
                  <td className="px-4 py-3 text-stone">{zoneName(p.locationSlug)}</td>
                  <td className="px-4 py-3 whitespace-nowrap">{cop(p.priceCop)}</td>
                  <td className="px-4 py-3">
                    <Badges p={p} />
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap text-stone">{formatDateTime(p.updatedAt)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
