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 SearchComponent from "../../../components/SearchComponent";
import { useDepartmentToggleMutation, useGetDepartmentMasterQuery } from "../../../Redux/Service/department.master";
import AddDepartmentMaster from "./AddDepartmentMaster";
import EditDepartmentMaster from "./EditDepartmentMaster";
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 DepartmentMasterList = () => {
    const [currentPage, setCurrentPage] = useState(1);
    const [departmentToggle] = useDepartmentToggleMutation()
    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 } = useGetDepartmentMasterQuery(queryArgs)

    console.log("Department Data", data?.data.data)

    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 departmentToggle({ 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} /> */}
                <EditDepartmentMaster localData={agency} refetch={refetch} />
                <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"}>
                        Department Master
                    </Text>

                    <HStack >
                        <SearchComponent
                            value={searchTerm}
                            onChange={handleSearchChange}
                        />
                        {/* <Button bgColor={'#EEEEEE'} pl={3} pr={3}><IoMdAdd /> <Text>Add</Text></Button> */}
                        {/* <ViewAgencyAddModel /> */}
                        <AddDepartmentMaster 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 DepartmentMasterList