import {
  Badge,
  Box,
  Button,
  HStack,
  Input,
  Switch,
  Text,
  Tooltip,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useState } from "react";
import { Link, Link as RouterLink } from "react-router-dom";
import { AddIcon, DeleteIcon, EditIcon } from "@chakra-ui/icons";
import { useNavigate } from "react-router-dom";
import { OPACITY_ON_LOAD } from "../../Layout/animations";
import NormalTable from "../../Components/DataTable/NormalTable";
import Pagination from "../../Components/Pagination";
import GlobalStateContext from "../../Contexts/GlobalStateContext";
import CustomAlertDialog from "../../Components/CustomAlertDialog";
import ToastBox from "../../Components/ToastBox";
import { TABLE_PAGINATION } from "../../Constants/Paginations";
import { generateSerialNumber } from "../../Constants/Constants";
import { useGetSponserMasterQuery } from "../../Services/io.service";
import {
  useGetSubAdminMasterQuery,
  useToggleStatusMutation,
} from "../../Services/subadmin.service";
import RoleSwitchButton from "../../Components/RoleSwitchButton";

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 { sponser, setSponser, 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("");
  const [isSwitchOn, setIsSwitchOn] = useState(true);

  // 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,
    error,
    isLoading: isSponserLoading,
  } = useGetSubAdminMasterQuery();

  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 ? 1 : 2,
    };
    try {
      const res = await toggleStatus(id, data).unwrap();
      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 = subAdmin?.data?.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, currentPage, pageSize)}
      </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 minW={24} isTruncated={true}>
        <Badge
          py={"2px"}
          px={"5px"}
          me={2}
          bg={item?.role[0]?.role === "Maker" ? "#00ffcc" : "#b3ff99"}
        >
          {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
            onClick={() => {
              setActionId(item?.id);
              setDeleteAlert(true);
            }}
            // _hover={{ color: "red.500" }}
            // color="red"
            rounded={"sm"}
            size={"xs"}
            colorScheme="red"
            variant={"solid"}
          >
            <DeleteIcon />
          </Button>
        </Tooltip> */}
      </Box>
    ),
  }));

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

  // const handleDelete = async () => {
  //   console.log(actionId);
  //   setIsLoading(true);
  //   try {
  //     const response = await deleteSponser(actionId);
  //     console.log(response?.data);
  //     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) {}
  // };

  console.log(isSponserLoading);

  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 sponers?"}
        // alertHandler={handleDelete}
        isLoading={isLoading}
      />
    </Box>
  );
};

export default SubAdmin;
