"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
import { PolicyForm } from "@/components/PolicyForm";
import { useCan } from "@/lib/abilities";
import { getPolicy } from "@/lib/api";
import type { PolicyDetail } from "@/lib/types";

export default function EditarPolizaPage({
  params,
}: {
  params: { id: string };
}) {
  return (
    <AppShell>
      <EditarPoliza id={params.id} />
    </AppShell>
  );
}

function EditarPoliza({ id }: { id: string }) {
  const allowed = useCan("policy:update");
  const [policy, setPolicy] = useState<PolicyDetail | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!allowed) return;
    getPolicy(id)
      .then(setPolicy)
      .catch((e) => setError(e?.message ?? "No se pudo cargar la póliza."));
  }, [id, allowed]);

  return (
    <>
      <div className="page-head">
        <Link href={`/polizas/${id}`} className="back-link">← Póliza</Link>
        <h1 className="page-title">Editar póliza</h1>
      </div>
      {!allowed ? (
        <div className="state-box state-error">
          No tiene permisos para editar pólizas.
        </div>
      ) : error ? (
        <div className="state-box state-error">{error}</div>
      ) : !policy ? (
        <div className="empty-inline"><span className="spinner" aria-label="Cargando" /></div>
      ) : (
        <PolicyForm policy={policy} />
      )}
    </>
  );
}
