"use client";
import { ChevronRightIcon } from "@/components/icons";
import { getMagazineById } from "@/service/magazine";
import {
  convertDateFormat,
  formatMonthString,
  formatTextToHtmlTag,
} from "@/utils/global";
import { BreadcrumbItem, Breadcrumbs } from "@nextui-org/breadcrumbs";
import { Button } from "@nextui-org/button";
import { Accordion, AccordionItem } from "@nextui-org/react";
import Link from "next/link";
import { useParams } from "next/navigation";
import React, { useEffect, useState } from "react";

export default function EMagazineDetail() {
  const params = useParams();
  const id = params?.id;
  const [detailData, setDetailData] = useState<any>();
  const [detailFiles, setDetailFiles] = useState<any>([]);

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

  const initFetch = async () => {
    const res = await getMagazineById(String(id));
    const data = res?.data?.data;
    setDetailData(data);
    setDetailFiles(data?.files);
  };

  const doDownload = async (fileName: string, title: string): Promise<void> => {
    try {
      const response = await fetch(
        `http://38.47.180.165:8802/magazine-files/viewer/${fileName}`
      );

      if (!response.ok) {
        throw new Error("File not found or server error");
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const anchor = document.createElement("a");

      anchor.href = url;
      anchor.download = title === "" ? fileName : title;
      document.body.appendChild(anchor);
      anchor.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(anchor);
    } catch (error) {
      console.error("Download failed:", error);
    }
  };
  return (
    <div className="w-auto bg-[#E2E2E2] text-black">
      <div className="p-1 md:p-5 lg:px-36">
        <div className="flex flex-row gap-4 items-end text-black">
          <Link href="/" className=" font-semibold text-lg">
            Beranda
          </Link>
          <ChevronRightIcon />
          <Link
            href="/e-majalah-polri/daftar-majalah"
            className=" font-semibold text-lg"
          >
            E-Majalah Polri
          </Link>
        </div>
        <div className="pt-5 space-y-4">
          <div className="font-semibold border-b-4 border-red-700 leading-loose">
            {detailData?.title}
          </div>
          <div className="rounded-lg h-[380px] flex items-center justify-center">
            <img
              src="/emagazine.jpeg"
              alt="emagazine"
              className="h-[380px] rounded-md py-1"
            />
          </div>
          <div
            dangerouslySetInnerHTML={formatTextToHtmlTag(
              detailData?.description
            )}
            className="text-sm lg:text-xl lg:leading-8 justify-center flex"
          />
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {detailFiles?.map((file: any, index: number) => (
              <Accordion key={file?.id} variant="splitted">
                <AccordionItem
                  key={file?.id}
                  aria-label={file?.title}
                  className="p-2"
                  title={
                    <p className="text-black dark:text-white font-semibold text-xs md:text-sm">
                      {file?.title === "" ? `File ${index + 1}` : file?.title}
                    </p>
                  }
                >
                  <div className="bg-[#FFFFFF] rounded-md font-medium text-xs md:text-sm">
                    <div className="flex justify-between items-center border text-black dark:text-white border-gray-300 p-3 rounded-t-md bg-gray-100 dark:bg-stone-900">
                      <div className="w-[35%] md:w-[20%]">Nama File</div>
                      <div className="w-[65%] md:w-[80%] text-center border-l border-gray-300">
                        {file?.fileName}
                      </div>
                    </div>
                    <div className="flex justify-between border items-center border-gray-300 p-3">
                      <div className="w-[35%] md:w-[20%]">Deskripsi</div>
                      <div className="w-[65%] md:w-[80%] text-center border-l border-gray-300">
                        {file?.description == "" ? "-" : file?.description}
                      </div>
                    </div>
                    <div className="flex justify-between border items-center border-gray-300 p-3">
                      <div className="w-[35%] md:w-[20%]">Ukuran File</div>
                      <div className="w-[65%] md:w-[80%] text-center border-l border-gray-300">
                        {Math.round(file?.size / 100) / 10 > 1000 ? (
                          <>
                            {(Math.round(file?.size / 100) / 10000).toFixed(1)}
                          </>
                        ) : (
                          <>{(Math.round(file?.size / 100) / 10).toFixed(1)}</>
                        )}
                        {" kb"}
                      </div>
                    </div>

                    <div className="flex justify-between items-center border rounded-b-md border-gray-300 p-3">
                      <div className="w-[35%] md:w-[20%]">Tanggal Publish</div>
                      <div className="w-[65%] md:w-[80%] text-center border-l border-gray-300">
                        {formatMonthString(file?.createdAt)}
                      </div>
                    </div>
                  </div>
                  <Button
                    className="w-full bg-[#DD8306] text-sm font-semibold text-white mt-2"
                    radius="sm"
                    onPress={() => doDownload(file?.fileName, file?.title)}
                  >
                    Download
                  </Button>
                </AccordionItem>
              </Accordion>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
