"use client";
import {
  CreateIconIon,
  DeleteIcon,
  DotsYIcon,
  EyeIconMdi,
  SearchIcon,
} from "@/components/icons";
import { error, loading, success } from "@/config/swal";
import {
  deleteArticle,
  getArticleByCategory,
  getListArticle,
} from "@/services/article";
import { deleteMagazine, getListMagazine } from "@/services/magazine";
import { Article } from "@/types/globals";
import { convertDateFormat, getUnixTimestamp } from "@/utils/global";
import { Button } from "@heroui/button";
import {
  Chip,
  ChipProps,
  Dropdown,
  DropdownItem,
  DropdownMenu,
  DropdownTrigger,
  Input,
  Pagination,
  Select,
  SelectItem,
  Spinner,
  Table,
  TableBody,
  TableCell,
  TableColumn,
  TableHeader,
  TableRow,
} from "@heroui/react";
import { timeStamp } from "console";
import Link from "next/link";
import { Key, useCallback, useEffect, useState } from "react";
import Datepicker from "react-tailwindcss-datepicker";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";

const columns = [
  { name: "No", uid: "no" },
  { name: "Judul", uid: "title" },
  // { name: "Kategori", uid: "categoryName" },
  { name: "Tanggal Unggah", uid: "createdAt" },
  { name: "Kreator", uid: "createdByName" },

  { name: "Aksi", uid: "actions" },
];

type ArticleData = Article & {
  no: number;
  createdAt: string;
};

export default function MagazineTable() {
  const MySwal = withReactContent(Swal);
  const [page, setPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);
  const [article, setArticle] = useState<ArticleData[]>([]);
  const [showData, setShowData] = useState("10");
  const [search, setSearch] = useState("");
  const [categories, setCategoies] = useState<any>([]);
  const [selectedCategories, setSelectedCategories] = useState<any>([]);
  const [startDateValue, setStartDateValue] = useState({
    startDate: null,
    endDate: null,
  });

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

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

  async function getCategories() {
    const res = await getArticleByCategory(getUnixTimestamp());
    const data = res?.data?.data;
    setCategoies(data);
  }

  async function initState() {
    const req = {
      limit: showData,
      page: page,
      search: search,
      startDate:
        startDateValue.startDate === null ? "" : startDateValue.startDate,
      endDate: startDateValue.endDate === null ? "" : startDateValue.endDate,
      timeStamp: getUnixTimestamp(),
    };
    const res = await getListMagazine(req);
    getTableNumber(parseInt(showData), res.data?.data);
    setTotalPage(res?.data?.meta?.totalPage);
  }

  const getTableNumber = (limit: number, data: Article[]) => {
    if (data) {
      const startIndex = limit * (page - 1);
      let iterate = 0;
      const newData = data.map((value: any) => {
        iterate++;
        value.no = startIndex + iterate;
        return value;
      });
      setArticle(newData);
    } else {
      setArticle([]);
    }
  };

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

    if (resDelete?.error) {
      error(resDelete.message);
      return false;
    }
    close();
    success("Berhasil Hapus");
    initState();
  }

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

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

    switch (columnKey) {
      case "status":
        return (
          <Chip
            className="capitalize "
            color={statusColorMap[article.status]}
            size="lg"
            variant="flat"
          >
            <div className="flex flex-row items-center gap-2 justify-center">
              {cellValue}
            </div>
          </Chip>
        );
      case "createdAt":
        return <p>{convertDateFormat(article.createdAt)}</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/${article.id}`}>
                    <EyeIconMdi className="inline mr-2 mb-1" />
                    Detail
                  </Link>
                </DropdownItem>
                <DropdownItem key="edit">
                  <Link href={`/admin/magazine/edit/${article.id}`}>
                    <CreateIconIon className="inline mr-2 mb-1" />
                    Edit
                  </Link>
                </DropdownItem>
                <DropdownItem
                  key="delete"
                  onClick={() => handleDelete(article.id)}
                >
                  <DeleteIcon
                    color="red"
                    width={20}
                    height={16}
                    className="inline mr-2 mb-1"
                  />
                  Delete
                </DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </div>
        );

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

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

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

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

  async function doneTyping() {
    initState();
  }

  return (
    <>
      <div className="py-3">
        <div className="flex flex-col items-start rounded-2xl gap-3">
          <div className="flex flex-col md:flex-row gap-3 w-full">
            <div className="flex flex-col gap-1 w-full lg:w-1/3">
              <p className="font-semibold text-sm">Pencarian</p>
              <Input
                aria-label="Search"
                classNames={{
                  inputWrapper: "bg-default-100",
                  input: "text-sm",
                }}
                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>
            <div className="flex flex-col gap-1 w-full lg:w-[72px]">
              <p className="font-semibold text-sm">Data</p>
              <Select
                label=""
                variant="bordered"
                labelPlacement="outside"
                placeholder="Select"
                selectedKeys={[showData]}
                className="w-full"
                classNames={{ trigger: "border-1" }}
                onChange={(e) =>
                  e.target.value === "" ? "" : setShowData(e.target.value)
                }
              >
                <SelectItem key="5">5</SelectItem>
                <SelectItem key="10">10</SelectItem>
              </Select>
            </div>
            {/* <div className="flex flex-col gap-1 w-[230px]">
              <p className="font-semibold text-sm">Kategori</p>
              <Select
                label=""
                variant="bordered"
                labelPlacement="outside"
                placeholder="Select"
                selectionMode="multiple"
                selectedKeys={[selectedCategories]}
                className="w-full"
                classNames={{ trigger: "border-1" }}
                onChange={(e) => {
                  e.target.value === ""
                    ? ""
                    : setSelectedCategories(e.target.value);
                }}
              >
                {categories?.map((category: any) => (
                  <SelectItem key={category?.id} value={category?.id}>
                    {category?.title}
                  </SelectItem>
                ))}
              </Select>
            </div> */}
            {/* <div className="flex flex-col gap-1 w-full lg:w-[240px]">
              <p className="font-semibold text-sm">Tanggal</p>
              <Datepicker
                value={startDateValue}
                displayFormat="DD/MM/YYYY"
                onChange={(e: any) => setStartDateValue(e)}
                inputClassName="z-50 w-full text-sm bg-transparent border-1 border-gray-200 px-2 py-[6px] rounded-xl h-[40px] text-gray-600 dark:text-gray-300"
              />
            </div> */}
          </div>
          <Table
            aria-label="micro issue table"
            className="rounded-3xl"
            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={article}
              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>
    </>
  );
}
