"use client";
import {
  BannerIcon,
  CopyIcon,
  CreateIconIon,
  DeleteIcon,
  DotsYIcon,
  EyeIconMdi,
  SearchIcon,
  TimesIcon,
} from "@/components/icons";
import { close, error, loading, success, successToast } from "@/config/swal";
import {
  deleteArticle,
  getArticleByCategory,
  getListArticleAdminPage,
  updateIsBannerArticle,
} from "@/services/article";
import { Article } from "@/types/globals";
import {
  convertDateFormat,
  convertDateFormatNoTime,
  convertDateFormatNoTimeV2,
  getUnixTimestamp,
} from "@/utils/global";
import { Button } from "@heroui/button";
import {
  Autocomplete,
  AutocompleteItem,
  Calendar,
  Chip,
  ChipProps,
  Dropdown,
  DropdownItem,
  DropdownMenu,
  DropdownTrigger,
  Input,
  Pagination,
  Popover,
  PopoverContent,
  PopoverTrigger,
  Select,
  SelectItem,
  Spinner,
  Table,
  TableBody,
  TableCell,
  TableColumn,
  TableHeader,
  TableRow,
} from "@heroui/react";
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";
import Cookies from "js-cookie";
import { parseDate } from "@internationalized/date";
import { listMasterUsers } from "@/services/master-user";
import ReactSelect from "react-select";
import makeAnimated from "react-select/animated";

const columns = [
  { name: "No", uid: "no" },
  { name: "Judul", uid: "title" },
  { name: "Banner", uid: "isBanner" },
  { name: "Kategori", uid: "category" },
  { name: "Tanggal Unggah", uid: "createdAt" },
  { name: "Kreator", uid: "createdByName" },
  { name: "Status", uid: "isPublish" },
  { name: "Aksi", uid: "actions" },
];
const columnsOtherRole = [
  { name: "No", uid: "no" },
  { name: "Judul", uid: "title" },
  { name: "Kategori", uid: "category" },
  { name: "Tanggal Unggah", uid: "createdAt" },
  { name: "Kreator", uid: "createdByName" },
  { name: "Status", uid: "isPublish" },
  { name: "Aksi", uid: "actions" },
];

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

type ArticleData = Article & {
  no: number;
  createdAt: string;
  categories: Category[];
};

