"use client";
import { useCopyToClipboard, useRouter } from "@/hooks";
import { enqueueSnackbar } from "@/shared/components/snackbar";
import GroupeFiltresResult from "@/shared/sections/agency/groupe/groupe-filters";
import GroupeToolbar from "@/shared/sections/agency/groupe/groupe-toolbar";
import GroupeView from "@/shared/sections/agency/groupe/groupe-view";
import { IGroupeAgency, IGroupeFilterValue, IGroupeFilters } from "@/shared/types/groupeAgency";
import { Box, Card } from "@mui/material";
import { useCallback, useEffect, useState } from "react";
import axiosInstancee from "@/utils/axios";



type Props = {
  agencyId: string; // Accepts the agency ID as a prop
};

export default function GroupeAgency({ agencyId }: Props) {
  const { copy } = useCopyToClipboard();

  const [groupeData, setGroupeData] = useState<IGroupeAgency[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  const defaultFilters: IGroupeFilters = { name: "" };
  const [filters, setFilters] = useState(defaultFilters);
  const canReset = !!filters.name;

  useEffect(() => {
    async function fetchGroupData() {
      try {
        const response = await axiosInstancee.get(`/api/user/${agencyId}/groups`, { params: filters });
        setGroupeData(response.data);
      } catch (error) {
        console.error("Failed to fetch group data:", error);
        enqueueSnackbar("Failed to load group data.", { variant: "error" });
      } finally {
        setLoading(false);
      }
    }

    fetchGroupData();
  }, [agencyId, filters]);

  const handleResetFilters = useCallback(() => {
    setFilters(defaultFilters);
  }, []);

  const handleFilters = useCallback((name: string, value: IGroupeFilterValue) => {
    setFilters((prevState) => ({ ...prevState, [name]: value }));
  }, []);

  const handleDeleteCard = useCallback(async (id: string) => {
    try {
      await axiosInstancee.delete(`/api/user/groups/${id}`);
      enqueueSnackbar("Delete success!");
      setGroupeData((prevData) => prevData.filter((row) => row.id !== id));
    } catch (error) {
      console.error("Failed to delete group:", error);
      enqueueSnackbar("Failed to delete group.", { variant: "error" });
    }
  }, []);

  const handleCopy = useCallback(() => {
    enqueueSnackbar("Copied!");
  }, [copy, enqueueSnackbar]);

  const renderList = (
    <>
      
      {groupeData.map((grp) => (
        <GroupeView
          key={grp.id}
          groupe={grp}
          onDeleteCard={() => handleDeleteCard(grp.id)}
          onCopyLink={handleCopy}
        />
      ))}
      
    </>

  );
;    console.log("toto", groupeData)
  return (
    <Card>
      <GroupeToolbar agencyId={agencyId} filters={filters} onFilters={handleFilters} />
      {canReset && (
        <GroupeFiltresResult
          filters={filters}
          onFilters={handleFilters}
          onResetFilters={handleResetFilters}
          results={groupeData.length}
          sx={{ p: 2.5, pt: 0 }}
        />
      )}
      <Box
        gap={3}
        display="grid"
        gridTemplateColumns={{ xs: "repeat(1, 1fr)", md: "repeat(2, 1fr)" }}
        style={{ marginTop: "20px", marginBottom: "20px", padding: "20px" }}
      >
        {loading ? <p>Loading...</p> : groupeData.length === 0 ? <p>No results found.</p> : renderList}
      </Box>
    </Card>
  );
}

// Helper function to filter data
function applyFilter({
  inputData,
  filters,
}: {
  inputData: IGroupeAgency[];
  filters: IGroupeFilters;
}) {
  const { name } = filters;
  let filteredData = [...inputData];

  if (name) {
    filteredData = filteredData.filter((grp) =>
      grp.name.toLowerCase().includes(name.toLowerCase())
    );
  }

  return filteredData;
}