"use client";
import {
  CreateIconIon,
  DeleteIcon,
  DotsYIcon,
  EyeIconMdi,
} from "@/components/icons";
import { error } from "@/config/swal";
import { deleteMasterUser } from "@/services/master-user";
import {
  deleteMasterUserRole,
  listUserRole,
} from "@/services/master-user-role";
import { MasterUser, MasterUserRole } from "@/types/globals";
import { getUnixTimestamp } from "@/utils/global";
import { Button } from "@heroui/button";
import {
  Chip,
  ChipProps,
  Dropdown,
  DropdownItem,
  DropdownMenu,
  DropdownTrigger,
  Pagination,
  Spinner,
  Table,
  TableBody,
  TableCell,
  TableColumn,
  TableHeader,
  TableRow,
} from "@heroui/react";
import Link from "next/link";
import { Key, useCallback, useEffect, useState } from "react";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";

type UserObject = {
  id: number;
  user: string;
  status: string;
  projectName: string;
  avatar: string;
};

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

export default function MasterRoleTable() {
  const MySwal = withReactContent(Swal);
  const [role, setRole] = useState<MasterUserRole[]>([]);
  const [page, setPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);

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

  async function initState() {
    const res = await listUserRole({
      page: page,
      limit: 10,
      timeStamp: getUnixTimestamp(),
    });
    getTableNumber(10, res?.data?.data);
    setTotalPage(res?.data?.meta?.totalPage);
  }

  const getTableNumber = (limit: number, data?: any) => {
    if (data) {
      const startIndex = limit * (page - 1);
      let iterate = 0;
      const newData = data.map((value: any) => {
        iterate++;
        value.no = startIndex + iterate;
        return value;
      });
      setRole(newData);
    }
  };
  const columns = [
    { name: "No", uid: "no" },
    { name: "Role", uid: "name" },
    { name: "Description", uid: "description" },
    { name: "Code", uid: "code" },
    // { name: "Level Number", uid: "level_number" },
    // { name: "Status Id", uid: "status_id" },
    { name: "Aksi", uid: "actions" },
  ];

  async function doDelete(id: any) {
    // loading();
    const resDelete = await deleteMasterUserRole(id);

    if (resDelete?.error) {
      error(resDelete.message);
      return false;
    }
    close();
    successSubmit();
  }

  const handleDelete = (id: any) => {
    MySwal.fire({
      title: "Hapus Data",
      icon: "warning",
      showCancelButton: true,
      cancelButtonColor: "#3085d6",
      confirmButtonColor: "#d33",
      confirmButtonText: "Hapus",
    }).then((result) => {
      if (result.isConfirmed) {
        doDelete(id);
      }
    });
  };

  function successSubmit() {
    MySwal.fire({
      title: "Sukses",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then((result) => {
      if (result.isConfirmed) {
        initState();
      }
    });
  }

  // const statusOptions = [
  //     { name: "Active", uid: "active" },
  //     { name: "Paused", uid: "paused" },
  //     { name: "Vacation", uid: "vacation" },
  // ];

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

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

      case "status":
        return (
          <Chip
            className="capitalize "
            // color={statusColorMap[role.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] dark:bg-black dark: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/master-role/detail/${role.id}`}>
                    <EyeIconMdi className="inline mr-2 mb-1" />
                    Detail
                  </Link>
                </DropdownItem>
                {/* <DropdownItem>
                  <Link href={`/admin/master-role/edit/${role.id}`}>
                    <CreateIconIon className="inline mr-2 mb-1" />
                    Edit
                  </Link>
                </DropdownItem> */}
                <DropdownItem
                  key="delete"
                  onClick={() => handleDelete(role.id)}
                >
                  <DeleteIcon
                    color="red"
                    width={20}
                    height={16}
                    className="inline mr-2 mb-1"
                  />
                  Delete
                </DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </div>
        );

      default:
        return cellValue;
    }
  }, []);

  return (
    <>
      <div className="mx-3 my-5">
        <div className="flex flex-col items-center rounded-2xl">
          <Table
            // selectionMode="multiple"
            aria-label="micro issue table"
            className="rounded-2xl"
            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={role}
              emptyContent={"No data to display."}
              loadingContent={<Spinner label="Loading..." />}
            >
              {(item) => (
                <TableRow key={item.id}>
                  {(columnKey) => (
                    <TableCell>{renderCell(item, columnKey)}</TableCell>
                  )}
                </TableRow>
              )}
            </TableBody>
          </Table>
          <div className="my-2 w-full flex justify-center">
            <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>
    </>
  );
}
