"use client";

import ClientCard from "@/components/client-card";
import DeviceCard from "@/components/device-card";
import { Cliente, Intervento, Registratore } from "@/generated/prisma";
import { useSearchParams } from "next/navigation";
import { useEffect, useState, Suspense } from "react";

function ClientComponent() {
  const searchParams = useSearchParams();
  const id = searchParams.get("client");
  const [cliente, setCliente] = useState<Cliente>();
  const [registratori, setRegistratori] = useState<Array<Registratore>>();

  useEffect(() => {
    async function getCliente() {
      const req = await fetch(`/api/clienti/${id}`);
      const data = await req.json();
      setCliente(data.cliente);
      setRegistratori(data.cliente.registratori);
    }

    getCliente();
  }, [id]);

  return (
    <div className="flex flex-1 flex-col gap-4 p-4">
      <div className="*:data-[slot=card]:from-primary/5 *:data-[slot=card]:to-card dark:*:data-[slot=card]:bg-card grid grid-cols-1 gap-4 px-4 *:data-[slot=card]:bg-gradient-to-t *:data-[slot=card]:shadow-xs lg:px-6 @xl/main:grid-cols-2 @5xl/main:grid-cols-4">
        {cliente ? <ClientCard cliente={cliente} /> : <></>}
        {registratori ? (
          registratori.map((registratore) => (
            <DeviceCard registratore={registratore} key={registratore.id} />
          ))
        ) : (
          <></>
        )}
      </div>
    </div>
  );
}

export default function Page() {
  return (
    <Suspense
      fallback={<div className="p-8 text-center">Caricamento cliente...</div>}
    >
      <ClientComponent />
    </Suspense>
  );
}
