"use client";

import HeaderManagement from "@/components/landing-page/header-management";
import SidebarManagement from "@/components/landing-page/sidebar-management";
import { close, error, loading, successCallback } from "@/config/swal";
import { getCookiesDecrypt } from "@/lib/utils";
import {
  checkWishlistStatus,
  deleteWishlist,
  getContentRewritePagination,
  getInfoProfile,
  saveWishlist,
} from "@/service/landing/landing";
import { useRouter, useSearchParams } from "next/navigation";
import React, { useEffect, useState } from "react";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { Card, CardContent } from "@/components/ui/card";
import { Link } from "@/i18n/routing";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Icon } from "@iconify/react/dist/iconify.js";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { sendMediaUploadToEmail } from "@/service/media-tracking/media-tracking";
import ImageBlurry from "@/components/ui/image-blurry";
import Image from "next/image";
import { useTranslations } from "next-intl";

const page = () => {
  const [, setProfile] = useState();
  const router = useRouter();
  const searchParams = useSearchParams();
  const MySwal = withReactContent(Swal);
  const page: any = searchParams?.get("page");
  const title = searchParams?.get("title");
  const category = searchParams?.get("category");
  const pages = page ? page - 1 : 0;
  const userId = getCookiesDecrypt("uie");
  const userRoleId = getCookiesDecrypt("urie");
  const [, setGetTotalPage] = useState();
  const [totalContent, setTotalContent] = useState<any>();
  const [contentImage, setContentImage] = useState([]);
  const [categoryFilter] = useState([]);
  const [formatFilter] = useState([]);
  const [sortBy] = useState();
  const [refresh, setRefresh] = useState(false);
  const [, setCopySuccess] = useState("");
  const [, setWishlistId] = useState();
  const [emailShareList, setEmailShareList] = useState<any>();
  const [emailShareInput, setEmailShareInput] = useState<any>();
  const [emailMessageInput, setEmailMessageInput] = useState();
  const id = searchParams?.get("id");
  const t = useTranslations("LandingPage");

  useEffect(() => {
    async function initState() {
      loading();
      const response = await getInfoProfile();
      // console.log(response?.data?.data);
      setProfile(response?.data?.data);
      close();
    }

    initState();
  }, []);

  useEffect(() => {
    getData();
  }, [page, category, title, refresh]);

  async function getData() {
    const filter =
      categoryFilter?.length > 0
        ? categoryFilter?.sort().join(",")
        : category || "";

    const name = title == undefined ? "" : title;
    const format = formatFilter == undefined ? "" : formatFilter?.join(",");

    const response = await getContentRewritePagination(pages);

    setGetTotalPage(response?.data?.data?.totalPages);
    setContentImage(response?.data?.data?.content);
    // console.log("response", response);
    setTotalContent(response?.data?.data?.totalElements);
    // console.log("KONTEN", response?.data?.data?.content);
  }

  useEffect(() => {
    async function initState() {
      getData();
    }

    initState();
  }, [page, refresh]);

  function addDefaultSrc(ev: any) {
    ev.target.src = "/assets/img/image404.png";
  }

  async function deleteProcess(id: any) {
    loading();
    const resDelete = await deleteWishlist(id);

    if (resDelete?.error) {
      error(resDelete.message);
      return false;
    }

    setRefresh((prevRefresh) => !prevRefresh);
    close();
  }

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

  const copyToClip = async (url: any) => {
    await navigator.clipboard.writeText(
      `https://mediahub.polri.go.id/image/detail/${url}`
    );
    setCopySuccess("Copied");
    // toast.success("Link Berhasil Di Copy");
  };

  async function checkWishlist(uploadId: any) {
    if (userId) {
      const res = await checkWishlistStatus(uploadId);
      // console.log(res?.data?.data);
      // const isAlreadyOnWishlist = res?.data?.data == "-1" ? false : true;
      // if (isAlreadyOnWishlist == true) {
      //   warning("Konten sudah Ada", `#`);
      // }
      setWishlistId(res?.data?.data); // setIsSaved(isAlreadyOnWishlist);
      // console.log("isSave", isAlreadyOnWishlist);
    }
  }

  const handleSaveWishlist = async (uploadId: any) => {
    if (Number(userRoleId) < 1 || userRoleId == undefined) {
      router.push("/auth/login");
    } else {
      // console.log("data", uploadId);
      const data = {
        mediaUploadId: uploadId,
      };

      loading();
      checkWishlist(uploadId);

      const res = await saveWishlist(data);
      if (res?.error) {
        error(res.message);
        // console.log("simpan data", res);
        return false;
      }

      successCallback("Konten Berhasil Disimpan");
    }
  };

  async function shareToEmail() {
    if (Number(userRoleId) < 1 || userRoleId == undefined) {
      router.push("/auth/login");
    } else {
      const data = {
        mediaUploadId: id?.split("-")?.[0],
        email: emailShareList || [emailShareInput],
        message: emailMessageInput,
        url: window.location.href,
      };
      loading();
      const res = await sendMediaUploadToEmail(data);
      if (res?.error) {
        error(res.message);
        return false;
      }
      close();
      successCallback("Konten Telah Dikirim");
    }
  }

  const handleEmailList = (e: any) => {
    const arrayEmail: any = [];
    for (let i = 0; i < emailShareList?.length; i += 1) {
      arrayEmail.push(emailShareList[i]);
    }
    if (e.which == 13) {
      if (e.target.value) {
        arrayEmail.push(e.target.value);
        setEmailShareList(arrayEmail);
        setEmailShareInput("");
      }
      e.preventDefault();
    }
    return false;
  };

  return (
    <>
      <HeaderManagement />
      <div className="flex flex-col lg:flex-row">
        <SidebarManagement />
        <div className="w-full lg:w-2/3 p-8 lg:p-14">
          <h1 className="text-2xl w-fit font-bold bg-[#bb3523] px-4 py-1 rounded-lg text-center text-white mb-4">
            <span className="text-black">{t("gallery", { defaultValue: "Gallery" })} </span>
            {t("content", { defaultValue: "Content" })} Rewrite
          </h1>
          <div className="">
            {contentImage?.length > 0 ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                {contentImage?.map((image: any) => (
                  <Card
                    key={image?.id}
                    className="hover:scale-105 transition-transform duration-300"
                  >
                    <CardContent className="flex flex-col text-xs lg:text-sm w-full p-0">
                      <div>
                        <div className="relative group overflow-hidden shadow-md hover:shadow-lg">
                          <div className="relative h-60 rounded-lg overflow-hidden">
                            <ImageBlurry
                              src={image?.thumbnailUrl}
                              alt={image?.title}
                              style={{
                                objectFit: "contain",
                                width: "100%",
                                height: "100%",
                              }}
                            />
                            <div className="absolute bottom-0 left-0 right-0 bg-black text-white">
                              <Link
                                href={`/content-management/rewrite/detail/${image.id}`}
                              >
                                <p className="text-sm p-2 lg:text-base font-semibold truncate">
                                  {image?.title}
                                </p>
                              </Link>
                              <p className="flex text-[10px] mr-1 mb-2 items-center justify-end self-end">
                                <Popover>
                                  <PopoverTrigger
                                    className="flex cursor-pointer"
                                    asChild
                                  >
                                    <a className="flex justify-end items-end place-items-end">
                                      <Icon
                                        className="text-white ml-1"
                                        fontSize={25}
                                        icon="tabler:dots"
                                      />
                                    </a>
                                  </PopoverTrigger>
                                  <PopoverContent className="w-52">
                                    {/* <div
                                      onClick={() =>
                                        handleSaveWishlist(
                                          image?.mediaUpload?.id
                                        )
                                      }
                                      className="cursor-pointer flex flex-row gap-2 hover:text-red-800"
                                    >
                                      <Icon
                                        icon="material-symbols:bookmark-outline"
                                        fontSize={25}
                                      />
                                      <p className="text-base font-semibold mb-2">
                                        {t("save", { defaultValue: "Save" })}
                                      </p>
                                    </div> */}
                                    {/* <Link
                                      href={`/content-management/rewrite/create/${image?.mediaUploadId}`}
                                      className="flex flex-row hover:text-red-800 gap-2"
                                    >
                                      <Icon icon="jam:write" fontSize={25} />
                                      <p className="text-base font-semibold mb-2">
                                        Content Rewrite
                                      </p>
                                    </Link> */}
                                    <div className="flex items-center gap-1 hover:text-red-800 w-full rounded-lg">
                                      <Popover>
                                        <PopoverTrigger asChild>
                                          <button className="w-full flex flex-row items-center gap-3">
                                            <Icon
                                              icon="oi:share"
                                              fontSize={20}
                                            />
                                            <p className="text-base font-semibold mb-1">
                                              {" "}
                                              {t("share", { defaultValue: "Share" })}
                                            </p>
                                          </button>
                                        </PopoverTrigger>
                                        <PopoverContent>
                                          <div className="flex flex-col">
                                            <h1 className="mb-2">
                                              {t("shareTo", { defaultValue: "Share To" })}
                                            </h1>
                                            <div className="flex flex-col mb-2">
                                              <p className="text-base font-semibold mb-1">
                                                {t("destinationEmail", { defaultValue: "Destination Email" })}
                                              </p>
                                              <Input
                                                value={emailShareInput}
                                                onChange={(event) =>
                                                  setEmailShareInput(
                                                    event.target.value
                                                  )
                                                }
                                                onKeyPress={handleEmailList}
                                                type="email"
                                                placeholder={t("pressEnter", { defaultValue: "Press Enter" })}
                                              />
                                            </div>
                                            <Button
                                              className="bg-blue-500 text-white p-2 w-fit rounded-lg"
                                              onClick={() => shareToEmail()}
                                            >
                                              {t("send", { defaultValue: "Send" })}
                                            </Button>
                                          </div>
                                        </PopoverContent>
                                      </Popover>
                                    </div>
                                    <div
                                      onClick={() =>
                                        handleDelete(
                                          image?.id
                                        )
                                      }
                                      className="cursor-pointer flex flex-row gap-2 hover:text-red-800"
                                    >
                                      <Icon
                                        icon="iconamoon:trash"
                                        fontSize={25}
                                      />
                                      <p className="text-base font-semibold mb-2">
                                        {t("delete", { defaultValue: "Delete" })}
                                      </p>
                                    </div>
                                  </PopoverContent>
                                </Popover>
                              </p>
                            </div>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            ) : (
              <p className="flex items-center justify-center">
                <Image
                  width={1920}
                  height={1080}
                  src="/assets/empty-data.png"
                  alt="empty"
                  className="h-52 w-52 my-4"
                />
              </p>
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default page;
