"use client";

import { useEffect, useState } from "react";
import { AppShell } from "@/components/AppShell";
import { ChildCollection, type ChildConfig } from "@/components/ChildCollection";
import { useCan } from "@/lib/abilities";
import { createLookup, getLookups, removeLookup, updateLookup } from "@/lib/api";
import type { LookupsResponse } from "@/lib/types";

const PROVIDER: ChildConfig = {
  apiKind: "providers",
  title: "Aseguradoras",
  fields: [{ key: "name", label: "Nombre" }],
};
const TYPE: ChildConfig = {
  apiKind: "policy-types",
  title: "Tipos de póliza",
  fields: [
    { key: "name", label: "Nombre" },
    { key: "shortDescription", label: "Descripción" },
  ],
};
const ADJUSTER: ChildConfig = {
  apiKind: "adjusters",
  title: "Ajustadores",
  fields: [
    { key: "company", label: "Empresa" },
    { key: "name", label: "Nombre" },
    { key: "city", label: "Ciudad" },
    { key: "phone", label: "Teléfono" },
    { key: "beeper", label: "Beeper" },
  ],
};

export default function CatalogosPage() {
  return (
    <AppShell>
      <Catalogos />
    </AppShell>
  );
}

function Catalogos() {
  const canEdit = useCan("lookup:manage");
  const [data, setData] = useState<LookupsResponse | null>(null);
  const [error, setError] = useState<string | null>(null);

  function reload() {
    getLookups().then(setData).catch((e) => setError(e?.message ?? "Error al cargar."));
  }
  useEffect(reload, []);

  if (!canEdit) {
    return (
      <>
        <div className="page-head"><h1 className="page-title">Catálogos</h1></div>
        <div className="state-box state-error">
          No tiene permisos para administrar catálogos.
        </div>
      </>
    );
  }

  const section = (config: ChildConfig, rows: Record<string, unknown>[]) => (
    <ChildCollection
      config={config}
      rows={rows}
      canEdit={canEdit}
      onAdd={async (p) => {
        await createLookup(config.apiKind, p);
        reload();
      }}
      onSave={async (id, p) => {
        await updateLookup(config.apiKind, id, p);
        reload();
      }}
      onRemove={async (id) => {
        await removeLookup(config.apiKind, id);
        reload();
      }}
    />
  );

  return (
    <>
      <div className="page-head">
        <p className="eyebrow">Datos de referencia de seguros</p>
        <h1 className="page-title">Catálogos</h1>
      </div>
      {error && <div className="state-box state-error">{error}</div>}
      {!data ? (
        <div className="empty-inline"><span className="spinner" aria-label="Cargando" /></div>
      ) : (
        <>
          {section(PROVIDER, data.providers as unknown as Record<string, unknown>[])}
          {section(TYPE, data.types as unknown as Record<string, unknown>[])}
          {section(ADJUSTER, data.adjusters as unknown as Record<string, unknown>[])}
        </>
      )}
    </>
  );
}
