"use client"

import React, { useCallback, useEffect, useMemo, useState } from "react"
import { useTranslations } from "next-intl"
import HeaderBreadcrumb from "@/component/Layout/HeaderBreadcrumb"
import { Link, usePathname, useRouter as useRouterI18n } from "@/i18n/routing"
import { Form, Modal } from "antd"
import classNames from "classnames"
import SearchBox from "@/component/Layout/SearchBox"
import CardItemDocument from "@component/Documents/List/ItemDocument"
import type { MenuProps } from "antd"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faPlus } from "@fortawesome/free-solid-svg-icons"
import AddnewFiles from "./AddNewFiles"
import { CustomDropDownMenuCss, DropDownMenu } from "@/component/Common/DropDownMenu"
import { FOLDER_COLOR } from "@/config/constant"
import { find, lowerCase, omitBy } from "lodash"
import { formatFileSize } from "@/util/Common"
import { useDeleteFile, useDeleteFolder, useDownloadFile, useGetFolderDetail } from "@/hook/useDocument"
import NotifyCustom from "@/component/Common/NotifyCustom"
import { useParams, useSearchParams } from "next/navigation"
import { renderLabelItem } from "@/component/Common/LabelItem"
import { IDetailFloderQuery } from "@/type/Document"
import { LoadingResult } from "@/component/Common/LoadingResult/LoadingResult"
import { useDownload } from "@/hook/useCommon"

