"use client"

import { Avatar, Drawer } from "antd"
import classNames from "classnames"
import { DrawerCss } from "../Calendar/style"
import Image from "next/image"
import { formatFileSize } from "@/util/Common"
import { useGetContacts } from "@/hook/useContacts"
import { useEffect, useState } from "react"
import { useGetPhoShare, useSharePhoto } from "@/hook/usePhoto"
import { PAGINATION } from "@/config/constant"
import { useNotificationContext } from "../Layout/NotificationContext"
import { useTranslations } from "next-intl"
import { useGetVideoShare, useShareVideo } from "@/hook/useVideo"
import { lowerCase } from "lodash"
import { useGetProfile } from "@/hook/useAuth"

type IProps = {
  isOpen: boolean
  photo?: any
  video?: any
  type?: "photo" | "video"
  setOpen: (value: boolean) => void
}

export default function PhotoShare({ isOpen, setOpen, photo, video, type = "photo" }: IProps) {
  const [page, setPage] = useState(1)
  const [totalPage, setTotalPage] = useState(0)
  const [query, setQuery] = useState<any>({
    pageNum: page,
    pageSize: PAGINATION.DEFAULT_PAGE_SIZE,
  })
  const [contacts, setContacts] = useState<any>([])
  const transMessage = useTranslations("message")
  const { data: dataContact, isLoading } = useGetContacts(query)
  const { data: photoShate, refetch: refetchPhotoShare } = useGetPhoShare(photo?.id, photo?.id ? true : false)
  const {data: videoShare, refetch: refetchVideoShare} = useGetVideoShare(video?.id, video?.id ? true : false)
  const sharePhoto = useSharePhoto()
  const shareVideo = useShareVideo()
  const { notify } = useNotificationContext()
  const { data: user } = useGetProfile()

  const handleScroll = (e: any) => {
    const { scrollTop, scrollHeight, clientHeight } = e.target
    if (scrollTop + clientHeight >= scrollHeight - 20) {
      if (contacts.length < totalPage && !isLoading) {
        setPage(page + 1)
        setQuery({ ...query, pageNum: page + 1 })
      }
    }
  }

  useEffect(() => {
    if (dataContact) {
      if (page === 1) setContacts(dataContact?.data?.data?.contacts)
      else setContacts((pre: any) => [...pre, ...dataContact?.data?.data?.contacts])
      setTotalPage(dataContact?.data?.data?.total_pages)
    } 
  }, [dataContact])

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

  const handleShare = (user: any) => {
    if (type === "photo") {
      sharePhoto
        .mutateAsync({
          id: photo?.id,
          uid: user.uid,
        })
        .then(() => {
          notify({
            type: "success",
            message: transMessage("congratulation"),
            description: "Share photo successfully",
          })
          refetchPhotoShare()
        })
        .catch((errors) => {
          notify({
            type: "error",
            message: transMessage("something_wrong"),
            description: errors?.response?.data?.msgs || transMessage("fail"),
          })
        })
    } else {
      shareVideo
        .mutateAsync({
          id: video?.id,
          uid: user.uid,
        })
        .then(() => {
          notify({
            type: "success",
            message: transMessage("congratulation"),
            description: "Share video successfully",
          })
          refetchVideoShare()
        })
        .catch((errors) => {
          notify({
            type: "error",
            message: transMessage("something_wrong"),
            description: errors?.response?.data?.msgs || transMessage("fail"),
          })
        })
    }
  }

  return (
    <Drawer
      className={classNames(``, DrawerCss)}
      closable
      destroyOnClose
      title={<p>Share Photo</p>}
      placement="right"
      open={isOpen}
      onClose={() => setOpen(false)}
      width={594}>
      <div className="h-full flex flex-col">
        {photo ? (
          <div className="relative mb-2">
            <div className="h-72">
              <Image
                alt=""
                src={photo?.file || "/img/default_image.jpg"}
                width={370}
                height={276}
                style={{
                  width: "100%",
                  height: "100%",
                }}
                onError={(e) => (e.currentTarget.src = "/img/default_image.jpg")}
                className="max-w-full max-h-full rounded-lg object-cover"
              />
            </div>
            <div className="absolute bottom-0 left-0 w-full bg-gradient-to-t from-[rgba(0,0,0,0.8)] to-[rgba(255,255,255,0)] pb-4 px-4 md:px-6 rounded-lg text-white pt-2">
              <p className="text-xs">{photo?.title}</p>
              <p className="font-semibold text-xs">{formatFileSize(Number(photo?.fileorg_size || 0))}</p>
            </div>
          </div>
        ) : video ? (
          <video
            width="320"
            height="160"
            preload="none"
            controls
            className="w-full aspect-video rounded-lg">
            <source
              src={video.file}
              type="video/mp4"
            />
            Your browser does not support the video tag.
          </video>
        ) : null}
        <ul
          className="grow overflow-y-auto"
          onScroll={handleScroll}>
          {contacts.map((item: any, index: number) => (
            <li
              key={index}
              className="relative flex items-center justify-between py-4 border-b border-[var(--secondary-20)] last:border-b-0">
              <div className="flex items-center gap-4">
                <Avatar
                  size={42}
                  style={{ backgroundColor: "#db9a1d", color: "#fff" }}>
                  {item?.name.charAt(0)}
                </Avatar>
                <p className="font-semibold">{item.name}</p>
              </div>
              {user?.data && lowerCase(user?.data?.username) === item.uid ? (
                <p />
              ) : (type === "photo" && photoShate?.data?.users && photoShate?.data?.users.includes(String(item.uid))) ||
                (type === "video" && videoShare?.data?.users && videoShare?.data?.users.includes(String(item.uid))) ? (
                <p className="text-xs font-bold text-[var(--success-80)]">Shared</p>
              ) : (
                <button
                  type="button"
                  onClick={() => handleShare(item)}
                  className="group">
                  <Image
                    src="/img/icon/redo.svg"
                    alt="share"
                    width={24}
                    height={24}
                    className="group-hover:hidden"
                  />
                  <Image
                    src="/img/icon/redo_yellow.svg"
                    alt="share"
                    width={24}
                    height={24}
                    className="hidden group-hover:block"
                  />
                </button>
              )}
            </li>
          ))}
        </ul>
      </div>
    </Drawer>
  )
}
