"use client";

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

const DetailAudio = () => {
  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 [detailDataAudio, setDetailDataAudio] = 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 [imageSizeSelected, setImageSizeSelected] = useState("l");

  const userId = getCookiesDecrypt("uie");

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

  const initFetch = async () => {
    const response = await getDetail(String(slug));
    console.log("detailAudio", 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,
    });
    setDetailDataAudio(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");
    }
  };

  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 {
            downloadFile(`${main?.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();
  };

  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" },
  ];

  return (
    <>
      <div className="min-h-screen 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 flex justify-center">
              <img src="/assets/audio-btn.png" />
              <BarWave color="#ffc831" width="60px" height="25px" duration="2s" />
              <div className="absolute top-4 left-4"></div>
            </div>
            {/* Footer Informasi */}
            <div className="p-4 text-sm text-gray-500 flex justify-between items-center border-t mt-4">
              <p className="flex flex-row items-center">
                oleh&nbsp;<span className="font-semibold text-black">{detailDataAudio?.uploadedBy?.userLevel?.name}</span>&nbsp;|&nbsp;Diupdate pada {detailDataAudio?.updatedAt} WIB&nbsp;|&nbsp;
                <Icon icon="formkit:eye" width="15" height="15" />
                &nbsp;
                {detailDataAudio?.clickCount}
              </p>
              <p>Kreator: {detailDataAudio?.creatorName}</p>
            </div>
            {/* Keterangan */}
            <div className="md:w-3/4">
              <h1 className="flex flex-row font-bold text-2xl mx-5 my-8">{detailDataAudio?.title}</h1>
              <div className="font-light text-justify" dangerouslySetInnerHTML={{ __html: detailDataAudio?.htmlDescription }} />
            </div>
          </div>

          {/* Bagian Kanan */}
          <div className="md:w-1/4 p-4 h-fit bg-gray-300 rounded-lg mx-4">
            {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=${detailDataAudio?.category.id}`} className="bg-red-600 text-white text-xs font-bold px-3 py-3 my-3 flex justify-center items-center rounded">
              {detailDataAudio?.category?.name}
            </Link>

            <div className="flex justify-center flex-wrap gap-2 mb-4">
              {detailDataAudio?.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">
                  {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 Audio</h4>

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

            <div className="space-y-2">
              {sizes.map((size: any) => (
                <div className="flex flex-row justify-between">
                  <div key={size.label} className="items-center flex flex-row  gap-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}</div>
                  </div>
                  <div className="">
                    <div className="text-sm">{size.value}</div>
                  </div>
                </div>
              ))}
            </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 gap-5 p-10 bg-gray-300">
          <p className="flex items-start text-lg">Berikan Komentar</p>
          <Textarea placeholder="Type your comments here." className="flex items-start justify-center" />
          <button className="flex items-start bg-[#bb3523] rounded-lg w-fit px-4 py-1">Kirim</button>
        </div>

        {/* Konten Serupa */}
        <div className="px-4">
          <NewContent group="satker" type={"similar"} />
        </div>
      </div>
    </>
  );
};

export default DetailAudio;
