"use client";
import {
  TableCell,
  TableRow,
  Table,
  TableHeader,
  TableColumn,
  TableBody,
  Pagination,
  Dropdown,
  DropdownTrigger,
  DropdownMenu,
  DropdownItem,
  Input,
  User,
  Card,
  Divider,
  Chip,
  ChipProps,
} from "@nextui-org/react";
import { Button } from "@nextui-org/button";
import React, { Key, useCallback, useEffect, useMemo, useState } from "react";
import {
  AddIcon,
  CreateIconIon,
  DeleteIcon,
  DotsYIcon,
  EyeFilledIcon,
  EyeIconMdi,
} from "@/components/icons";
import Link from "next/link";
import { getAllUserLevels } from "@/services/user-levels/user-levels-service";

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

const statusColorMap = {
  active: "success",
  paused: "danger",
  vacation: "warning",
};

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

  type TableRow = (typeof masterUserLevelTable)[0];

  const columns = [
    { name: "No", uid: "no" },
    { name: "Name", uid: "name" },
    { name: "User Name", uid: "alias_name" },
    { name: "Level Number", uid: "level_number" },
    { name: "Parent Level", uid: "parent_level_id" },
    { name: "Province", uid: "province_id" },
    { name: "Status", uid: "is_active" },
    { name: "Action", uid: "actions" },
  ];

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

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

  async function fetchData() {
    const request = {
      page: page,
      limit: 10,
    };
    const res = await getAllUserLevels(request);
    const data = res?.data?.data;
    setTotalPage(Math.ceil(res?.data?.total / 10));
    initUserData(10, data);
  }

  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;
      });
      console.log("Data ::", newData);
      setmasterUserLevel(newData);
    }
  }

  const renderCell = useCallback(
    (masterUserLevel: TableRow, columnKey: Key) => {
      const cellValue = masterUserLevel[columnKey as keyof UserObject];
      const statusColorMap: Record<string, ChipProps["color"]> = {
        active: "success",
        cancel: "danger",
        pending: "warning",
      };

      switch (columnKey) {
        case "no":
          return <div>{masterUserLevel.id}</div>;

        case "name":
          return <div className="w-[150px]">{masterUserLevel.name}</div>;

        case "alias_Name":
          return <div className="">{masterUserLevel.aliasName}</div>;
        case "is_active":
          return (
            <Chip
              className="capitalize "
              color={statusColorMap[masterUserLevel.status]}
              size="lg"
              variant="flat"
            >
              <div className="flex flex-row items-center gap-2 justify-center">
                {cellValue}
              </div>
            </Chip>
          );

        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={`#`}>
                      <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;
      }
    },
    []
  );

  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">
          <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>
    </>
  );
}
