"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";

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");

  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-12">
          <div>
            <h1 className="text-2xl font-semibold mb-4">Galeri Content Rewrite</h1>
          </div>
          <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}>
                    <CardContent className="flex flex-col  bg-black dark:bg-white w-full rounded-lg p-0">
                      <div className="">
                        <Link href={`/content-management/rewrite/detail/${image.id}`}>
                          {/* <img src={image?.thumbnailUrl} className="h-40 object-cover items-center justify-center cursor-pointer rounded-lg place-self-center" /> */}
                          <div className="img-container h-60 bg-[#e9e9e9] cursor-pointer rounded-lg">
                            <ImageBlurry src={image?.thumbnailUrl} alt={image?.title} style={{ objectFit: "contain", width: "100%", height: "100%" }} />
                          </div>
                        </Link>
                        <div className="font-semibold p-4 text-white text-xs lg:text-sm dark:text-black truncate w-full">{image?.title}</div>
                        <Popover>
                          <PopoverTrigger className="flex justify-end gap-1 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-40">
                            <div className="flex items-center gap-1 hover:text-red-800 w-full rounded-lg">
                              <Popover>
                                <PopoverTrigger asChild>
                                  <button className="w-full flex items-center gap-2">
                                    <Icon icon="oi:share" fontSize={20} />
                                    <p className="text-base font-semibold mb-3">Bagikan</p>
                                  </button>
                                </PopoverTrigger>
                                <PopoverContent>
                                  <div className="flex flex-col">
                                    <h1 className="mb-2">Share Ke Email</h1>
                                    <div className="flex flex-col mb-2">
                                      <p className="text-base font-semibold mb-1">Email Tujuan :</p>
                                      <Input value={emailShareInput} onChange={(event) => setEmailShareInput(event.target.value)} onKeyPress={handleEmailList} type="email" placeholder="Tekan Enter untuk input Email" />
                                    </div>
                                    <Button className="bg-blue-500 text-white p-2 w-fit rounded-lg" onClick={() => shareToEmail()}>
                                      Kirim
                                    </Button>
                                  </div>
                                </PopoverContent>
                              </Popover>
                            </div>
                            <a onClick={() => handleDelete(image?.id)} className="flex items-center gap-1  hover:text-red-800 w-full rounded-lg">
                              <Icon icon="fa:trash" fontSize={20} />
                              <p className="text-base  font-semibold">Hapus</p>
                            </a>
                          </PopoverContent>
                        </Popover>
                      </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;