export default function ArticleTable() {
  const MySwal = withReactContent(Swal);
  const username = Cookies.get("username");
  const userId = Cookies.get("uie");
  const animatedComponents = makeAnimated();

  const [page, setPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);
  const [article, setArticle] = useState<any[]>([]);
  const [showData, setShowData] = useState("10");
  const [search, setSearch] = useState("");
  const [categories, setCategories] = useState<any>([]);
  const [users, setUsers] = useState<any>([]);
  const [selectedCategories, setSelectedCategories] = useState<any>([]);
  const [selectedUsers, setSelectedUsers] = useState<any>([]);
  const [startDateValue, setStartDateValue] = useState({
    startDate: null,
    endDate: null,
  });

  const [articleDate, setArticleDate] = useState<{
    startDate: any;
    endDate: any;
  }>({
    startDate: parseDate(
      convertDateFormatNoTimeV2(
        new Date(new Date().setDate(new Date().getDate() - 7))
      )
    ),
    endDate: parseDate(convertDateFormatNoTimeV2(new Date())),
  });

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

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

  const setupList = (data: any, type: string) => {
    const temp = [];
    if (data) {
      for (const element of data) {
        temp.push({
          id: element.id,
          label: element.title || element.fullname,
          value: element.id,
        });
      }
      if (type === "users") {
        setUsers(temp);
      }

      if (type === "category") {
        setCategories(temp);
      }
    }
  };

  async function getUsers() {
    const res = await listMasterUsers({
      page: page,
      limit: -1,
      timeStamp: getUnixTimestamp(),
    });
    setupList(res?.data?.data, "users");
  }

  async function getCategories() {
    const res = await getArticleByCategory(getUnixTimestamp());
    setupList(res?.data?.data, "category");
  }

  const onSelectionChange = (id: Key | null) => {
    setSelectedCategories(String(id));
  };

  const getDate = (data: any) => {
    if (data === null) {
      return "";
    } else {
      return `${data.year}-${data.month < 10 ? `0${data.month}` : data.month}-${
        data.day < 10 ? `0${data.day}` : data.day
      }`;
    }
  };

  const getIds = (data: { id: number; label: string; value: number }[]) => {
    let temp = "";
    if (data) {
      for (let i = 0; i < data.length; i++) {
        if (i == 0) {
          temp = String(data[i].id);
        } else {
          temp = temp + `,${data[i].id}`;
        }
      }
    }

    return temp;
  };

  async function initState() {
    loading();
    const req = {
      limit: showData,
      page: page,
      search: search,
      startDate: getDate(articleDate.startDate),
      endDate: getDate(articleDate.endDate),
      categoryIds: getIds(selectedCategories),
      createdByIds: getIds(selectedUsers),
      sort: "desc",
      sortBy: "created_at",
      timeStamp: getUnixTimestamp(),
    };
    const res = await getListArticleAdminPage(req);
    await getTableNumber(parseInt(showData), res.data?.data);
    setTotalPage(res?.data?.meta?.totalPage);
    close();
  }

  const getTableNumber = async (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 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 handleBanner = async (id: number, status: boolean) => {
    const res = await updateIsBannerArticle(id, status);
    if (res?.error) {
      error(res?.message);
      return false;
    }
    initState();
  };

  const copyUrlArticle = async (id: number, slug: string) => {
    const url =
      `${window.location.protocol}//${window.location.host}` +
      "/news/detail/" +
      `${id}-${slug}`;
    try {
      await navigator.clipboard.writeText(url);
      successToast("Success", "Article Copy to Clipboard");
      setTimeout(() => {}, 1500);
    } catch (err) {
      ("Failed to copy!");
    }
  };

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

      switch (columnKey) {
        case "isPublish":
          return (
            // <Chip
            //   className="capitalize "
            //   color={statusColorMap[article.status]}
            //   size="lg"
            //   variant="flat"
            // >
            //   <div className="flex flex-row items-center gap-2 justify-center">
            //     {article.status}
            //   </div>
            // </Chip>
            <p>{article.isPublish ? "Publish" : "Draft"}</p>
          );
        case "isBanner":
          return <p>{article.isBanner ? "Ya" : "Tidak"}</p>;
        case "createdAt":
          return <p>{convertDateFormat(article.createdAt)}</p>;
        case "category":
          return (
            <p>
              {article?.categories?.map((list: any) => list.title).join(", ") +
                " "}
            </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="copy-article"
                    onPress={() => copyUrlArticle(article.id, article.slug)}
                  >
                    <CopyIcon className="inline mr-2 mb-1" />
                    Copy Url Article
                  </DropdownItem>
                  <DropdownItem key="detail">
                    <Link href={`/admin/article/detail/${article.id}`}>
                      <EyeIconMdi className="inline mr-2 mb-1" />
                      Detail
                    </Link>
                  </DropdownItem>
                  <DropdownItem
                    key="edit"
                    className={
                      username?.includes("mabes") ||
                      Number(userId) === article.createdById
                        ? ""
                        : "hidden"
                    }
                  >
                    {(username?.includes("mabes") ||
                      Number(userId) === article.createdById) && (
                      <Link href={`/admin/article/edit/${article.id}`}>
                        <CreateIconIon className="inline mr-2 mb-1" />
                        Edit
                      </Link>
                    )}
                  </DropdownItem>
                  <DropdownItem
                    key="setBanner"
                    onPress={() =>
                      handleBanner(article?.id, !article?.isBanner)
                    }
                    className={username?.includes("mabes") ? "" : "hidden"}
                  >
                    {username?.includes("mabes") && (
                      <>
                        <BannerIcon size={24} className="inline mr-2 mb-1" />
                        {article?.isBanner
                          ? "Hapus dari Banner"
                          : "Jadikan Banner"}
                      </>
                    )}
                  </DropdownItem>
                  <DropdownItem
                    key="delete"
                    onPress={() => handleDelete(article.id)}
                    className={
                      username?.includes("mabes") ||
                      Number(userId) === article.createdById
                        ? ""
                        : "hidden"
                    }
                  >
                    {(username?.includes("mabes") ||
                      Number(userId) === article.createdById) && (
                      <>
                        {" "}
                        <DeleteIcon
                          color="red"
                          size={18}
                          className="inline ml-1 mr-2 mb-1"
                        />
                        Delete
                      </>
                    )}
                  </DropdownItem>
                </DropdownMenu>
              </Dropdown>
            </div>
          );

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

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

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

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

  async function doneTyping() {
    setPage(1);
    initState();
  }

  const [hasMounted, setHasMounted] = useState(false);

  useEffect(() => {
    setHasMounted(true);
  }, []);

  // Render
  if (!hasMounted) return null;

  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>
                <SelectItem key="25">25</SelectItem>
                <SelectItem key="50">50</SelectItem>
              </Select>
            </div>
            <div className="flex flex-col gap-1 w-full lg:w-[230px]">
              <p className="font-semibold text-sm">Kategori</p>
              <ReactSelect
                className="basic-single text-black z-40"
                classNames={{
                  control: (state: any) =>
                    "!rounded-lg bg-white !border-1 !border-gray-200 dark:!border-stone-500",
                }}
                classNamePrefix="select"
                onChange={setSelectedCategories}
                closeMenuOnSelect={false}
                components={animatedComponents}
                isClearable={true}
                isSearchable={true}
                isMulti={true}
                placeholder="Kategori..."
                name="sub-module"
                options={categories}
                // styles={{
                //   control: (base) => ({
                //     ...base,
                //     width: "100%",
                //     overflowX: "auto",
                //   }),
                //   valueContainer: (base) => ({
                //     ...base,
                //     display: "flex",
                //     flexWrap: "nowrap",
                //     overflowX: "auto",
                //     whiteSpace: "nowrap",
                //     gap: "4px",
                //   }),
                //   multiValue: (base) => ({
                //     ...base,
                //     whiteSpace: "nowrap",
                //     flexShrink: 0,
                //   }),
                //   multiValueLabel: (base) => ({
                //     ...base,
                //     whiteSpace: "nowrap",
                //   }),
                // }}
              />
            </div>
            {username?.includes("mabes") && (
              <div className="flex flex-col gap-1 w-full lg:w-[230px]">
                <p className="font-semibold text-sm">Author</p>

                <ReactSelect
                  className="basic-single text-black z-40"
                  classNames={{
                    control: (state: any) =>
                      "!rounded-lg bg-white !border-1 !border-gray-200 dark:!border-stone-500",
                  }}
                  classNamePrefix="select"
                  onChange={setSelectedUsers}
                  closeMenuOnSelect={false}
                  components={animatedComponents}
                  isClearable={true}
                  isSearchable={true}
                  isMulti={true}
                  placeholder="Author..."
                  name="sub-module"
                  options={users}
                />
              </div>
            )}
            <div className="flex flex-col gap-1 w-full lg:w-[140px]">
              <p className="font-semibold text-sm">Start Date</p>

              <Popover
                placement="bottom"
                classNames={{ content: ["!bg-transparent", "p-0"] }}
              >
                <PopoverTrigger>
                  <div className="flex flex-row gap-1 items-center cursor-pointer border-1 px-2 py-2 rounded-xl">
                    <a className=" w-[120px]">
                      {articleDate.startDate
                        ? convertDateFormatNoTime(articleDate.startDate)
                        : "-"}
                    </a>
                    {articleDate.startDate && (
                      <a
                        onClick={() =>
                          setArticleDate({
                            startDate: null,
                            endDate: articleDate.endDate,
                          })
                        }
                      >
                        <TimesIcon size={16} />
                      </a>
                    )}
                  </div>
                </PopoverTrigger>
                <PopoverContent className="bg-transparent">
                  <Calendar
                    value={articleDate.startDate}
                    onChange={(e) =>
                      setArticleDate({
                        startDate: e,
                        endDate: articleDate.endDate,
                      })
                    }
                    maxValue={articleDate.endDate}
                  />
                </PopoverContent>
              </Popover>
            </div>
            <div className="flex flex-col gap-1 w-full lg:w-[140px]">
              <p className="font-semibold text-sm">End Date</p>

              <Popover
                placement="bottom"
                classNames={{ content: ["!bg-transparent", "p-0"] }}
              >
                <PopoverTrigger>
                  <div className="flex flex-row gap-1 items-center cursor-pointer border-1 px-2 py-2 rounded-xl">
                    <a className=" w-[120px]">
                      {articleDate.endDate
                        ? convertDateFormatNoTime(articleDate.endDate)
                        : "-"}
                    </a>
                    {articleDate.endDate && (
                      <a
                        onClick={() =>
                          setArticleDate({
                            endDate: null,
                            startDate: articleDate.startDate,
                          })
                        }
                      >
                        <TimesIcon size={16} />
                      </a>
                    )}
                  </div>
                </PopoverTrigger>
                <PopoverContent className="bg-transparent">
                  <Calendar
                    value={articleDate.endDate}
                    onChange={(e) =>
                      setArticleDate({
                        startDate: articleDate.startDate,
                        endDate: e,
                      })
                    }
                    minValue={articleDate.startDate}
                  />
                </PopoverContent>
              </Popover>
            </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={username?.includes("mabes") ? columns : columnsOtherRole}
            >
              {(column) => (
                <TableColumn key={column.uid}>{column.name}</TableColumn>
              )}
            </TableHeader>
            <TableBody
              items={article}
              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",
                item: "w-fit px-3",
                cursor: "w-fit px-3",
              }}
              page={page}
              total={totalPage}
              onChange={(page) => setPage(page)}
            />
          </div>
        </div>
      </div>
    </>
  );
}
