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

const page = (props: any) => {
  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 { isInstitute, instituteId } = props;
  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();

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

  return (
    <>
      <HeaderManagement />
      <div className="flex flex-row">
        <SidebarManagement />
        <div className="w-2/3 p-12">
          <div>
            <h1 className="text-2xl font-semibold mb-4">Galeri Content Rewrite</h1>
          </div>
          <div className="px-0 lg:px-10">
            {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-110 transition-transform duration-300">
                    <CardContent className="flex flex-col  bg-black dark:bg-white w-full rounded-lg p-0">
                      <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="font-semibold p-4 text-white text-xs lg:text-sm dark:text-black truncate w-full">{image?.title}</div>
                      </Link>
                    </CardContent>
                  </Card>
                ))}
              </div>
            ) : (
              <p className="flex items-center justify-center">
                <img src="/assets/empty-data.png" alt="empty" className="h-52 w-52 my-4" />
              </p>
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default page;
