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 CountryAddModel from "./CountryAddModel";
import EditCountryModel from "./EditCountryModel";
import { CountryData, useCountryToggleMutation, useGetCountryMasterQuery } from "../../../Redux/Service/country.master";
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",
  "Title",
  "Action"

];

// const managepost: any[] = [
//   ...Array.from({ length: 12 }, (_, i) => ({
//     "Sr. No": i + 1,
//     "Title": "Lorem Ipsum",
//     "Action": (
//       <HStack justifyContent="center">
//         <EditCountryModel />
//         <Box>
//           <Switch colorPalette={'teal'} size={"xs"} />
//         </Box>
//       </HStack>
//     ),
//   })),
// ];

const Country = () => {
  const [currentPage, setCurrentPage] = useState(1);
  // const { data, refetch } = useGetCountryMasterQuery(currentPage)
  const [countryToggle] = useCountryToggleMutation()
  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 } = useGetCountryMasterQuery(queryArgs);
  console.log("Country Data", data?.data.data)

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

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

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

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

  const handleToggle = async (agencyId: number, currentStatus: string) => {
    const newStatus = currentStatus === '1' ? '0' : '1';

    setLocalData((prevData) =>
      prevData.map((agency) =>
        agency.id === agencyId ? { ...agency, is_active: newStatus } : agency
      )
    );

    try {
      await countryToggle({ 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: "Please try again later.",
        type: "error",
      });
      setLocalData((prevData) =>
        prevData.map((agency) =>
          agency.id === agencyId ? { ...agency, is_active: currentStatus } : agency
        )
      );
    }
  }

  const managepost = filteredData?.flatMap((agency: CountryData, index: number) => ({
    "Sr. No": (currentPage - 1) * (data?.data.per_page ?? 0) + index + 1,
    "Title": agency.en_name,
    "Action": (
      <HStack justifyContent="center">
        <EditCountryModel rowData={{ id: agency.id, en_name: agency.en_name, country_code: agency.country_code, phonecode: agency.phonecode, capital: agency.capital, currency: agency.currency, currency_name: agency.currency_name, currency_symbol: agency.currency_symbol }} refetch={refetch} />
        <Box>
          <Switch
            colorPalette={'teal'}
            size={"xs"}
            checked={agency.is_active === '1'}
            onChange={() => handleToggle(agency.id, agency.is_active)}
          />
        </Box>
      </HStack>
    ),
  }))


  return (

    <MainFrame>
      <Box>
        <HStack
          w={"100%"}
          justifyContent={"space-between"}
          mb={4}
          py={0}
          px={3}
        >
          <Text as={"span"} fontSize={"sm"} fontWeight={500} color={"#000"}>
            Country
          </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={(value) => {
              //   setSearchTerm(value);
              //   // setCurrentPage(1);
              //   refetch()
              // }}
              onChange={handleSearchChange}
            />
            {/* <Button bgColor={'#EEEEEE'} pl={3} pr={3}><IoMdAdd /> <Text>Add</Text></Button> */}
            <CountryAddModel 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 Country