"use client";
import {
  TableCell,
  TableRow,
  Table,
  TableHeader,
  TableColumn,
  TableBody,
  Pagination,
  Dropdown,
  DropdownTrigger,
  DropdownMenu,
  DropdownItem,
  Input,
  User,
  Card,
  Divider,
  Chip,
  ChipProps,
  Checkbox,
  Switch,
} from "@heroui/react";
import { Button } from "@heroui/button";
import React, { Key, useCallback, useEffect, useMemo, useState } from "react";
import {
  AddIcon,
  CreateIconIon,
  DeleteIcon,
  DotsYIcon,
  EyeFilledIcon,
  EyeIconMdi,
  SearchIcon,
} from "@/components/icons";
import Link from "next/link";
import {
  changeIsApproval,
  getAllUserLevels,
} from "@/services/user-levels/user-levels-service";
import { close, error, loading } from "@/config/swal";
import { stringify } from "querystring";
import { getUnixTimestamp } from "@/utils/global";

type UserObject = {
  id: number;
  name: string;
  levelNumber: string;
  aliasName: string;
  parentLevelId: string;
  provinceId: string;
  status: string;
  isApprovalActive: boolean;
};

export default function MasterUserLevelTable() {
  const [totalPage, setTotalPage] = useState(1);
  const [masterUserLevelTable, setMasterUserLevel] = useState<UserObject[]>([]);
  const [search, setSearch] = useState("");
  const [doSetup, setDoSetup] = useState(false);
  const [userLevelAll, setUserLevelAll] = useState<UserObject[]>([]);
  const [selectAllLevel, setSelectAllLevel] = useState(false);
  const [selectedLevel, setSelectedLevel] = useState<string[]>([]);
  const [isSelected, setIsSelected] = useState(true);

  const columns = [
    { name: "No", uid: "no" },
    { name: "Name", uid: "name" },
    { name: "User Name", uid: "aliasName" },
    { name: "Level Number", uid: "levelNumber" },
    { name: "Parent", uid: "parentLevelId" },
    { name: "Action", uid: "actions" },
  ];
  const columns2 = [
    { name: "No", uid: "no" },
    { name: "Setup", uid: "setup" },
    { name: "Name", uid: "name" },
    { name: "User Name", uid: "aliasName" },
    { name: "Level Number", uid: "levelNumber" },
    { name: "Parent", uid: "parentLevelId" },
    { name: "Need Approval", uid: "approvalActive" },
    { name: "Action", uid: "actions" },
  ];

  const [page, setPage] = useState(1);

  useEffect(() => {
    console.log("level", selectedLevel);
  }, [selectedLevel]);

  useEffect(() => {
    fetchData();
  }, [page, selectedLevel]);

  useEffect(() => {
    fetchDataAll();
  }, []);

  async function fetchData() {
    loading();
    const request = {
      page: page,
      limit: 10,
      search: search,
      timeStamp: getUnixTimestamp(),
    };
    const res = await getAllUserLevels(request);
    const data = res?.data?.data;
    setTotalPage(Math.ceil(res?.data?.meta?.totalPage));
    await initUserData(10, data);
    close();
  }
  async function fetchDataAll() {
    loading();
    const request = {
      page: 1,
      limit: -1,
      search: "",
      timeStamp: getUnixTimestamp(),
    };
    const res = await getAllUserLevels(request);
    const data = res?.data?.data;
    setUserLevelAll(data);
    const temp = [];
    for (const element of data) {
      if (element.isApprovalActive) {
        temp.push(String(element.id));
      }
    }
    // setSelectedLevel(temp);
    close();
  }

  async function initUserData(limit: number, data?: any) {
    if (data) {
      console.log(data);
      const startIndex = limit * (page - 1);
      let iterate = 0;
      const newData = data.map((value: any) => {
        iterate++;
        value.no = startIndex + iterate;
        return value;
      });
      setMasterUserLevel(newData);
    }
  }

  let typingTimer: NodeJS.Timeout;
  const doneTypingInterval = 1500;

  const handleKeyUp = () => {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
  };

  const handleKeyDown = () => {
    clearTimeout(typingTimer);
  };

  async function doneTyping() {
    fetchData();
  }

  const doMapping = (status: boolean) => {
    setSelectAllLevel(status);
    if (status) {
      const temp = [];
      for (const element of userLevelAll) {
        temp.push(String(element.id));
      }
      setSelectedLevel(temp);
    } else {
      setSelectedLevel([]);
    }
  };

  const handleSelectedLevel = (id: string, checked: boolean) => {
    console.log("change", id, checked);
    const temp = [...selectedLevel];
    if (checked) {
      temp.push(id);
      setSelectedLevel(temp);
      if (temp.length === userLevelAll.length) {
        setSelectAllLevel(true);
      }
    } else {
      const newTemp = temp.filter((a) => a !== id);
      setSelectedLevel(newTemp);
      if (newTemp.length !== userLevelAll.length) {
        setSelectAllLevel(false);
      }
    }
  };

  const renderCell = useCallback(
    (masterUserLevel: UserObject, columnKey: Key) => {
      const findParentName = (data: string | number) => {
        let name = "-";

        for (let i = 9; i < userLevelAll?.length; i++) {
          const temp = userLevelAll[i];
          if (temp.id === Number(data)) {
            name = temp.name;
            break;
          }
        }

        return name;
      };

      const cellValue = masterUserLevel[columnKey as keyof UserObject];
      switch (columnKey) {
        case "parentLevelId":
          return (
            <p className="text-black">
              {findParentName(masterUserLevel.parentLevelId)}
            </p>
          );

        case "setup":
          return (
            <Checkbox
              key={masterUserLevel.id}
              isSelected={selectedLevel?.includes(String(masterUserLevel.id))}
              onValueChange={(e) =>
                handleSelectedLevel(String(masterUserLevel.id), e)
              }
            />
          );
        case "approvalActive":
          return (
            <p className="text-black">
              {masterUserLevel.isApprovalActive ? "Yes" : "No"}
            </p>
          );
        case "actions":
          return (
            <div className="relative flex justify-star items-center gap-2">
              <Dropdown className="lg:min-w-[150px] bg-black text-white shadow border ">
                <DropdownTrigger>
                  <Button isIconOnly size="lg" variant="light">
                    <DotsYIcon className="text-default-300" />
                  </Button>
                </DropdownTrigger>
                <DropdownMenu>
                  {/* <DropdownItem key="Detail">
                    <Link href={`/admin/magazine/detail`}>
                      <EyeIconMdi className="inline mr-2 mb-1" />
                      Detail
                    </Link>
                  </DropdownItem> */}
                  <DropdownItem key="Edit">
                    <Link href={`/admin/user-level/edit/${masterUserLevel.id}`}>
                      <CreateIconIon className="inline mr-2 mb-1" />
                      Edit
                    </Link>
                  </DropdownItem>
                  <DropdownItem key="Delete">
                    <Link href={`#`}>
                      <DeleteIcon
                        width={20}
                        height={16}
                        className="inline mr-2 mb-1"
                      />
                      Delete
                    </Link>
                  </DropdownItem>
                </DropdownMenu>
              </Dropdown>
            </div>
          );

        default:
          return cellValue;
      }
    },
    [selectedLevel, userLevelAll, masterUserLevelTable]
  );

  const saveApproval = async () => {
    const req = { ids: selectedLevel.join(","), isApprovalActive: isSelected };
    const res = await changeIsApproval(req);
    if (res?.error) {
      error(res?.message);
      return false;
    }
    fetchData();
  };

  return (
    <>
      <div className="mx-3 my-5">
        <div className="flex flex-col items-start rounded-2xl">
          <div className="flex flex-row gap-3 mb-3 w-full justify-start items-end">
            <div className="flex flex-col gap-1 w-auto justify-start">
              <p className="font-semibold text-sm">Pencarian</p>
              <Input
                aria-label="Search"
                classNames={{
                  inputWrapper: "bg-default-100",
                  input: "text-sm",
                }}
                className="w-[300px]"
                labelPlacement="outside"
                startContent={
                  <SearchIcon className="text-base text-default-400 pointer-events-none flex-shrink-0" />
                }
                type="text"
                onChange={(e) => setSearch(e.target.value)}
                onKeyUp={handleKeyUp}
                onKeyDown={handleKeyDown}
              />
            </div>
            <Button
              color="primary"
              onPress={() => setDoSetup(!doSetup)}
              className="px-2"
            >
              Settings Approval
            </Button>
            {doSetup && (
              <div className="flex items-center gap-2">
                Need Approval?
                <Switch isSelected={isSelected} onValueChange={setIsSelected} />
                {isSelected ? "Yes" : "No"}
                <Button
                  color="success"
                  className="text-white"
                  onPress={saveApproval}
                >
                  Save
                </Button>
              </div>
            )}
          </div>

          <Table
            // selectionMode="multiple"
            aria-label="micro issue table"
            className="rounded-xl"
            classNames={{
              th: "bg-white dark:bg-black text-black dark:text-white border-b-1 text-md",
              base: "bg-white dark:bg-black border",
              wrapper:
                "min-h-[50px] bg-transpararent text-black dark:text-white ",
            }}
          >
            <TableHeader columns={doSetup ? columns2 : columns}>
              {(column) => (
                <TableColumn key={column.uid}>
                  {column.uid === "setup" ? (
                    <Checkbox
                      isSelected={selectAllLevel}
                      onValueChange={(e) => {
                        doMapping(e);
                      }}
                    ></Checkbox>
                  ) : (
                    column.name
                  )}
                </TableColumn>
              )}
            </TableHeader>
            <TableBody
              items={masterUserLevelTable}
              emptyContent={"No data to display."}
            >
              {(item) => (
                <TableRow key={item.id}>
                  {(columnKey) => (
                    <TableCell>{renderCell(item, columnKey)}</TableCell>
                  )}
                </TableRow>
              )}
            </TableBody>
          </Table>
          <div className="mt-2 justify-center flex w-full">
            <Pagination
              isCompact
              showControls
              showShadow
              color="primary"
              classNames={{
                base: "bg-transparent",
                wrapper: "bg-transparent",
                item: "w-fit px-3",
                cursor: "w-fit px-3",
              }}
              page={page}
              total={totalPage}
              onChange={(page) => setPage(page)}
            />
          </div>
        </div>
      </div>
    </>
  );
}
