"use client";

import dynamic from "next/dynamic";
import { useSearchParams } from "next/navigation";
import { useEffect, useState, Suspense } from "react";
import { Cliente } from "@/generated/prisma";

function MapContent() {
  const MapWithNoSSR = dynamic(() => import("../../components/map"), {
    ssr: false,
  });
  const [clienti, setClienti] = useState<Array<Cliente>>();
  const searchParams = useSearchParams();
  const client = searchParams.get("client");

  useEffect(() => {
    async function getClienti() {
      const req = await fetch(`/api/clienti`);
      const data = await req.json();
      setClienti(data.clients);
    }

    getClienti();
  }, []);

  return (
    <div id="map" className="w-full h-full border rounded-md m-0 p-0">
      <MapWithNoSSR
        highlight={clienti?.find((cliente) => cliente.id == +(client || -1))}
        clienti={clienti || undefined}
      />
    </div>
  );
}

export default function Page() {
  return (
    <Suspense fallback={<div>Caricamento mappa...</div>}>
      <MapContent />
    </Suspense>
  );
}
