import { Box, HStack, Image, Text } from "@chakra-ui/react";
import MainFrame from "../../../components/MainFrame"
import EditDetails from "./EditDetails";
// import { InputGroup } from "../../../components/ui/input-group";
// import { LuSearch } from "react-icons/lu";
import DataTable from "../../../components/DataTable";
import AlertDailog from "../../../components/AlertDailog";
import { Switch } from "../../../components/ui/switch";
import FaqAddModel from "./FaqAddModel";
import Delete from "../../../components/ActionIcons/Delete";
import { useEffect, useState } from "react";
import { FaqData, useDeleteFaqPostMutation, useFaqToggleMutation, useGetFaqQuery } from "../../../Redux/Service/faqs.service";
import SearchComponent from "../../../components/SearchComponent";


// table data

const tableHeadRow = [
  "Sr. No",
  "Question",
  "Answer",
  "Action",
];

// const managepost: any[] = [
//   ...Array.from({ length: 12 }, (_, i) => ({
//     "Sr. No": i + 1,
//     "Question": "Lorem Ipsum",
//     "Answer": "Lorem Ipsum",
//     "Action": (
//       <HStack justifyContent="center">
//         <Box>
//           <Switch colorPalette={'teal'} size={"xs"} />
//         </Box>
//         {/* <EditDetails /> */}
//         <EditDetails id={(i + 1).toString()} question="Lorem Ipsum" answer="Lorem Ipsum" />

//         <AlertDailog
//           AltertTiggerIcon={() => <Delete />}
//           alertText="Delete Users"
//           alertIcon={<Image src={"DeleteIcon"} h={"39px"} />}
//           alertCaption="are you sure you want to delete ?"
//           onConfirm={() => {
//             console.log("User deleted:", i + 1);
//           }}
//         />
//       </HStack>
//     ),
//   })),
// ];

const FAQ = () => {
  const { data, refetch } = useGetFaqQuery()
  const [localData, setLocalData] = useState<any[]>([]);
  const [faqToggle] = useFaqToggleMutation()
  const [deleteFaqPost] = useDeleteFaqPostMutation()
  const [searchTerm, setSearchTerm] = useState("");

  // console.log('DATA', data?.data);

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


  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 faqToggle({ id: agencyId, is_active: newStatus }).unwrap();
      refetch()
    } catch (error) {
      console.error("Error updating privacy policy:", error);
      setLocalData((prevData) =>
        prevData.map((agency) =>
          agency.id === agencyId ? { ...agency, is_active: currentStatus } : agency
        )
      );
    }
  };

  const handleDeleteFaq = async (faqId: number) => {
    try {
      const response = await deleteFaqPost(faqId).unwrap();
      refetch()
      console.log("FAQ deleted successfully:", response);
      // Optionally, refetch data or update state after deletion
    } catch (error) {
      console.error("Error deleting FAQ:", error);
    }
  };


  const filteredData = localData?.filter((agency) =>
    agency.question.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const managepost = filteredData?.map((agency: FaqData, index: number) => ({
    'id': agency.id,
    "Sr. No": index + 1,
    "Question": agency.question,
    "Answer": agency.answer,

    "Action": (
      <HStack justifyContent="center">
        <EditDetails rowData={{ id: agency.id, question: agency.question, answer: agency.answer }} refetch={refetch} />

        <AlertDailog
          AltertTiggerIcon={() => <Delete />}
          alertText="Delete Users"
          alertIcon={<Image src={"DeleteIcon"} h={"39px"} />}
          alertCaption="are you sure you want to delete ?"
          onConfirm={() => {
            // console.log("User deleted:", index + 1);
            handleDeleteFaq(agency.id)
          }}
        />
        <Box>
          <Switch
            colorPalette={'teal'}
            size={"xs"}
            onChange={() => handleToggle(agency.id.toString(), Number(agency.is_active))}
            checked={Boolean(Number(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"}>
            FAQs
          </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={"2sm"}
                placeholder="Search..."
                bgColor={'#EEEEEE'}
                ps={8}
              />
            </InputGroup> */}
            <SearchComponent
              // placeholder="Search FAQs..."
              value={searchTerm}
              onChange={setSearchTerm}
            />
            {/* <Button bgColor={'#EEEEEE'} pl={3} pr={3}><IoMdAdd /> <Text>Add</Text></Button> */}
            <FaqAddModel refetch={refetch} />
          </HStack>
        </HStack>
        <DataTable
          sortableColumns={["Name"]}
          tableHeadRow={tableHeadRow}
          data={managepost}
          paginationData={data?.data}
          refetch={refetch}
        />
      </Box>
    </MainFrame>
  )
}
export default FAQ