export default function DocumentFileComponent() {
  const router = useRouterI18n()
  const [formRef] = Form.useForm()
  const { handleDownload } = useDownload()

  const trans = useTranslations("document")
  const transBook = useTranslations("book")
  const transButton = useTranslations("button")
  const transGeneral = useTranslations("general")
  const transRq = useTranslations("required")
  const [searchValue, setSearchValue] = useState("")
  const [activeButtons, setActiveButtons] = useState<any>("")
  const transMusic = useTranslations("music")
  const types = ["csv", , "pdf", "docx", "iso", "java", "xml", "jpg", "jpeg", "png", "xls"]
  const deleteFolder = useDeleteFolder()
  const deleteFile = useDeleteFile()
  const [open, setOpen] = useState<boolean>(false)
  const [loading, setLoading] = useState<boolean>(true)
  const [paramDownload, setParamDownload] = useState<any>({
    id: 0,
    name: "",
    enabled: false,
  })
  const { data: dataDownload, refetch: refetchDownload } = useDownloadFile(paramDownload)
  const transMessage = useTranslations("message")
  const [openNotify, setOpenNotify] = useState(false)
  const [messageNotify, setMessageNotify] = useState<{
    type: "success" | "error"
    message: string
    description: string
  }>({
    type: "error",
    message: "",
    description: "",
  })
  const [modal, modalContextHolder] = Modal.useModal()
  const [openViewFile, setOpenViewFile] = useState(false)
  const [fileSelected, setFileSelected] = useState<any>(null)
  const [query, setQuery] = useState<IDetailFloderQuery>({})
  const [countDownLoad, setCountDownLoad] = useState<number>(0)

  const { id } = useParams()
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const oldSearch = Object.fromEntries(searchParams.entries())

  const { data, isLoading, refetch } = useGetFolderDetail(String(id), query)

  const folder = useMemo(() => data?.data?.data, [data?.data?.data])

  useEffect(() => {
    handleSearchKeyword(searchParams.get("search") || "")
    setSearchValue(searchParams.get("search") || "")
  }, [searchParams])

  const showLoading = () => {
    setOpen(true)
    setLoading(true)

    // Simple loading mock. You should add cleanup logic in real world.
    setTimeout(() => {
      setLoading(false)
    }, 1000)
  }

  const updateSearchQuery = useCallback(
    (updatedQuery: any) => {
      const params = new URLSearchParams(searchParams)

      if (Object.keys(updatedQuery).length === 0) {
        router.push(pathname, { scroll: false })
      } else {
        Object.entries(updatedQuery).forEach(([key, value]) => {
          value ? params.set(key, String(value)) : params.delete(key)
        })

        Array.from(params.keys()).forEach((key) => {
          if (!(key in updatedQuery)) {
            params.delete(key)
          }
        })
        router.push(`?${params.toString()}`, { scroll: false })
      }
    },
    [searchParams, pathname, query],
  )

  const handleSearchKeyword = (keyword: string) => {
    if (keyword && keyword?.length >= 3) {
      const updatedQuery = { ...oldSearch, search: keyword?.trim() }
      const cleanedObj = omitBy(updatedQuery, (value) => value === null || value === undefined || value === "")

      setQuery(cleanedObj)
      updateSearchQuery(cleanedObj)
    }
    if (keyword === "" && query?.search) {
      const updatedQuery = { ...oldSearch, search: "" }
      const cleanedObj = omitBy(updatedQuery, (value) => value === null || value === undefined || value === "")
      setQuery(cleanedObj)
      updateSearchQuery(cleanedObj)
    }
  }

  const handleOpenChange = (open: boolean, index: any) => {
    setActiveButtons((prevId: any) => (prevId === index || !open ? null : index))
  }

  const renderFolderButtonTopRight = (item: any, className?: string) => {
    const items: MenuProps["items"] = [
      {
        label: renderLabelItem(transBook("go_detail"), "/img/icon/information_circle_outline.svg", "information_circle_outline"),
        key: "0",
        onClick: () => {
          router.push(`/documents/${item?.id}`)
        },
      },
      {
        label: renderLabelItem(transBook("edit"), "/img/icon/edit.svg", "edit"),
        key: "1",
        onClick: () => router.push(`/documents/edit-folder/${item.id}`),
      },
      {
        label: renderLabelItem(transBook("delete"), "/img/icon/trash_outline.svg", "Delete"),
        key: "2",
        onClick: () => confirmDeleteFolder(item?.id),
      },
    ]

    return (
      <DropDownMenu
        className={className || ""}
        menu={{ items, className: classNames(CustomDropDownMenuCss) }}
        onOpenChange={(open) => handleOpenChange(open, item.id)}
      />
    )
  }

  const confirmDeleteFolder = (id: number) => {
    modal.confirm({
      title: transGeneral("confirm_delete"),
      okText: transButton("ok"),
      cancelText: transButton("cancel"),
      onOk() {
        handleDeleteFolder(id)
      },
    })
  }

  const handleDeleteFolder = (id: number) => {
    deleteFolder
      .mutateAsync(id)
      .then(() => {
        refetch()
        setOpenNotify(true)
        setMessageNotify({
          type: "success",
          message: transMessage("success"),
          description: trans("delete_folder_success"),
        })
      })
      .catch((error: any) => {
        setOpenNotify(true)
        setMessageNotify({
          type: "error",
          message: transMessage("something_wrong"),
          description: error?.response?.data.msgs || transMessage("fail"),
        })
      })
  }

  const handleViewFile = (item: any) => {
    setFileSelected(item)
    setOpenViewFile((pre) => !pre)
    if (paramDownload?.id === item?.id) {
      handleOpenFile(dataDownload?.data?.url)
    } else handleDownloadFile(item)
  }

  const renderFileButtonTopRight = (item: any, className?: string) => {
    const items: MenuProps["items"] = [
      {
        label: renderLabelItem(transBook("go_detail"), "/img/icon/information_circle_outline.svg", "view"),
        key: "0",
        onClick: () => handleViewFile(item),
      },
      {
        label: renderLabelItem(transGeneral("download"), "/img/icon/download_outline.svg", transGeneral("download")),
        key: "1",
        onClick: () => handleDownloadFile(item),
      },
      {
        label: renderLabelItem(transBook("delete"), "/img/icon/trash_outline.svg", "trash_outline"),
        key: "2",
        onClick: () => confirmDeleteFile(item?.id),
      },
    ]

    return (
      <DropDownMenu
        className={className || ""}
        menu={{ items: items, className: classNames(CustomDropDownMenuCss) }}
        onOpenChange={(open) => handleOpenChange(open, item.id)}
      />
    )
  }

  const removeFileExtension = (url?: string) => {
    if (!url) return
    return url.split(".").slice(0, -1).join(".")
  }

  useEffect(() => {
    if (dataDownload?.data?.url) {
      if (openViewFile && fileSelected) {
        handleOpenFile(dataDownload?.data?.url)
      } else if (!openViewFile && !fileSelected) {
        handleDownload(dataDownload?.data?.url, removeFileExtension(paramDownload?.name))
      }
    }
  }, [dataDownload, countDownLoad])

  const handleDownloadFile = (item: any) => {
    setParamDownload({
      id: item.id,
      name: item.fileorgname,
      enabled: true,
    })
    setCountDownLoad((pre) => pre + 1)
  }

  const handleOpenFile = (fileUrl: string) => {
    const link = document.createElement("a")
    if (lowerCase(fileSelected?.filetype) === "pdf") {
      link.href = fileUrl
    } else link.href = `/file-render?file=${fileUrl}&type=${fileSelected?.filetype}`
    link.setAttribute("target", "_blank")
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    setOpenViewFile((pre) => !pre)
  }

  const confirmDeleteFile = (id: number) => {
    modal.confirm({
      title: transGeneral("confirm_delete"),
      okText: transButton("ok"),
      cancelText: transButton("cancel"),
      onOk() {
        handleDeleteFile(id)
      },
    })
  }

  const handleDeleteFile = (id: number) => {
    deleteFile
      .mutateAsync(id)
      .then(() => {
        refetch()
        setOpenNotify(true)
        setMessageNotify({
          type: "success",
          message: transMessage("success"),
          description: trans("delete_file_success"),
        })
      })
      .catch((error: any) => {
        setOpenNotify(true)
        setMessageNotify({
          type: "error",
          message: transMessage("something_wrong"),
          description: error?.response?.data.msgs || transMessage("fail"),
        })
      })
  }

  useEffect(() => {
    console.log(folder)
  }, [folder])

  return (
    <div className="h-full flex flex-col">
      <HeaderBreadcrumb
        items={[
          {
            aria_label: trans("my_folder"),
            href: "/documents",
            title: trans("my_folder"),
            classChevron: "hidden md:block",
          },
          {
            aria_label: folder?.foldername,
            href: `#`,
            title: folder?.foldername,
            classChevron: "hidden md:block",
            className: "!hidden md:!flex",
          },
        ]}
        slot={
          <div className="flex items-center justify-end">
            <SearchBox
              value={searchValue}
              onSearch={handleSearchKeyword}
              onChange={setSearchValue}
              placeholder={trans("search_files_here")}
              className="h-12"
              classInput="!h-12 lg:!w-56 xl:!w-56"
              classButton="!h-12 md:!pl-2"
            />
            <span className="bg-[var(--secondary-20)] w-[1px] h-10 mx-4"></span>
            <button
              onClick={() => {
                showLoading()
              }}>
              <Link
                aria-label="Add files"
                href={"#"}
                className="rounded-lg border border-solid border-[var(--primary--70)] px-4 py-[14px] font-bold bg-[var(--primary--70)] !text-white text-base hover:opacity-80 whitespace-nowrap mr-4">
                <FontAwesomeIcon icon={faPlus} />
                {trans("add_files")}
              </Link>
            </button>
            <button>
              <Link
                aria-label={trans("add_folder")}
                href={`/documents/add-folder?folderId=${folder?.id}`}
                className="rounded-lg border border-solid border-[var(--primary--70)] px-4 py-[14px] font-bold bg-[var(--primary--70)] !text-white text-base hover:opacity-80 whitespace-nowrap">
                <FontAwesomeIcon icon={faPlus} />
                {trans("add_folder")}
              </Link>
            </button>
          </div>
        }
      />
      <LoadingResult
        isLoading={isLoading && !folder?.sub_folders?.length}
        isShowResult={Boolean(folder?.sub_folders?.length || folder?.documents?.length)}
        result={
          <div className="overflow-y-auto">
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4 p-4">
              {folder?.sub_folders?.map((item: any) => (
                <CardItemDocument
                  key={item.id}
                  keyProps={item.id}
                  keyActive={activeButtons}
                  className="col-span-1 max-w-[10.438rem]"
                  url={`/documents/${item?.id}`}
                  url_image={find(FOLDER_COLOR, { value: item.bgcolor }) ? find(FOLDER_COLOR, { value: item.bgcolor })?.icon : "/img/icon/folder_blue.svg"}
                  alt_image={item?.foldername}
                  classNameBoxImg="w-[3.5rem] mt-10 mb-7"
                  classNameImage="!aspect-[6/5]"
                  classNameBoxContent="mb-4"
                  buttonTopRight={renderFolderButtonTopRight(item, "absolute top-[9px] right-[9px]")}
                  title={item?.foldername}
                  subTitle={`${item?.total_files} files`}
                />
              ))}
              {folder?.documents?.map((item: any) => (
                <CardItemDocument
                  key={item?.id}
                  keyProps={item.id}
                  keyActive={activeButtons}
                  className="col-span-1 max-w-[10.438rem]"
                  url="#"
                  url_image={types.includes(lowerCase(item.filetype)) ? `/img/files/${lowerCase(item.filetype)}.svg` : "/img/files/ukn.svg"}
                  alt_image={item?.fileorgname}
                  classNameBoxImg="w-[3.5rem] mt-10 mb-7"
                  classNameBoxContent="mb-4"
                  buttonTopRight={renderFileButtonTopRight(item, "absolute top-[9px] right-[9px]")}
                  title={item?.fileorgname}
                  subTitle={formatFileSize(item?.filesize)}
                  onClick={() => handleViewFile(item)}
                />
              ))}
            </div>
          </div>
        }
      />
      {modalContextHolder}
      <AddnewFiles
        formRef={formRef}
        open={open}
        setOpen={setOpen}
        folderId={folder?.id}
        onRefresh={() => refetch()}
      />
      <NotifyCustom
        type={messageNotify.type}
        message={messageNotify.message}
        description={messageNotify.description}
        isOpen={openNotify}
        onclose={() => setOpenNotify(false)}
      />
    </div>
  )
}
