"use client";
import {
  TableCell,
  TableRow,
  Table,
  TableHeader,
  TableColumn,
  TableBody,
  Pagination,
  Dropdown,
  DropdownTrigger,
  DropdownMenu,
  DropdownItem,
  Input,
  User,
  Card,
  Divider,
  Chip,
  ChipProps,
} 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 { getAllUserLevels } from "@/services/user-levels/user-levels-service";
import { close, loading } from "@/config/swal";

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

export default function MasterUserLevelTable() {
  const [totalPage, setTotalPage] = useState(1);
  const [masterUserLevelTable, setmasterUserLevel] = useState<UserObject[]>([]);
  const [search, setSearch] = useState("");

  type TableRow = (typeof masterUserLevelTable)[0];

  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: "Province", uid: "province_id" },
    // { name: "Status", uid: "is_active" },
    { name: "Action", uid: "actions" },
  ];

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

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

  async function fetchData() {
    loading();
    const request = {
      page: page,
      limit: 10,
      search: search,
    };
    const res = await getAllUserLevels(request);
    const data = res?.data?.data;
    setTotalPage(Math.ceil(res?.data?.meta?.totalPage / 10));
    await initUserData(10, data);
    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);
    }
  }

  const findParentName = (data: string | number) => {
    let name = "-";

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

    return name;
  };

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

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

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

  async function doneTyping() {
    fetchData();
  }

  const renderCell = useCallback(
    (masterUserLevel: TableRow, columnKey: Key) => {
      const cellValue = masterUserLevel[columnKey as keyof UserObject];

      switch (columnKey) {
        case "parentLevelId":
          return <p className="text-black">{findParentName(cellValue)}</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;
      }
    },
    [masterUserLevelTable]
  );

  return (
    <>
      <div className="mx-3 my-5">
        {/* <Link href="/admin/master/master-user-level/create">
          <Button className="my-3 bg-blue-600 text-white">
            <CreateIconIon />
            Create New User Level
          </Button>
        </Link> */}
        <div className="flex flex-col items-center rounded-2xl">
          <div className="flex flex-col gap-1 w-full justify-start mb-3">
            <p className="font-semibold text-sm">Pencarian</p>
            <Input
              aria-label="Search"
              classNames={{
                inputWrapper: "bg-default-100",
                input: "text-sm",
              }}
              className="max-w-md"
              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>
          <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={columns}>
              {(column) => (
                <TableColumn key={column.uid}>{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">
            <Pagination
              isCompact
              showControls
              showShadow
              color="primary"
              classNames={{
                base: "bg-transparent",
                wrapper: "bg-transparent",
              }}
              page={page}
              total={totalPage}
              onChange={(page) => setPage(page)}
            />
          </div>
        </div>
      </div>
    </>
  );
}
