import { Box, HStack, Text } from "@chakra-ui/react";
import MainFrame from "../../../components/MainFrame"
import DataTable from "../../../components/DataTable";
import { Switch } from "../../../components/ui/switch";
import EditAgencyMaster from "./EditAgencyMaster";
// import ViewAgencyAddModel from "./ViewAgencyAddModel";
import ViewAgencyMaster from "./ViewAgencyMaster";
import { useAgencyMasterToggleMutation, useGetAgencyMasterQuery } from "../../../Redux/Service/agency.master.module.service";
import { useEffect, useState } from "react";
import SearchComponent from "../../../components/SearchComponent";
import { useDebounce } from "../../../components/Hooks/useDebounce";
import { toaster, Toaster } from "../../../components/ui/toaster";
import { delay } from "../../../components/Utils";

// table data

const tableHeadRow = [
  "Sr. No",
  "Agency Name",
  "RC no.",
  "State",
  "RC Status",
  "Registered Office Address",
  "Website/Domain",
  "GST no.",
  "Agency Status",
  "Action"

];

// const managepost: any[] = [
//   ...Array.from({ length: 12 }, (_, i) => ({
//     "Sr. No": i + 1,
//     "Agency Name": "Lorem Ipsum",
//     "RC no.": "Lorem Ipsum",
//     "State": "Lorem Ipsum",
//     "RC Status": "Active",
//     "Registered Office Address": "Lorem Ipsum",
//     "Website/Domain": "Lorem Ipsum",
//     "GST no.": "Lorem Ipsum",
//     "Action": (
//       <HStack justifyContent="center">
//         <ViewAgencyMaster/>
//         <EditAgencyMaster />
//         <Box>
//           <Switch colorPalette={'teal'} size={"xs"}/>
//         </Box>
//       </HStack>
//     ),
//   })),
// ];

const AgencyMaster = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const [agencyMasterToggle] = useAgencyMasterToggleMutation()
  const [localData, setLocalData] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const debouncedSearchTerm = useDebounce(searchTerm, 500);
  const queryArgs = debouncedSearchTerm ? { page: currentPage, search: debouncedSearchTerm } : { page: currentPage };
  const { data, refetch, isError, isFetching } = useGetAgencyMasterQuery(queryArgs)

  const handleToggle = async (agencyId: string, currentStatus: number) => {
    const newStatus = currentStatus ? 0 : 1;
    setLocalData((prevData) =>
      prevData.map((agency) =>
        agency.id === agencyId ? { ...agency, is_active: newStatus } : agency
      )
    );
    try {
      await agencyMasterToggle({ id: agencyId, is_active: newStatus }).unwrap();
      toaster.create({
        title: "Success",
        description: "Status updated successfully",
        type: "success",
      });
      await delay(500);
      refetch()
    } catch (error) {
      console.error("Error updating privacy policy:", error);
      setLocalData((prevData) =>
        prevData.map((agency) =>
          agency.id === agencyId ? { ...agency, is_active: currentStatus } : agency
        )
      );
      toaster.create({
        title: "Error",
        description: "Please try again later",
        type: "error",
      });
    }
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  const handleSearchChange = (value: string) => {
    setSearchTerm(value);
    setCurrentPage(1);
  };

  const filteredData = localData?.filter((agency) =>
    agency?.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    agency?.rc_number.toLowerCase().includes(searchTerm.toLowerCase()) ||
    agency?.state.toLowerCase().includes(searchTerm.toLowerCase()) ||
    agency?.registered_office.toLowerCase().includes(searchTerm.toLowerCase()) ||
    agency?.domain_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    agency?.gst_number.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // const activeCount = filteredData?.filter((a: any) => a.is_active === 1).length ?? 0;

  const managepost = filteredData?.map((agency: any, index: number) => {
    // const isOnlyActive = activeCount === 1 && agency.is_active === 1;

    return {
      id: agency.id,
      "Sr. No": (currentPage - 1) * (data?.data.per_page ?? 0) + index + 1,
      "Agency Name": agency.name,
      "RC no.": agency.rc_number,
      "State": agency.state,
      "RC Status": agency.rc_status,
      "Registered Office Address": agency.registered_office,
      "Website/Domain": agency.domain_name,
      "GST no.": agency.gst_number,
      "Agency Status": agency.is_domain_verified ? "Verified" : "Unverified",
      "is_active": agency.is_active,
      Action: (
        <HStack justifyContent="center">
          <ViewAgencyMaster agency={localData} id={agency.id} />
          <EditAgencyMaster editData={agency} refetch={refetch} />
          <Box>
            <Switch
              colorPalette={"teal"}
              size={"xs"}
              onChange={() => handleToggle(agency.id.toString(), Number(agency.is_active))}
              checked={Boolean(Number(agency.is_active))}
            // disabled={isOnlyActive}
            />
          </Box>
        </HStack>
      ),
    };
  });


  useEffect(() => {
    if (data?.data?.data) {
      setLocalData(data?.data?.data);
    }
  }, [data, localData, managepost]);

  // useEffect(() => {
  //   console.log("Fetched data:", data);
  //   console.log("Local data:", localData);
  //   console.log("Managepost data:", managepost);
  // }, [data, localData, managepost]);

  return (

    <MainFrame>
      <Box>
        <HStack
          w={"100%"}
          justifyContent={"space-between"}
          mb={4}
          py={0}
          px={3}
        >
          <Text as={"span"} fontSize={"sm"} fontWeight={500} color={"#000"}>
            Agency Master
          </Text>

          <HStack >
            {/* <InputGroup
              startElement={
                <LuSearch fontSize={"xs"} style={{ position: 'relative', left: '10px' }} />
              }
              color={"#000"}
            >
              <Input
                p={3}
                w={300}
                bg={"#fff"}
                colorPalette={"blue"}
                _focus={{ border: "1px solid #02A0A0" }}
                rounded={"md"}
                size={"xs"}
                fontSize={"sm"}
                placeholder="Search..."
                bgColor={'#EEEEEE'}
                ps={8}
              />
            </InputGroup> */}
            <SearchComponent
              value={searchTerm}
              onChange={handleSearchChange}
            />
            {/* <ViewAgencyAddModel refetch={refetch} /> */}
          </HStack>
        </HStack>
        <DataTable
          sortableColumns={["Name", "Registration Date "]}
          tableHeadRow={tableHeadRow}
          data={managepost || []}
          paginationData={{
            current_page: data?.data.current_page || 1,
            last_page: data?.data.last_page || 1,
            per_page: data?.data.per_page || 10,
            total: data?.data.total || 0
          }}
          onPageChange={handlePageChange}
          isLoading={isFetching}
          isError={isError}
        />
      </Box>
      <Toaster />
    </MainFrame>
  )
}
export default AgencyMaster