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";
import NoData from "../../../components/NoData";
import { Toaster, toaster } from "../../../components/ui/toaster";


// 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, isLoading } = useGetFaqQuery()
  const [localData, setLocalData] = useState<any[]>([]);
  const [faqToggle] = useFaqToggleMutation()
  const [deleteFaqPost] = useDeleteFaqPostMutation()
  const [searchTerm, setSearchTerm] = useState("");
  const [deleteModal, setDeleteModal] = useState(false)
  const [selectedFaqId, setSelectedFaqId] = useState<number | null>(null);

  // 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();
      if (response.success) {
        toaster.create({
          title: "Success",
          description: "FAQ deleted successfully",
          type: "success",
        });
        refetch()
        console.log("FAQ deleted successfully:", response);
      }
      // Optionally, refetch data or update state after deletion
    } catch (error) {
      console.error("Error deleting FAQ:", error);
      toaster.create({
        title: "Error",
        description: "Something went wrong",
        type: "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
          isOpen={deleteModal}
          AltertTiggerIcon={() => <Delete onClick={() => {
            setSelectedFaqId(agency.id);
            setDeleteModal(true)
          }} />}
          alertText="Delete FAQ"
          alertIcon={<Image src={"DeleteIcon"} h={"39px"} />}
          alertCaption="are you sure you want to delete ?"
          onClose={() => setDeleteModal(false)}
          onConfirm={() => {
            // console.log("Deleting FAQ with ID:", selectedFaqId); // Correct ID
            if (selectedFaqId) {
              setDeleteModal(false);
              handleDeleteFaq(selectedFaqId);
            }
          }}
        />
        <Box>
          <Switch
            colorPalette={'teal'}
            size={"xs"}
            onChange={() => handleToggle(agency.id.toString(), Number(agency.is_active))}
            checked={Boolean(Number(agency.is_active))}
          />
        </Box>
      </HStack>
    ),
  }));

  // if (!isLoading && !data?.data) {
  //   return (
  //     <NoData />
  //   )
  // }

  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 >
            <SearchComponent
              value={searchTerm}
              onChange={setSearchTerm}
            />
            {/* <Button bgColor={'#EEEEEE'} pl={3} pr={3}><IoMdAdd /> <Text>Add</Text></Button> */}
            <FaqAddModel refetch={refetch} />
          </HStack>
        </HStack>
        {!isLoading && !data?.data ? (
          <NoData />
        ) : <DataTable
          sortableColumns={["Name"]}
          tableHeadRow={tableHeadRow}
          data={managepost}
          paginationData={data?.data}
          refetch={refetch}
        />}
      </Box>
      <Toaster />
    </MainFrame>
  )
}
export default FAQ