"use client";
import {
  BannerIcon,
  CloudUploadIcon,
  CreateIconIon,
  DeleteIcon,
  DotsYIcon,
  EyeIconMdi,
  SearchIcon,
  TimesIcon,
} from "@/components/icons";
import { close, error, loading, success } from "@/config/swal";
import {
  deleteArticle,
  getArticleByCategory,
  getArticleById,
  getListArticle,
} from "@/services/article";
import { Article } from "@/types/globals";
import { convertDateFormat } from "@/utils/global";
import { Button } from "@heroui/button";
import {
  Chip,
  ChipProps,
  Dropdown,
  DropdownItem,
  DropdownMenu,
  DropdownTrigger,
  Input,
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalHeader,
  Pagination,
  Select,
  SelectItem,
  Spinner,
  Switch,
  Table,
  TableBody,
  TableCell,
  TableColumn,
  TableHeader,
  TableRow,
  Textarea,
  useDisclosure,
} from "@heroui/react";
import Link from "next/link";
import { Fragment, Key, useCallback, useEffect, useState } from "react";
import Cookies from "js-cookie";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { Controller, useForm } from "react-hook-form";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useDropzone } from "react-dropzone";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { getComments } from "@/services/comment";

const columns = [
  { name: "No", uid: "no" },
  { name: "Nama", uid: "commentFromName" },
  { name: "Komentar", uid: "message" },
  { name: "Article", uid: "articleId" },
  { name: "Status", uid: "status" },

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

interface Category {
  id: number;
  title: string;
}

export default function CommentTable() {
  const MySwal = withReactContent(Swal);
  const router = useRouter();
  const [page, setPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);
  const [comments, setComments] = useState<any[]>([]);
  const [showData, setShowData] = useState("10");
  const [search, setSearch] = useState("");

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

  async function initState() {
    const req = {
      limit: showData,
      page: page,
      search: search,
    };
    const res = await getComments(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;
      });
      setComments(newData);
    } else {
      setComments([]);
    }
  };

  async function doDelete(id: any) {
    loading();
    const resDelete = await deleteArticle(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 openArticle = async (id: number) => {
    const res = await getArticleById(id);
    if (res?.error) {
      MySwal.fire({
        title: "Artikel tidak ditemukan atau telah dihapus",
        icon: "warning",
        showCancelButton: false,
        cancelButtonColor: "#3085d6",
        confirmButtonColor: "#d33",
        confirmButtonText: "Oke",
      }).then((result) => {
        if (result.isConfirmed) {
        }
      });
      return false;
    }
    router.push(`/news/detail/${id}-${res?.data?.data?.slug}`);
  };

  const renderCell = useCallback(
    (comment: any, columnKey: Key) => {
      const cellValue = comment[columnKey as keyof any];

      switch (columnKey) {
        case "articleId":
          return (
            <a
              onClick={() => openArticle(cellValue)}
              className="text-primary underline cursor-pointer"
            >
              Buka Article
            </a>
          );
        case "status":
          return (
            <p
              className={`${
                comment?.statusId == 1
                  ? "bg-success"
                  : comment?.statusId == 1
                  ? "bg-primary"
                  : comment?.statusId == 1
                  ? "bg-danger"
                  : "bg-warning"
              } text-white w-[180px] rounded-lg py-1 text-center`}
            >
              {comment?.statusId == 1
                ? "Disetujui"
                : comment?.statusId == 2
                ? "Dibalas"
                : comment?.statusId == 3
                ? "Ditolak"
                : "Menunggu Review"}
            </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="edit"
                    onPress={() =>
                      router.push(`/admin/comment/review/${comment.id}`)
                    }
                    className={comment.isPublic ? "hidden" : ""}
                  >
                    {comment.isPublic == false && (
                      <>
                        <CreateIconIon size={22} className="inline mr-2 mb-1" />
                        Review
                      </>
                    )}
                  </DropdownItem>

                  <DropdownItem
                    key="delete"
                    onPress={() => handleDelete(comment.id)}
                  >
                    <DeleteIcon
                      color="red"
                      size={18}
                      className="inline ml-1 mr-2 mb-1"
                    />
                    Delete
                  </DropdownItem>
                </DropdownMenu>
              </Dropdown>
            </div>
          );

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

  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>
          <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={comments}
              emptyContent={"No data to display."}
              loadingContent={<Spinner label="Loading..." />}
            >
              {(item: any) => (
                <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",
              }}
              page={page}
              total={totalPage}
              onChange={(page) => setPage(page)}
            />
          </div>
        </div>
      </div>
    </>
  );
}
