import { AddIcon, DeleteIcon, EditIcon } from "@chakra-ui/icons";
import {
  Badge,
  Box,
  Button,
  HStack,
  Input,
  Switch,
  Text,
  Tooltip,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import CustomAlertDialog from "../../Components/CustomAlertDialog";
import NormalTable from "../../Components/DataTable/NormalTable";
import ToastBox from "../../Components/ToastBox";
import {
  CHECKER_ID,
  generateSerialNumber,
  MAKER_ID,
  SUPER_ADMIN_ID,
} from "../../Constants/Constants";
import GlobalStateContext from "../../Contexts/GlobalStateContext";
import { OPACITY_ON_LOAD } from "../../Layout/animations";
import {
  useDeleteUserMutation,
  useGetSubAdminMasterQuery,
  useToggleStatusMutation,
} from "../../Services/subadmin.service";

export const formatDate = (date) => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0"); // Months are 0-indexed
  const day = String(d.getDate()).padStart(2, "0");

  return `${day}/${month}/${year}`;
};

const SubAdmin = () => {
  const navigate = useNavigate();
  const toast = useToast();
  const [isLoading, setIsLoading] = useState(false);
  const [deleteAlert, setDeleteAlert] = useState(false);
  const [actionId, setActionId] = useState(false);
  const [mouseEntered, setMouseEntered] = useState(false);
  const [mouseEnteredId, setMouseEnteredId] = useState("");
  //   const [deleteSponser] = useDeleteSponserMutation();
  const { slideFromRight } = useContext(GlobalStateContext);

  // =========================== [Use State] =============================
  // const [pageSize, setPageSize] = useState(TABLE_PAGINATION?.size);
  // const [currentPage, setCurrentPage] = useState(TABLE_PAGINATION?.page);
  const [searchTerm, setSearchTerm] = useState("");
  // const [debouncedSearchTerm, setDebouncedSearchTerm] = useState("");

  // Debounce the search term to avoid making a request on every keystroke
  // useEffect(() => {
  //   const handler = setTimeout(() => {
  //     setDebouncedSearchTerm(searchTerm);
  //   }, 500); // Adjust delay as needed
  //   return () => {
  //     clearTimeout(handler);
  //   };
  // }, [searchTerm]);

  const { data: subAdmin, isLoading: isSponserLoading } =
    useGetSubAdminMasterQuery();

  const [deleteUser] = useDeleteUserMutation();

  const [toggleStatus] = useToggleStatusMutation();

  // useEffect(() => {
  //   if (subAdmin?.data) {
  //     setIsSwitchOn(subAdmin?.role?.role);
  //     console.log(subAdmin);
  //   }
  // }, [subAdmin]);

  // ==============================[Table Filter]========================

  const filteredData = subAdmin?.data?.filter((item) => {
    const name = item.firstName;
    const searchLower = searchTerm?.toLowerCase();
    const nameMatches = name?.toLowerCase().includes(searchLower);
    return nameMatches;
  });

  const handleToggleStatus = async (isMaker, id) => {
    // console.log("hit");
    const data = {
      role_xid: isMaker ? CHECKER_ID : MAKER_ID,
    };
    console.log("=======================", data);
    try {
      const res = await toggleStatus({ id, data });
      if (res?.error) {
        toast({
          render: () => (
            <ToastBox status={"error"} message={res?.error?.data?.message} />
          ),
        });
      } else if (res) {
        toast({
          render: () => (
            <ToastBox
              status={"success"}
              message={res?.message || "Status updated successfully!"}
            />
          ),
        });
      }
    } catch (error) {
      toast({
        render: () => (
          <ToastBox
            status={"error"}
            message={error?.data?.message || "Something went wrong"}
          />
        ),
      });
    }
  };

  // ====================================================[Table Setup]================================================================

  const tableHeadRow = [
    "Sr No",
    "First Name",
    "Last Name",
    "Email Address",
    "Role",
    "Action",
  ];

  const extractedArray = filteredData?.map((item, index) => ({
    "Sr No": (
      <Text
        w={"24px"}
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center fw-bold web-text-small"
      >
        {/* {item.id} */}
        {generateSerialNumber(index)}
      </Text>
    ),
    "First Name": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item?.firstName}
      </Text>
    ),
    "Last Name": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item?.lastName}
      </Text>
    ),
    "Email Address": (
      <Box isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item?.emailAddress}
        </Text>
      </Box>
    ),
    Role: (
      <Box isTruncated={true}>
        <Badge
          py={"2px"}
          me={2}
          fontWeight={600}
          bg={item?.role[0]?.role === "Maker" ? "#00ffcc" : "#b3ff99"}
          px={item?.role[0]?.role === "Maker" ? "12px" : "5px"}
        >
          {item?.role[0]?.role}
        </Badge>
        {/* <Switch
          onChange={() =>
            handleToggleStatus(item?.role[0]?.role === "Maker", item?.id)
          }
          isChecked={item?.role[0]?.role === "Maker"}
          // colorScheme={item?.role[0]?.role === "Maker" ? "green" : "teal"}
          sx={{
            ".chakra-switch__track": {
              bg: item?.role[0]?.role === "Maker" ? "#00ffcc" : "#b3ff99", // "Off" state color
            },
          }}
        /> */}
        {/* <RoleSwitchButton
        setIsSwitchOn={setIsSwitchOn}
          isSwitchOn={item?.role[0]?.role === "Maker"}
          onClick={() => handleToggleStatus(item?.role[0]?.role=== "Maker")}
        /> */}
      </Box>
    ),
    Action: (
      <Box display={"flex"} justifyContent={"center"} gap={2}>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Edit"
          bg="#fff"
          color={"blue.500"}
          placement="top"
        >
          <Button
            onClick={() => navigate(`/subadmin/subadmin-update/${item.id}`)}
            // _hover={{ color: "blue.500" }}
            // color="blue.400"
            rounded={"sm"}
            size={"xs"}
            colorScheme="blue"
          >
            <EditIcon />
          </Button>
        </Tooltip>

        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Delete"
          bg="#fff"
          color={"red.500"}
          placement="top"
        >
          <Button
          isDisabled={item?.id === SUPER_ADMIN_ID}
            onClick={() => {
              setActionId(item?.id);
              setDeleteAlert(true);
            }}
            // _hover={{ color: "red.500" }}
            // color="red"
            // disabled={true}
            rounded={"sm"}
            size={"xs"}
            colorScheme="red"
            variant={"solid"}
          >
            <DeleteIcon />
          </Button>
        </Tooltip>
      </Box>
    ),
  }));

  // ===========================  [ Delete Function ] =================================

  const handleDelete = async () => {
    setIsLoading(true);
    try {
      const response = await deleteUser(actionId);
      if (response?.error?.data?.code === 400) {
        toast({
          render: () => (
            <ToastBox
              message={response?.error?.data?.message}
              status={"error"}
            />
          ),
        });
        setIsLoading(false);
        setDeleteAlert(false);
      } else if (
        response?.data?.statusCode === 201 ||
        response?.data?.statusCode === 200
      ) {
        toast({
          render: () => (
            <ToastBox message={response?.data?.message} status={"success"} />
          ),
        });
        setIsLoading(false);
        setDeleteAlert(false);
      }
    } catch (error) {}
  };

  return (
    <Box {...OPACITY_ON_LOAD} overflowY={"scroll"} height={"100vh"} pb={38}>
      <Box bg="white.500">
        <HStack
          display={"flex"}
          justifyContent={"space-between"}
          ps={1}
          pe={1}
          pb={4}
          pt={4}
          spacing="24px"
        >
          {/* =======================[Search Input]======================== */}

          <Input
            type="search"
            width={300}
            placeholder="Search..."
            size="sm"
            rounded="sm"
            focusBorderColor="green.500"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />

          <HStack display={"flex"} alignItems={"center"}>
            {/* ====================[Pagination]===================== */}

            {/* <Pagination
              isLoading={isSponserLoading}
              pageSize={pageSize}
              setPageSize={setPageSize}
              currentPage={currentPage}
              setCurrentPage={setCurrentPage}
              totalItems={subAdmin?.data?.totalItems}
            /> */}

            {/* =====================[Add Button]===================== */}

            <Link to={"/subadmin/subadmin-update"}>
              <Button
                leftIcon={<AddIcon />}
                colorScheme={"forestGreen"}
                rounded={"sm"}
                fontSize={"xs"}
                size={"sm"}
              >
                Add
              </Button>
            </Link>
          </HStack>
        </HStack>
      </Box>

      {/* =================== [Data Table] ===================== */}

      <NormalTable
        emptyMessage={`We don't have any Sponers `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={isSponserLoading}
        viewActionId={actionId}
        setViewActionId={setActionId}
        setMouseEnteredId={setMouseEnteredId}
        setMouseEntered={setMouseEntered}
      />

      {/* ========================  [Modal]  ======================== */}

      <CustomAlertDialog
        onClose={() => setDeleteAlert(false)}
        isOpen={deleteAlert}
        message={"Are you sure you want to delete sub-admin?"}
        alertHandler={handleDelete}
        isLoading={isLoading}
      />
    </Box>
  );
};

export default SubAdmin;
