"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,
  getListArticle,
} from "@/service/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,
  Radio,
  RadioGroup,
  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 {
  createAdvertiseById,
  deleteAdvertise,
  editAdvertise,
  editAdvertiseIsActive,
  getAdvertise,
} from "@/service/advertisement";

const columns = [
  { name: "No", uid: "no" },
  { name: "Judul", uid: "title" },
  { name: "Deskripsi", uid: "description" },
  { name: "Penempatan", uid: "placement" },
  { name: "Link", uid: "redirectLink" },
  { name: "Aktif", uid: "isActive" },
  { name: "Aksi", uid: "actions" },
];

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

const createArticleSchema = z.object({
  id: z.string().optional(),
  title: z.string().min(2, {
    message: "Judul harus diisi",
  }),
  url: z.string().min(1, {
    message: "Url harus diisi",
  }),
  description: z.string().min(2, {
    message: "Deskripsi harus diisi",
  }),
  file: z.string().optional(),
});

export default function AdvertiseTable(props: { triggerRefresh: boolean }) {
  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 [placement, setPlacement] = useState("banner");
  const [refresh, setRefresh] = useState(false);

  const [files, setFiles] = useState<File[]>([]);

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

  const { getRootProps, getInputProps } = useDropzone({
    onDrop: (acceptedFiles) => {
      setFiles(acceptedFiles.map((file) => Object.assign(file)));
    },
    maxFiles: 1,
    accept: {
      "image/*": [],
    },
  });
  type UserSettingSchema = z.infer<typeof createArticleSchema>;
  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<UserSettingSchema>(formOptions);

  useEffect(() => {
    initState();
  }, [page, showData, props.triggerRefresh, refresh]);

  const handleRemoveFile = (file: File) => {
    const uploadedFiles = files;
    const filtered = uploadedFiles.filter((i) => i.name !== file.name);
    setFiles([...filtered]);
  };

  async function initState() {
    const req = {
      limit: showData,
      page: page,
      search: search,

      sort: "desc",
      sortBy: "created_at",
    };
    const res = await getAdvertise(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);
    }
  };

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

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

  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 onSubmit = async (values: z.infer<typeof createArticleSchema>) => {
    loading();
    const formData = {
      id: Number(values.id),
      title: values.title,
      description: values.description,
      placement: placement,
      redirectLink: values.url,
    };
    const res = await editAdvertise(formData);
    if (res?.error) {
      error(res?.message);
      return false;
    }
    close();
    MySwal.fire({
      title: "Sukses",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then((result) => {
      if (result.isConfirmed) {
        setRefresh(!refresh);
      }
    });
  };

  const openModal = async (id: number) => {
    const res = await createAdvertiseById(Number(id));
    const data = res?.data?.data;
    setValue("id", String(data?.id));
    setValue("title", data?.title);
    setValue("description", data?.description);
    setValue("url", data?.redirectLink);
    setPlacement(data?.placement);
    // setValue("file", data?.thumbnailUrl);

    onOpen();
  };

  const handleAdvertise = async (e: boolean, id: number) => {
    const res = await editAdvertiseIsActive({ id, isActive: e });
    if (res?.error) {
      error(res?.message);
      return false;
    }
    setRefresh(!refresh);
  };

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

      switch (columnKey) {
        case "redirectLink":
          return cellValue.includes("https") ? (
            <Link
              href={cellValue}
              target="_blank"
              className="text-primary hover:underline cursor-pointer"
            >
              {cellValue}
            </Link>
          ) : (
            <p> {cellValue}</p>
          );
        case "placement":
          return <p className="capitalize">{cellValue}</p>;
        case "isActive":
          return (
            <div className="flex flex-row gap-2">
              <Switch
                isSelected={advertise?.isActive}
                onValueChange={(e) => handleAdvertise(e, advertise?.id)}
              />
              {advertise?.isActive ? "Ya" : "Tidak"}
            </div>
          );
        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/advertise/detail/${article.id}`}>
                      <EyeIconMdi className="inline mr-2 mb-1" />
                      Detail
                    </Link>
                  </DropdownItem> */}
                  <DropdownItem
                    key="edit"
                    onPress={() => openModal(advertise.id)}
                  >
                    <CreateIconIon className="inline mr-2 mb-1" />
                    Edit
                  </DropdownItem>

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

        default:
          return cellValue;
      }
    },
    [article, props.triggerRefresh, refresh]
  );

  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={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",
              }}
              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">
                Advertise
              </ModalHeader>
              <ModalBody>
                <form
                  onSubmit={handleSubmit(onSubmit)}
                  className="flex flex-col gap-3"
                >
                  <div className="flex flex-col gap-1">
                    <p className="text-sm">Judul</p>
                    <Controller
                      control={control}
                      name="title"
                      render={({ field: { onChange, value } }) => (
                        <Input
                          type="text"
                          id="title"
                          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?.title && (
                      <p className="text-red-400 text-sm">
                        {errors.title?.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">
                    <p className="text-sm">Link</p>
                    <Controller
                      control={control}
                      name="url"
                      render={({ field: { onChange, value } }) => (
                        <Input
                          type="text"
                          id="url"
                          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?.url && (
                      <p className="text-red-400 text-sm">
                        {errors.url?.message}
                      </p>
                    )}
                  </div>

                  <p className="text-sm mt-3">Penempatan</p>
                  <RadioGroup
                    label=""
                    orientation="horizontal"
                    size="sm"
                    value={placement}
                    onValueChange={setPlacement}
                  >
                    <Radio value="banner">Banner</Radio>
                    <Radio value="jumbotron">Jumbotron</Radio>
                  </RadioGroup>
                  <Controller
                    control={control}
                    name="file"
                    render={({ field: { onChange, value } }) => (
                      <div className="flex flex-col gap-1">
                        <p className="text-sm mt-3">Thumbnail</p>

                        {files.length < 1 && value === "" && (
                          <Fragment>
                            <div {...getRootProps({ className: "dropzone" })}>
                              <input {...getInputProps()} />
                              <div className=" w-full text-center border-dashed border border-default-200 dark:border-default-300  rounded-md py-[52px] flex  items-center flex-col">
                                <CloudUploadIcon />
                                <h4 className=" text-2xl font-medium mb-1 mt-3 text-card-foreground/80">
                                  Tarik file disini atau klik untuk upload.
                                </h4>
                                <div className=" text-xs text-muted-foreground">
                                  ( Upload file dengan format .jpg, .jpeg, atau
                                  .png. Ukuran maksimal 100mb.)
                                </div>
                              </div>
                            </div>
                          </Fragment>
                        )}
                        {value !== "" && (
                          <div className="flex flex-row gap-2">
                            <Image
                              src={String(value)}
                              className="w-[30%]"
                              alt="thumbnail"
                              width={480}
                              height={480}
                            />
                            <Button
                              onPress={() => setValue("file", "")}
                              variant="bordered"
                              size="sm"
                              className="cursor-pointer text-black border-none"
                            >
                              <TimesIcon />
                            </Button>
                          </div>
                        )}
                        {files.length > 0 && (
                          <div className="flex flex-row gap-2">
                            <img
                              src={URL.createObjectURL(files[0])}
                              className="w-[30%]"
                              alt="thumbnail"
                            />
                            <Button
                              className=" border-none rounded-full"
                              variant="bordered"
                              onClick={() => handleRemoveFile(files[0])}
                            >
                              <TimesIcon />
                            </Button>
                          </div>
                        )}
                      </div>
                    )}
                  />
                  <ModalFooter className="self-end grow items-end">
                    <Button
                      color="primary"
                      type="submit"
                      // isDisabled={files.length < 1}
                    >
                      Simpan
                    </Button>
                    <Button color="danger" variant="light" onPress={onClose}>
                      Tutup
                    </Button>
                  </ModalFooter>
                </form>
              </ModalBody>
            </>
          )}
        </ModalContent>
      </Modal>
    </>
  );
}
