"use client";
import {
  BannerIcon,
  CloudUploadIcon,
  CreateIconIon,
  DeleteIcon,
  DotsYIcon,
  ExportIcon,
  EyeIconMdi,
  SearchIcon,
  TimesIcon,
} from "@/components/icons";
import { close, error, loading, success } from "@/config/swal";
import {
  deleteArticle,
  getArticleByCategory,
  getListArticle,
} from "@/services/article";
import { Article } from "@/types/globals";
import {
  convertDateFormat,
  convertDateFormatNoTime,
  convertDateFormatNoTimeV2,
  getUnixTimestamp,
} from "@/utils/global";
import { Button } from "@heroui/button";
import {
  Calendar,
  Chip,
  ChipProps,
  Dropdown,
  DropdownItem,
  DropdownMenu,
  DropdownTrigger,
  Input,
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalHeader,
  Pagination,
  Popover,
  PopoverContent,
  PopoverTrigger,
  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 SuggestionsChart from "@/components/main/dashboard/chart/suggestions-line-chart";
import { parseDate } from "@internationalized/date";
import {
  deleteFeedback,
  getFeedbacks,
  getFeedbacksById,
} from "@/services/feedbacks";
import * as XLSX from "xlsx";
import {
  Document,
  Packer,
  Paragraph,
  Table as DocxTable,
  TableCell as DocxTableCell,
  TableRow as DocxTableRow,
  TextRun,
  WidthType,
} from "docx";
import { timeStamp } from "console";

interface ExportData {
  no: string;
  commentFromName: string;
  commentFromEmail: string;
  message: string;
}

const columns = [
  { name: "No", uid: "no" },
  { name: "Nama", uid: "commentFromName" },
  { name: "Email", uid: "commentFromEmail" },
  { name: "Kritik & Saran", uid: "message" },
  { name: "Aksi", uid: "actions" },
];

const createArticleSchema = z.object({
  id: z.string().optional(),
  commentFromName: z.string().min(2, {
    message: "Nama harus diisi",
  }),
  commentFromEmail: z.string().min(2, {
    message: "Email harus diisi",
  }),
  description: z.string().min(2, {
    message: "Pesan harus diisi",
  }),
  file: z.string().optional(),
});

export default function SuggestionsTable() {
  const MySwal = withReactContent(Swal);
  const { isOpen, onOpen, onOpenChange, onClose } = useDisclosure();

  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 [isReply, setIsReply] = useState(false);
  const [replyValue, setReplyValue] = useState("");
  const [totalData, setTotalData] = useState(0);
  const [feedbackDate, setFeedbackDate] = useState({
    startDate: parseDate(
      convertDateFormatNoTimeV2(
        new Date(new Date().setDate(new Date().getDate() - 7))
      )
    ),
    endDate: parseDate(convertDateFormatNoTimeV2(new Date())),
  });

  const formOptions = {
    resolver: zodResolver(createArticleSchema),
    defaultValues: {
      commentFromName: "",
      description: "",
      commentFromEmail: "",
      file: "",
    },
  };

  type UserSettingSchema = z.infer<typeof createArticleSchema>;
  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<UserSettingSchema>(formOptions);

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

  async function initState() {
    const getDate = (data: any) => {
      return `${data.year}-${data.month < 10 ? `0${data.month}` : data.month}-${
        data.day < 10 ? `0${data.day}` : data.day
      }`;
    };
    const res = await getFeedbacks({
      limit: showData,
      search: search,
      startDate: getDate(feedbackDate.startDate),
      endDate: getDate(feedbackDate.endDate),
      timeStamp: getUnixTimestamp(),
    });
    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: number) {
    loading();
    const resDelete = await deleteFeedback(id);

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

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

  const onSubmit = async (values: z.infer<typeof createArticleSchema>) => {
    loading();
    const formData = {
      commentFromName: values.commentFromName,
      message: values.description,
      commentFromEmail: values.commentFromEmail,
    };
    console.log("dataas", formData);
    close();
    // setRefresh(!refresh);
    // MySwal.fire({
    //   title: "Sukses",
    //   icon: "success",
    //   confirmButtonColor: "#3085d6",
    //   confirmButtonText: "OK",
    // }).then((result) => {
    //   if (result.isConfirmed) {
    //   }
    // });
  };

  const openModal = async (id: number) => {
    const res = await getFeedbacksById(id);
    const data = res?.data?.data;
    setValue("id", String(data?.id));
    setValue("commentFromName", data?.commentFromName);
    setValue("commentFromEmail", data?.commentFromEmail);
    setValue("description", data?.message);

    onOpen();
  };

  const getMonthYearName = (date: any) => {
    const newDate = new Date(date);

    const months = [
      "Januari",
      "Februari",
      "Maret",
      "April",
      "Mei",
      "Juni",
      "Juli",
      "Agustus",
      "September",
      "Oktober",
      "November",
      "Desember",
    ];
    const year = newDate.getFullYear();

    const month = months[newDate.getMonth()];
    return month + " " + year;
  };

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

      switch (columnKey) {
        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/suggestion/detail/${article.id}`}>
                      <EyeIconMdi className="inline mr-2 mb-1" />
                      Detail
                    </Link>
                  </DropdownItem> */}
                  <DropdownItem
                    key="edit"
                    onPress={() => openModal(suggestion.id)}
                  >
                    <CreateIconIon className="inline mr-2 mb-1" />
                    Detail
                  </DropdownItem>
                  <DropdownItem
                    key="export"
                    onPress={() =>
                      exportToWord({
                        no: suggestion.no,
                        commentFromName: suggestion.commentFromName,
                        commentFromEmail: suggestion.commentFromEmail,
                        message: suggestion.message,
                      })
                    }
                  >
                    <ExportIcon className="inline mr-2 mb-1" />
                    Export
                  </DropdownItem>

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

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

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

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

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

  async function doneTyping() {
    initState();
  }

  const [startDateValue, setStartDateValue] = useState(
    parseDate(convertDateFormatNoTimeV2(new Date()))
  );
  const [typeDate, setTypeDate] = useState("monthly");

  const doExport = async () => {
    const res = await getFeedbacks({
      limit: showData,
      search: search,
      timeStamp: getUnixTimestamp(),
    });
    if (res?.data?.data) {
      exportRecap(res?.data?.data);
    }
  };

  const exportRecap = (data: any) => {
    let temp: any = [];
    let no = 0;

    const worksheet = XLSX.utils.json_to_sheet([]);

    data.map((list: any) => {
      no += 1;
      const now = [
        no,
        list.commentFromName,
        list.commentFromEmail,
        list.message,
      ];
      temp.push(now);
    });

    XLSX.utils.sheet_add_aoa(
      worksheet,
      [["No", "Nama", "Email", "Kritik & Saran"]],
      {
        origin: "A1",
      }
    );
    XLSX.utils.sheet_add_json(worksheet, temp, {
      origin: "A2",
      skipHeader: true,
    });

    worksheet["!cols"] = [{ wch: 7 }, { wch: 24 }, { wch: 24 }, { wch: 48 }];

    const workbook = XLSX.utils.book_new();

    XLSX.utils.book_append_sheet(workbook, worksheet, "ethic");

    XLSX.writeFile(workbook, `Kritik Saran.xlsx`);
  };

  const exportToWord = async (data: ExportData) => {
    const tableRows = [
      new DocxTableRow({
        children: ["No", "Nama", "Email", "Kritik & Saran"].map(
          (text) =>
            new DocxTableCell({
              children: [
                new Paragraph({
                  children: [new TextRun({ text, bold: true })],
                }),
              ],
              width: { size: 25, type: WidthType.PERCENTAGE },
            })
        ),
      }),
    ];
    tableRows.push(
      new DocxTableRow({
        children: [
          String(data.no) || "",
          data.commentFromName || "",
          data.commentFromEmail || "",
          data.message || "",
        ].map(
          (text) =>
            new DocxTableCell({
              children: [new Paragraph(text)],
              width: { size: 25, type: WidthType.PERCENTAGE },
            })
        ),
      })
    );

    const doc = new Document({
      sections: [
        {
          children: [
            new Paragraph({
              text: "Kritik & Saran",
              heading: "Heading1",
            }),
            new DocxTable({
              rows: tableRows,
              width: {
                size: 100,
                type: WidthType.PERCENTAGE,
              },
            }),
          ],
        },
      ],
    });

    const blob = await Packer.toBlob(doc);

    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "KritikSaran.docx";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  return (
    <>
      <div className="flex flex-row gap-2 items-center">
        <Button
          color="primary"
          variant={typeDate === "monthly" ? "solid" : "bordered"}
          onPress={() => setTypeDate("monthly")}
          className="w-[140px] text-xs lg:text-sm h-[30px] lg:h-[40px] rounded-md lg:rounded-lg"
        >
          Bulanan
        </Button>
        <Button
          color="primary"
          onPress={() => setTypeDate("weekly")}
          variant={typeDate === "weekly" ? "solid" : "bordered"}
          className="w-[140px] text-xs lg:text-sm h-[30px] lg:h-[40px] rounded-md lg:rounded-lg"
        >
          Mingguan
        </Button>
        <Button
          color="primary"
          onPress={() => setTypeDate("daily")}
          variant={typeDate === "daily" ? "solid" : "bordered"}
          className="w-[140px] text-xs lg:text-sm h-[30px] lg:h-[40px] rounded-md lg:rounded-lg"
        >
          Harian
        </Button>
        <div className="w-[140px]">
          <Popover
            placement="bottom"
            classNames={{ content: ["!bg-transparent", "p-0"] }}
          >
            <PopoverTrigger>
              <Button className="w-[140px] text-xs lg:text-sm h-[30px] lg:h-[40px] rounded-md lg:rounded-lg">
                {getMonthYearName(startDateValue)}
              </Button>
            </PopoverTrigger>
            <PopoverContent className="bg-transparent">
              <Calendar value={startDateValue} onChange={setStartDateValue} />
            </PopoverContent>
          </Popover>
        </div>
        <p className="font-semibold">
          Total : <span className="font-bold">{totalData}</span>
        </p>
      </div>
      <div className="flex flex-row w-full h-full">
        <div className="w-full h-[30vh] lg:h-[300px] text-black">
          <SuggestionsChart
            type={typeDate}
            date={`${startDateValue.month} ${startDateValue.year}`}
            totals={(data) => setTotalData(data)}
          />
        </div>
      </div>
      <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 lg:items-end">
            <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-full lg:w-[120px]">
              <p className="font-semibold text-sm">Start Date</p>
              <Popover
                placement="bottom"
                classNames={{ content: ["!bg-transparent", "p-0"] }}
              >
                <PopoverTrigger>
                  <a className="cursor-pointer border-1 px-2 py-2 rounded-xl">
                    {convertDateFormatNoTime(feedbackDate.startDate)}
                  </a>
                </PopoverTrigger>
                <PopoverContent className="bg-transparent">
                  <Calendar
                    value={feedbackDate.startDate}
                    onChange={(e) =>
                      setFeedbackDate({
                        startDate: e,
                        endDate: feedbackDate.endDate,
                      })
                    }
                    maxValue={feedbackDate.endDate}
                  />
                </PopoverContent>
              </Popover>
            </div>

            <div className="flex flex-col gap-1 w-full lg:w-[120px]">
              <p className="font-semibold text-sm">End Date</p>
              <Popover
                placement="bottom"
                classNames={{ content: ["!bg-transparent", "p-0"] }}
              >
                <PopoverTrigger>
                  <a className="cursor-pointer border-1 px-2 py-2 rounded-xl">
                    {convertDateFormatNoTime(feedbackDate.endDate)}
                  </a>
                </PopoverTrigger>
                <PopoverContent className="bg-transparent">
                  <Calendar
                    value={feedbackDate.endDate}
                    onChange={(e) =>
                      setFeedbackDate({
                        startDate: feedbackDate.startDate,
                        endDate: e,
                      })
                    }
                    minValue={feedbackDate.startDate}
                  />
                </PopoverContent>
              </Popover>
            </div>

            {/* <div className=" w-[220px] h-[40px] flex flex-row gap-2 justify-between items-center">
              
            </div> */}
            <Button color="primary" className="text-white" onPress={doExport}>
              Export
            </Button>
          </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: 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>
      <Modal isOpen={isOpen} onOpenChange={onOpenChange} size="3xl">
        <ModalContent>
          {() => (
            <>
              <ModalHeader className="flex flex-col gap-1">
                Kritik Saran
              </ModalHeader>
              <ModalBody>
                <form
                  onSubmit={handleSubmit(onSubmit)}
                  className="flex flex-col gap-3"
                >
                  <div className="flex flex-col gap-1">
                    <p className="text-sm">Nama</p>
                    <Controller
                      control={control}
                      name="commentFromName"
                      render={({ field: { onChange, value } }) => (
                        <Input
                          type="text"
                          id="commentFromName"
                          placeholder=""
                          label=""
                          value={value}
                          onChange={onChange}
                          labelPlacement="outside"
                          className="w-full "
                          classNames={{
                            inputWrapper: [
                              "border-1 rounded-lg",
                              "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                            ],
                          }}
                          variant="bordered"
                        />
                      )}
                    />
                    {errors?.commentFromName && (
                      <p className="text-red-400 text-sm">
                        {errors.commentFromName?.message}
                      </p>
                    )}
                  </div>
                  <div className="flex flex-col gap-1">
                    <p className="text-sm">Email</p>
                    <Controller
                      control={control}
                      name="commentFromEmail"
                      render={({ field: { onChange, value } }) => (
                        <Input
                          type="text"
                          id="commentFromEmail"
                          placeholder=""
                          label=""
                          value={value}
                          onChange={onChange}
                          labelPlacement="outside"
                          className="w-full "
                          classNames={{
                            inputWrapper: [
                              "border-1 rounded-lg",
                              "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                            ],
                          }}
                          variant="bordered"
                        />
                      )}
                    />
                    {errors?.commentFromEmail && (
                      <p className="text-red-400 text-sm">
                        {errors.commentFromEmail?.message}
                      </p>
                    )}
                  </div>
                  <div className="flex flex-col gap-1">
                    <p className="text-sm">Deskripsi</p>
                    <Controller
                      control={control}
                      name="description"
                      render={({ field: { onChange, value } }) => (
                        <Textarea
                          type="text"
                          id="description"
                          placeholder=""
                          label=""
                          value={value}
                          onChange={onChange}
                          labelPlacement="outside"
                          className="w-full "
                          classNames={{
                            inputWrapper: [
                              "border-1 rounded-lg",
                              "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                            ],
                          }}
                          variant="bordered"
                        />
                      )}
                    />
                    {errors?.description && (
                      <p className="text-red-400 text-sm">
                        {errors.description?.message}
                      </p>
                    )}
                  </div>

                  <div className="flex flex-col gap-1">
                    <a
                      className="text-sm cursor-pointer hover:underline text-primary"
                      onClick={() => setIsReply(!isReply)}
                    >
                      Balas
                    </a>
                    {isReply && (
                      <Textarea
                        type="text"
                        id="description"
                        placeholder=""
                        label=""
                        value={replyValue}
                        onValueChange={setReplyValue}
                        labelPlacement="outside"
                        className="w-full "
                        classNames={{
                          inputWrapper: [
                            "border-1 rounded-lg",
                            "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                          ],
                        }}
                        variant="bordered"
                      />
                    )}
                  </div>

                  <ModalFooter className="self-end grow items-end">
                    {isReply && (
                      <Button
                        color="primary"
                        type="submit"
                        isDisabled={replyValue == ""}
                      >
                        Kirim
                      </Button>
                    )}

                    <Button color="danger" variant="light" onPress={onClose}>
                      Tutup
                    </Button>
                  </ModalFooter>
                </form>
              </ModalBody>
            </>
          )}
        </ModalContent>
      </Modal>
    </>
  );
}
