"use client";

import Button from "@/components/ui/buttons/Button";
import SectionWrapper from "@/components/ui/section/SectionWrapper";
import { Plus, User } from "lucide-react";
import Loader from "@/components/ui/Loader/Loader";
import NotFound from "@/components/ui/NotFound";
import GuarantorForm from "../guarantor/modal/GuarantorForm";
import { useGuarantor } from "@/hooks/useGuarantor";
import { GuarantorCard } from "../guarantor/GuarantorCard";


export default function Guarantor({ clientId }: { clientId: string }) {
  const {
    guarantors,
    loading,
  
    showForm,
    editTarget,
    expanded,
    setShowForm,
    setEditTarget,
    handleAdd,
    handleEdit,
    handleDelete,
    toggleExpand,
  } = useGuarantor(clientId);
  console.log("guarantors",guarantors);

  return (
    <div className="flex-1 overflow-auto px-6 py-5">
      <SectionWrapper
        title="Guarantor"
        count={guarantors}
        countLabel="Guarantor"
        countLabelPlural="Guarantors"
        button={
          <Button
            name="Add Guarantor"
            variant="outline"
            size="sm"
            icon={Plus}
            onClick={() => setShowForm(true)}
          />
        }
      >
        {loading ? (
          <Loader />
        ) : guarantors.length === 0 ? (
          <NotFound
            title="No Guarantor yet"
            message='Click "Add Guarantor" to add your first guarantor.'
            icon={<User className="w-6 h-6 text-gray-400" />}
          />
        ) : (
          <div className="space-y-2">
            {guarantors.map((guarantor, idx) => {
              const open = expanded.has(guarantor.id);

              return (
                <GuarantorCard
                  key={guarantor.id}
                  guarantor={guarantor}
                  idx={idx}
                  open={open}
                  toggleExpand={toggleExpand}
                  setEditTarget={setEditTarget}
                  handleDelete={handleDelete}
                />
              );
            })}
          </div>
        )}

        {showForm && (
          <GuarantorForm
            title="Add Guarantor"
            onSave={handleAdd}
            onClose={() => setShowForm(false)}
          />
        )}

        {editTarget && (
          <GuarantorForm
            title="Edit Guarantor"
            initial={editTarget}
            onSave={handleEdit}
            onClose={() => setEditTarget(null)}
          />
        )}
      </SectionWrapper>
    </div>
  );
}
