"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
import { PropertyForm } from "@/components/PropertyForm";
import { useCan } from "@/lib/abilities";
import { getProperty } from "@/lib/api";
import type { PropertyDetail } from "@/lib/types";

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

function EditarPropiedad({ id }: { id: string }) {
  const allowed = useCan("property:update");
  const [property, setProperty] = useState<PropertyDetail | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!allowed) return;
    getProperty(id)
      .then(setProperty)
      .catch((e) => setError(e?.message ?? "No se pudo cargar la propiedad."));
  }, [id, allowed]);

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