import {
  Box, HStack,
  Image,
  // Image, 
  Text,
} from "@chakra-ui/react";
import MainFrame from "../../../components/MainFrame";
// import AlertDailog from "../../../components/AlertDailog";
// import { RiDeleteBin5Line } from "react-icons/ri";
import DataTable from "../../../components/DataTable";
import { Switch } from "../../../components/ui/switch";
import ViewRegisterUsers from "./ViewRegisterUsers";
import EditRegisterUsers from "./EditRegisterUsers";
// import AddRegisterUsers from "./AddRegisterUsers";
import { useEffect, useState } from "react";
import { useDeleteUserMutation, useGetManageUserQuery, UserData, useUserToggleMutation } from "../../../Redux/Service/manage.user";
import SearchComponent from "../../../components/SearchComponent";
import AlertDailog from "../../../components/AlertDailog";
import { toaster } from "../../../components/ui/toaster";
import Delete from "../../../components/ActionIcons/Delete";
import { delay } from "../../../components/Utils";
// import Delete from "../../../components/ActionIcons/Delete";

const tableHeadRow = [
  "Sr. No",
  "First Name",
  "Last Name",
  "Mobile Number",
  "Gender",
  "DOB",
  "Type Of User",
  "Default Language",
  "Active/Deactive",
  "Action",
];

// const registerUser: any[] = [
//   ...Array.from({ length: 12 }, (_, i) => ({
//     "Sr. No": i + 1,
//     "First Name": "Ritesh",
//     "Mobile Number": "akanksha@gmail.com",
//     "Gender": "9876543210",
//     "DOB": "Female",
//     "Type Of User": "15-01-1990",
//     "Language": "Mumbai",
//     "Activate/Deactivate": (
//       <Box>
//         <Switch size={'sm'} colorPalette={'teal'} />
//       </Box>
//     ),
//     "Action": (
//       <HStack justifyContent="center">
//         <ViewRegisterUsers />
//         <EditRegisterUsers />
//         {/* <RiDeleteBin5Line style={{ cursor: "pointer" }} /> */}
//         {/* <AlertDailog
//           AltertTiggerIcon={() =><Delete /> } // Pass as function
//           alertText="Delete Users"
//           alertIcon={<Image src={"DeleteIcon"} h={"39px"} />}
//           alertCaption="Are You Sure You Want To Delete This User ?"
//           onConfirm={() => {
//             console.log("User deleted:", i + 1);
//           }}
//         /> */}
//       </HStack>
//     ),
//   })),
// ];

const RegisterUsers = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const { data, refetch, isFetching, isError } = useGetManageUserQuery(currentPage)
  const [localData, setLocalData] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [userToggle] = useUserToggleMutation()
  const [deleteFaqPost] = useDeleteUserMutation()
  const [deleteModal, setDeleteModal] = useState(false)
  const [selectedFaqId, setSelectedFaqId] = useState<number | null>(null);

  console.log("Register Users Data", data?.data.data);

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

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

  const filteredData = localData?.filter((agency) => {
    const searchLower = searchTerm.toLowerCase();
    const firstName = agency.first_name?.toLowerCase().includes(searchLower);
    // const email = agency.capital?.toLowerCase().includes(searchLower);
    return firstName;
  });

  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 userToggle({ 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 handleDeleteFaq = async (faqId: number) => {
    try {
      const response = await deleteFaqPost({ id: faqId }).unwrap();
      if (response?.status === "success") {
        toaster.create({
          title: "Success",
          description: "User deleted successfully",
          type: "success",
        });
        refetch()
        console.log("User deleted successfully:", response);
      }
      // Optionally, refetch data or update state after deletion
    } catch (error) {
      console.error("Error deleting User:", error);
      toaster.create({
        title: "Error",
        description: "Something went wrong",
        type: "error",
      });
    }
  };

  const managepost = filteredData?.flatMap((agency: UserData, index: number) => ({
    "Sr. No": (currentPage - 1) * (data?.data.per_page ?? 0) + index + 1,
    "First Name": agency.first_name,
    "Last Name": agency.last_name,
    "Mobile Number": agency.phone_number,
    "Gender": agency.gender,
    "DOB": agency.date_of_birth ? new Date(agency.date_of_birth).toLocaleDateString('en-GB').replace(/\//g, '-') : 'N/A',
    "Type Of User": agency.principal_type?.principal_type_title || 'N/A',
    "Default Language": agency?.principle_language_linkss?.language?.language_name,
    "Active/Deactive": agency.is_active === true ? 'Active' : 'Inactive',
    "Action": (
      <HStack justifyContent="center">
        <EditRegisterUsers
          data={agency}
          refetch={refetch}
        />
        <ViewRegisterUsers data={agency} />
        <Box>
          <Switch
            colorPalette={'teal'}
            size={"xs"}
            checked={agency.is_active === true}
            onChange={() => handleToggle(agency.id, agency.is_active ? '1' : '0')}
          />
        </Box>
        <AlertDailog
          isOpen={deleteModal}
          AltertTiggerIcon={() => <Delete onClick={() => {
            setSelectedFaqId(agency.id);
            setDeleteModal(true)
          }} />}
          alertText="Do you want to delete user?"
          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);
            }
          }}
        />
      </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"}>
            Register Users
          </Text>

          <HStack>
            <SearchComponent
              value={searchTerm}
              onChange={(value) => {
                setSearchTerm(value);
                // setCurrentPage(1);
                refetch()
              }}
            />
            {/* <AddRegisterUsers /> */}
          </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>
    </MainFrame>
  );
};

export default RegisterUsers;
