"use client";

import { useParams, usePathname } from "next/navigation";
import React, { useEffect, useState } from "react";
import { Icon } from "@iconify/react/dist/iconify.js";
import {
  checkWishlistStatus,
  deleteWishlist,
  getDetail,
  saveWishlist,
} from "@/service/landing/landing";
import VideoPlayer from "@/utils/video-player";
import NewContent from "@/components/landing-page/new-content";
import { Link, useRouter } from "@/i18n/routing";
import { Textarea } from "@/components/ui/textarea";
import { getCookiesDecrypt } from "@/lib/utils";
import { close, error, loading } from "@/config/swal";
import { useToast } from "@/components/ui/use-toast";

const DetailVideo = () => {
  const [selectedSize, setSelectedSize] = useState<string>("L");
  const [selectedTab, setSelectedTab] = useState("video");
  const router = useRouter();
  const pathname = usePathname();
  const params = useParams();
  const slug = String(params?.slug);
  const [detailDataVideo, setDetailDataVideo] = useState<any>();
  const [isSaved, setIsSaved] = useState(false);
  const [wishlistId, setWishlistId] = useState();
  const { toast } = useToast();
  const [isDownloadAll, setIsDownloadAll] = useState(false);
  const [downloadProgress, setDownloadProgress] = useState(0);
  const [isFromSPIT, setIsFromSPIT] = useState(false);
  const [main, setMain] = useState<any>();
  const [resolutionSelected, setResolutionSelected] = useState("720");

  const userId = getCookiesDecrypt("uie");

  useEffect(() => {
    initFetch();
    checkWishlist();
  }, []);

  const initFetch = async () => {
    const response = await getDetail(String(slug));
    console.log("detailVideo", response);
    setIsFromSPIT(response?.data?.data?.isFromSPIT);
    setMain({
      id: response?.data?.data?.files[0]?.id,
      type: response?.data?.data?.fileType.name,
      url:
        Number(response?.data?.data?.fileType?.id) == 4
          ? response?.data?.data?.files[0]?.secondaryUrl
          : Number(response?.data?.data?.fileType?.id) == 2
          ? `${process.env.NEXT_PUBLIC_API}/media/view?id=${response?.data?.data?.files[0]?.id}&operation=file&type=video`
          : response?.data?.data?.files[0]?.url,
      thumbnailFileUrl: response?.data?.data?.files[0]?.thumbnailFileUrl,
      names: response?.data?.data?.files[0]?.fileName,
      format: response?.data?.data?.files[0]?.format,
      widthPixel: response?.data?.data?.files[0]?.widthPixel,
      heightPixel: response?.data?.data?.files[0]?.heightPixel,
      size: response?.data?.data?.files[0]?.size,
      caption: response?.data?.data?.files[0]?.caption,
    });
    setDetailDataVideo(response?.data?.data);
  };

  const doBookmark = async () => {
    if (userId) {
      const data = {
        mediaUploadId: slug?.split("-")?.[0],
      };

      loading();
      const res = await saveWishlist(data);
      if (res?.error) {
        error(res.message);
        return false;
      }
      close();
      toast({
        title: "Konten berhasil disimpan",
      });
      checkWishlist();
    } else {
      router.push("/auth");
    }
  };
  async function checkWishlist() {
    if (userId) {
      const res = await checkWishlistStatus(slug.split("-")?.[0]);
      console.log(res?.data?.data);
      const isAlreadyOnWishlist = res?.data?.data !== "-1";
      setWishlistId(res?.data?.data);
      setIsSaved(isAlreadyOnWishlist);
    }
  }

  const handleDeleteWishlist = async () => {
    if (userId) {
      loading();
      const res = await deleteWishlist(wishlistId);

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

      toast({
        title: "Konten berhasil dihapus",
      });
      close();
      checkWishlist();
    } else {
      router.push("/auth");
    }
  };

  const sizes = [
    { label: "XL", value: "3198 x 1798 px" },
    { label: "L", value: "2399 x 1349 px" },
    { label: "M", value: "1599 x 899 px" },
    { label: "S", value: "1066 x 599 px" },
    { label: "XS", value: "800 x 450 px" },
  ];

  async function sendActivityLog(activityTypeId: number) {
    const data = {
      activityTypeId,
      mediaId: slug.split("-")?.[0],
      url: window.location.href,
    };
    // set activity
    // const response = await postActivityLog(data, token);
    // console.log(response);
  }

  const handleDownload = () => {
    if (downloadProgress === 0) {
      if (!userId) {
        router.push("/auth/login");
      } else {
        sendActivityLog(2);
        sendActivityLog(3);

        if (isDownloadAll) {
          let url: string;
          const baseId = slug.split("-")?.[0];

          // if (type === "1") {
          url = `${process.env.NEXT_PUBLIC_API}/media/file/download-zip?id=${baseId}&resolution=${resolutionSelected}`;
          // } else if (type === "2") {
          // url = `${process.env.NEXT_PUBLIC_API}/media/file/download-zip?id=${baseId}&resolution=${imageSizeSelected}`;
          // } else {
          //   url = `${process.env.NEXT_PUBLIC_API}/media/file/download-zip?id=${baseId}`;
          // }

          downloadFile(url, "FileDownload.zip");
        } else {
          if (isFromSPIT && main?.url?.includes("spit.humas")) {
            downloadFile(`${main?.url}`, `${main.names}`);
          } else {
            const url = `${process.env.NEXT_PUBLIC_API}/media/view?id=${main?.id}&operation=file&type=video&resolution=${resolutionSelected}p`;
            downloadFile(url, `${main.names}`);
          }
        }
        // } else if (type === "1" && resolutionSelected?.length > 0) {
        //   if (isFromSPIT && main?.url?.includes("spit.humas")) {
        //     downloadFile(`${main?.url}`, `${main.names}`);
        //   } else {
        //     const url = `${process.env.NEXT_PUBLIC_API}/media/view?id=${main?.id}&operation=file&type=video&resolution=${resolutionSelected}p`;
        //     downloadFile(url, `${main.names}`);
        //   }
        // } else if (type === "2" && imageSizeSelected?.length > 0) {
        //   const url = `${process.env.NEXT_PUBLIC_API}/media/view?id=${main?.id}&operation=file&type=image&resolution=${imageSizeSelected}`;
        //   downloadFile(url, `${main.names}`);
        // } else if (type === "3" || type === "4") {
        //   downloadFile(`${main?.url}`, `${main.names}`);
        // }
      }
    }
  };

  const downloadFile = (fileUrl: string, name: string) => {
    const xhr = new XMLHttpRequest();

    xhr.open("GET", fileUrl, true);
    xhr.responseType = "blob";

    xhr.addEventListener("progress", (event) => {
      if (event.lengthComputable) {
        const percentCompleted = Math.round((event.loaded / event.total) * 100);
        setDownloadProgress(percentCompleted);
      }
    });

    xhr.addEventListener("readystatechange", () => {
      if (xhr.readyState === 4 && xhr.status === 200) {
        const contentType =
          xhr.getResponseHeader("content-type") || "application/octet-stream";
        const extension = contentType.split("/")[1];
        const filename = `${name}.${extension}`;

        const blob = new Blob([xhr.response], {
          type: contentType,
        });
        const downloadUrl = URL.createObjectURL(blob);
        const a = document.createElement("a");

        a.href = downloadUrl;
        a.download = filename;
        document.body.append(a);
        a.click();
        a.remove();
      }
    });

    xhr.onloadend = () => {
      setDownloadProgress(0);
    };

    xhr.send();
  };

  return (
    <>
      <div className="px-4 md:px-24 py-4">
        {/* Container Utama */}
        <div className="rounded-md overflow-hidden md:flex">
          {/* Bagian Kiri */}
          <div className="md:w-3/4">
            <div className="relative">
              <VideoPlayer url={detailDataVideo?.files[0]?.url} />
              <div className="absolute top-4 left-4"></div>
            </div>

            {/* Footer Informasi */}
            <div className="text-sm text-gray-500 flex justify-between items-center border-t mt-4">
              <p className="flex flex-row items-center mt-3">
                oleh&nbsp;
                <span className="font-semibold text-black">
                  {detailDataVideo?.uploadedBy?.userLevel?.name}
                </span>
                &nbsp;|&nbsp;Diupdate pada {detailDataVideo?.updatedAt}{" "}
                WIB&nbsp;|&nbsp;
                <Icon icon="formkit:eye" width="15" height="15" />
                &nbsp;
                {detailDataVideo?.clickCount}
              </p>
              <p className="mt-3">Kreator: {detailDataVideo?.creatorName}</p>
            </div>

            {/* Keterangan */}
            <div className="w-full">
              <h1 className="flex flex-row font-bold text-2xl my-8">
                {detailDataVideo?.title}
              </h1>
              <div
                className="font-light text-justify"
                dangerouslySetInnerHTML={{
                  __html: detailDataVideo?.htmlDescription,
                }}
              />
            </div>
          </div>

          {/* Bagian Kanan */}
          <div className="md:w-1/4 p-4 bg-[#f7f7f7] rounded-lg mx-4 h-fit">
            {isSaved ? (
              <a
                onClick={() => handleDeleteWishlist()}
                className="flex flex-col mb-3 items-center justify-center cursor-pointer"
              >
                <Icon icon="material-symbols:bookmark" width={40} />
                <p className="text-base lg:text-lg">Hapus</p>
              </a>
            ) : (
              <a
                onClick={() => doBookmark()}
                className="flex flex-col mb-3 items-center justify-center cursor-pointer"
              >
                <Icon icon="material-symbols:bookmark-outline" width={40} />
                <p className="text-base lg:text-lg">Simpan</p>
              </a>
            )}

            {/* garis */}
            <div className="border-t border-black my-4"></div>

            <Link
              href={`/all/filter?title=polda&category=${detailDataVideo?.category.id}`}
              className="bg-red-600 text-white text-xs font-bold px-3 py-3 my-3 flex justify-center items-center rounded"
            >
              {detailDataVideo?.categoryName}
            </Link>

            <div className="flex justify-center flex-wrap gap-2 mb-4">
              {detailDataVideo?.tags.split(",").map((tag: string) => (
                <a
                  onClick={() => router.push(`/all/filter?tag=${tag}`)}
                  key={tag}
                  className="bg-gray-200 text-gray-700 text-xs px-3 py-1 rounded-full cursor-pointer hover:bg-gray-500 hover:text-white"
                >
                  {tag}
                </a>
              ))}
            </div>

            <div className="border-t border-black my-4"></div>

            {/* Opsi Ukuran Foto */}
            <h4 className="flex text-lg justify-center items-center font-semibold my-3">
              Opsi Ukuran Foto
            </h4>

            <div className="border-t border-black my-4"></div>

            <div className="space-y-2">
              {sizes.map((size) => (
                <label
                  key={size.label}
                  className="flex items-center space-x-2 cursor-pointer"
                >
                  <input
                    type="radio"
                    name="size"
                    value={size.label}
                    checked={selectedSize === size.label}
                    onChange={() => setSelectedSize(size.label)}
                    className="text-red-600 focus:ring-red-600"
                  />
                  <div className="text-sm">
                    {size.label} ----------------- {size.value}
                  </div>
                </label>
              ))}
            </div>

            {/* Download Semua */}
            <div className="mt-4">
              <label className="flex items-center space-x-2 text-sm">
                <input
                  type="checkbox"
                  className="text-red-600 focus:ring-red-600"
                  onChange={() => setIsDownloadAll(!isDownloadAll)}
                />
                <span>Download Semua File?</span>
              </label>
            </div>

            {/* Tombol Download */}
            <button
              onClick={handleDownload}
              className="mt-4 bg-red-600 text-white w-full py-2 flex justify-center items-center gap-1 rounded-md text-sm hover:bg-red-700"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="1em"
                height="1em"
                viewBox="0 0 24 24"
              >
                <path
                  fill="white"
                  d="m12 16l-5-5l1.4-1.45l2.6 2.6V4h2v8.15l2.6-2.6L17 11zm-6 4q-.825 0-1.412-.587T4 18v-3h2v3h12v-3h2v3q0 .825-.587 1.413T18 20z"
                />
              </svg>
              Download
            </button>
          </div>
        </div>
      </div>
      <div className="w-full mb-8">
        {/* Comment */}
        <div className="flex flex-col my-16 p-10 bg-[#f7f7f7]">
          <div className="gap-5 flex flex-col px-4 lg:px-14">
            <p className="flex items-start text-lg">Berikan Komentar</p>
            <Textarea
              placeholder="Type your comments here."
              className="flex w-full"
            />
            <button className="flex items-start bg-[#bb3523] text-white rounded-lg w-fit px-4 py-1">
              Kirim
            </button>
          </div>
        </div>

        {/* Konten Serupa */}
        <div className="">
          <NewContent type={"similar"} />
        </div>
      </div>
    </>
  );
};

export default DetailVideo;
