import { Box, HStack, Text } from "@chakra-ui/react";
import MainFrame from "../../../components/MainFrame"
// import { InputGroup } from "../../../components/ui/input-group";
// import { LuSearch } from "react-icons/lu";
import DataTable from "../../../components/DataTable";
import { Switch } from "../../../components/ui/switch";
import { useEffect, useState } from "react";
import { useGetIndustryMasterQuery, useIndustryMasterToggleMutation } from "../../../Redux/Service/industry.master.service";
import EditIndustryMaster from "./EditIndustryMaster";
import AddIndustryMaster from "./AddIndustryMaster";
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",
    "Title",
    "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 IndustryMasterList = () => {
    const [currentPage, setCurrentPage] = useState(1);
    const [industryMasterToggle] = useIndustryMasterToggleMutation()
    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 } = useGetIndustryMasterQuery(queryArgs)

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

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

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

    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 industryMasterToggle({ 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);
            toaster.create({
                    title: "Error",
                    description: "Someting went wrong.",
                    type: "error",
                  });
            setLocalData((prevData) =>
                prevData.map((agency) =>
                    agency.id === agencyId ? { ...agency, is_active: currentStatus } : agency
                )
            );
        }
    };

    const filteredData = localData?.filter((agency) => {
        const searchLower = searchTerm.toLowerCase();
        const title = agency.en_name?.toLowerCase().includes(searchLower);
        return title;
    });

    const managepost = filteredData?.map((agency: any, index: number) => ({
        'id': agency.id,
        "Sr. No": (currentPage - 1) * (data?.data.per_page ?? 0) + index + 1,
        "Title": agency.en_name,
        "is_active": agency.is_active,
        "Action": (
            <HStack justifyContent="center">
                {/* <ViewAgencyMaster agency={localData} id={agency.id} /> */}
                <EditIndustryMaster id={agency.id} localData={localData} refetch={refetch} categories={agency.categories_masters_xid} />
                <Box>
                    <Switch
                        colorPalette={"teal"}
                        size={"xs"}
                        onChange={() => handleToggle(agency.id, Number(agency.is_active))}
                        checked={Boolean(Number(agency.is_active))}
                    />
                </Box>
            </HStack>
        ),
    }));

    // 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"}>
                        Industry Master
                    </Text>

                    <HStack >
                        <SearchComponent
                            value={searchTerm}
                            onChange={handleSearchChange}
                        />
                        {/* <Button bgColor={'#EEEEEE'} pl={3} pr={3}><IoMdAdd /> <Text>Add</Text></Button> */}
                        {/* <ViewAgencyAddModel /> */}
                        <AddIndustryMaster refetch={refetch} />
                    </HStack>
                </HStack>
                <DataTable
                    sortableColumns={["Name"]}
                    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 IndustryMasterList