"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
import { CustomerForm } from "@/components/CustomerForm";
import { useCan } from "@/lib/abilities";
import { getCustomer } from "@/lib/api";
import type { CustomerDetail } from "@/lib/types";

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

function EditarCliente({ id }: { id: string }) {
  const allowed = useCan("customer:update");
  const [customer, setCustomer] = useState<CustomerDetail | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!allowed) return;
    getCustomer(id)
      .then(setCustomer)
      .catch((e) => setError(e?.message ?? "No se pudo cargar el cliente."));
  }, [id, allowed]);

  return (
    <>
      <div className="page-head">
        <Link href={`/clientes/${id}`} className="back-link">
          ← Cliente
        </Link>
        <h1 className="page-title">Editar cliente</h1>
      </div>
      {!allowed ? (
        <div className="state-box state-error">
          No tiene permisos para editar clientes.
        </div>
      ) : error ? (
        <div className="state-box state-error">{error}</div>
      ) : !customer ? (
        <div className="empty-inline">
          <span className="spinner" aria-label="Cargando" />
        </div>
      ) : (
        <CustomerForm customer={customer} />
      )}
    </>
  );
}
