import { BooksApi } from "@/api/BooksApi"
import { KuisineApi } from "@/api/KuisineApi"
import { MarketApi } from "@/api/MarketApi"
import { LoadingBox } from "@/component/Common/LoadingBox"
import { useNotificationContext } from "@/component/Layout/NotificationContext"
import { useGetCommentBook } from "@/hook/useBooks"
import { useGetPostCommentList } from "@/hook/useKuisine"
import { useGetCommentMarket } from "@/hook/useMarket"
import { CheckOutlined, CloseOutlined } from "@ant-design/icons"
import { Button, Col, Divider, Flex, Modal, Image as AntImage, Row, Space } from "antd"
import { AxiosError } from "axios"
import dayjs from "dayjs"
import Image from "next/image"
import { FC, useMemo, useState } from "react"
//

interface IProps {
  show: boolean
  onClose: () => void
  bgImageUrl: string
  categoryName: string
  feedType: "book" | "market" | "kuisine"
  feedId: string | number
  seen: number
  booked?: number
  visited?: number
  shared?: number
  clicked?: number
  onRefetch?: () => void
}
//
const EmptyApproval: FC = () => {
  return (
    <div className="w-full h-[500px] bg-[#F9FAFC] flex justify-center items-center flex-col gap-10 rounded-[10px]">
      <Image
        src={"/img/comment_approval_empty.png"}
        width={216}
        height={178}
        alt="auto"
      />
      <div>
        <p className="font-bold text-center text-lg text-[#9CA3AF]">We found nothing here</p>
      </div>
    </div>
  )
}
//
const CommentItem: FC<{
  avatar: string
  username: string
  email: string
  content: string
  date: string
  itemId: string
  approval: string
  type: "book" | "market" | "kuisine"
  onSuccess: () => void
  onRefetch?: () => void
}> = (props) => {
  const { avatar, content, date, email, username, itemId, approval = "0", type, onSuccess, onRefetch } = props
  const { notify } = useNotificationContext()
  const [approveStatus, setApproveStatus] = useState<string>(approval)
  const [isLoading, setIsLoading] = useState<boolean>(false)
  const handleAction = async (action: "approve" | "reject") => {
    setIsLoading(true)
    try {
      const apiService = type === "book" ? BooksApi : type === "kuisine" ? KuisineApi : MarketApi
      const res = await apiService.approveComment(itemId, { action })
      if (res) {
        notify({ type: "success", message: res.data.msg })
        setApproveStatus(action === "approve" ? "1" : "2")
        onSuccess()
        onRefetch && onRefetch()
      }
    } catch (err) {
      if (err instanceof AxiosError) {
        notify({ type: "error", message: err.response?.data.msgs })
      }
    } finally {
      setIsLoading(false)
    }
  }
  if (approveStatus === "0") {
    return (
      <div className="overflow-hidden bg-[#F9FAFC] rounded-[10px] p-4">
        <Row gutter={16}>
          <Col span={2}>
            <div className="bg-gray-200 rounded-[10px] w-[42px] h-[42px]">
              <Image
                src={avatar}
                alt="Avatar"
                fill
                className="rounded-[10px]"
              />
            </div>
          </Col>
          <Col span={22}>
            <Flex
              vertical
              gap={8}>
              <Flex
                gap={16}
                className="!flex-shrink-0">
                <div>
                  <p className="font-semibold">{username}</p>
                  <p className="text-xs font-light">{email}</p>
                </div>
                <Flex
                  gap={16}
                  className="ml-auto">
                  <Button
                    loading={isLoading}
                    disabled={isLoading}
                    onClick={() => handleAction("approve")}
                    size="large"
                    type="primary"
                    className="!bg-[#359020]"
                    icon={<CheckOutlined />}>
                    Approve
                  </Button>
                  <Button
                    loading={isLoading}
                    disabled={isLoading}
                    onClick={() => handleAction("reject")}
                    size="large"
                    variant="outlined"
                    icon={<CloseOutlined />}
                    className="!bg-[#E5E7EB]">
                    Reject
                  </Button>
                </Flex>
              </Flex>
              <div>
                <p>{content}</p>
                <p className="text-xs text-[#6B7280]">{date}</p>
              </div>
            </Flex>
          </Col>
        </Row>
      </div>
    )
  } else {
    return <></>
  }
}
const CommentApprovalModal: FC<IProps> = (props) => {
  const { bgImageUrl, categoryName, show, onClose, feedType, feedId, seen, booked, clicked, shared, visited } = props

  const [activeValue, setActiveValue] = useState<string>("manual")
  const [refresh, setRefresh] = useState<boolean>(false)
  const { data: bookCommentList, isLoading: loadingBookCmt } = useGetCommentBook(feedId as number, feedType === "book" && show && (!refresh || refresh))
  const listCommentBook = useMemo(() => bookCommentList?.data.comments.filter((item) => item.approval === "0") || [], [bookCommentList])
  const { data: kuisineCommentList, isLoading: loadingKuisine } = useGetPostCommentList(
    feedId as string,
    feedType === "kuisine" && show && (!refresh || refresh),
  )
  const listKuisineComt = useMemo(() => kuisineCommentList?.pages[0]?.data?.data?.comments?.filter((item) => item.approval === "0") || [], [kuisineCommentList])
  const { data: marketCommentList, isLoading: loadingMarket } = useGetCommentMarket(feedId as number, feedType === "market" && show && (!refresh || refresh))
  const listCommenMarket = useMemo(() => marketCommentList?.data.comments.filter((item) => item.approval === "0") || [], [marketCommentList])
  const DATA: Array<{ value: string; label: string; iconPath: string }> = [
    {
      value: "auto",
      label: "Auto Approval",
      iconPath: "/img/icon/earth.svg",
    },
    { value: "manual", label: "Need Approval", iconPath: "/img/icon/warning.svg" },
  ]
  const toggleRefresh = () => setRefresh((prev) => !prev)

  return (
    <Modal
      open={show}
      onCancel={onClose}
      title="Comment Approval"
      classNames={{
        footer: "!pt-4",
      }}
      width={1180}
      footer={null}
      centered>
      <Row gutter={[16, 16]}>
        <Col
          xs={24}
          xl={8}>
          <div className="relative w-[263px] h-[256px] rounded-[10px] flex-none">
            <Image
              src={bgImageUrl}
              fill
              alt="bg-image"
              className="object-cover rounded-[10px]"
            />
            <Flex
              vertical
              justify="space-between"
              className="absolute w-full h-full left-0 top-0 rounded-[10px]">
              <div></div>
              <Flex
                vertical
                gap={4}
                className="px-4 pb-2 rounded-b-[10px]"
                style={{ background: "linear-gradient(180deg, rgba(255,255,255,0) 10%, rgba(0,0,0,1) 100%)" }}>
                <p className="font-bold text-white">{categoryName}</p>
                <Row>
                  <Col span={12}>
                    <Space>
                      <AntImage
                        preview={false}
                        src="/img/icon/eye.svg"
                        width={24}
                        height={24}
                        alt="time"
                      />
                      <p className="text-white text-sm">{seen} seen</p>
                    </Space>
                  </Col>
                  {clicked !== undefined ? (
                    <Col span={12}>
                      <Space>
                        <AntImage
                          preview={false}
                          src="/img/icon/cursor_click.svg"
                          width={24}
                          height={24}
                          alt="time"
                        />
                        <p className="text-white text-sm">232 clicked</p>
                      </Space>
                    </Col>
                  ) : (
                    <></>
                  )}
                  {shared !== undefined ? (
                    <Col span={12}>
                      <Space>
                        <AntImage
                          preview={false}
                          src="/img/icon/share_arrow.svg"
                          width={24}
                          height={24}
                          alt="time"
                        />
                        <p className="text-white text-sm">232 shared</p>
                      </Space>
                    </Col>
                  ) : (
                    <></>
                  )}
                  <Col span={12}>
                    {booked !== undefined ? (
                      <Space>
                        <AntImage
                          preview={false}
                          src="/img/icon/check.svg"
                          width={24}
                          height={24}
                          alt="time"
                        />
                        <p className="text-white text-sm">{booked} booked</p>
                      </Space>
                    ) : visited !== undefined ? (
                      <Space>
                        <AntImage
                          preview={false}
                          src="/img/icon/visited.svg"
                          width={24}
                          height={24}
                          alt="time"
                        />
                        <p className="text-white text-sm">{booked} visited</p>
                      </Space>
                    ) : (
                      <></>
                    )}
                  </Col>
                </Row>
              </Flex>
            </Flex>
          </div>
        </Col>
        <Col
          xs={24}
          xl={16}>
          <p className="font-semibold mb-4">Comment Approval Setting</p>
          <Flex
            align="center"
            justify="space-between"
            gap={16}
            wrap>
            <Row
              gutter={[16, 16]}
              className="lg:w-2/3">
              {DATA.map((item, index) => {
                const isActive = item.value === activeValue
                return (
                  <Col
                    key={index}
                    xs={24}
                    lg={12}>
                    <Flex
                      onClick={() => setActiveValue(item.value)}
                      align="center"
                      gap={16}
                      className="rounded-md border border-gray-200 h-[60px] px-4 cursor-pointer"
                      key={index}>
                      <Image
                        src={isActive ? "/img/icon/checked.svg" : "/img/icon/unchecked.svg"}
                        width={24}
                        height={24}
                        alt="check"
                      />
                      <Flex
                        align="center"
                        gap={10}>
                        <Image
                          src={item.iconPath}
                          width={24}
                          height={24}
                          alt="icon"
                        />
                        {item.label}
                      </Flex>
                    </Flex>
                  </Col>
                )
              })}
            </Row>
            <Flex
              align="center"
              gap={16}>
              <Button
                size="large"
                type="primary"
                className="!bg-gray-900"
                onClick={onClose}>
                Apply
              </Button>
              <Button
                size="large"
                variant="outlined"
                onClick={onClose}>
                Cancel
              </Button>
            </Flex>
          </Flex>
          <Divider />
          {/* Content */}
          {activeValue === "auto" ? (
            <div className="w-full h-[500px] bg-[#F9FAFC] flex justify-center items-center flex-col gap-10 rounded-[10px]">
              <Image
                src={"/img/auto_approve_comment.png"}
                width={216}
                height={178}
                alt="auto"
              />
              <div>
                <p className="font-bold text-center text-lg text-[#9CA3AF]">Your setting is currently auto-approval</p>
                <p
                  onClick={() => setActiveValue("manual")}
                  className="cursor-pointer font-bold text-center text-lg text-[#030712] underline">
                  Change to [Need Approval]
                </p>
              </div>
            </div>
          ) : (
            <Flex
              vertical
              gap={8}>
              {loadingBookCmt || loadingKuisine || loadingMarket ? <LoadingBox /> : <></>}
              {feedType === "book" ? (
                listCommentBook.length > 0 ? (
                  listCommentBook.map((item) => (
                    <CommentItem
                      onSuccess={toggleRefresh}
                      type={feedType}
                      approval={item.approval}
                      itemId={`${item.id}`}
                      avatar={item.user?.photo}
                      content={item.comments}
                      date={dayjs.unix(Number(item.created)).format("MMMM DD,YYYY")}
                      email={item.user?.email}
                      username={item.user ? item.user?.firstname || "" + " " + item.user?.lastname || "" : "Anonymous"}
                      onRefetch={props.onRefetch} // Pass onRefetch prop to CommentItem
                    />
                  ))
                ) : !loadingBookCmt ? (
                  <EmptyApproval />
                ) : (
                  <></>
                )
              ) : feedType === "kuisine" ? (
                listKuisineComt.length > 0 ? (
                  listKuisineComt.map((item) => (
                    <CommentItem
                      onSuccess={toggleRefresh}
                      type={feedType}
                      approval={item.approval}
                      itemId={item.id}
                      avatar={item.user?.photo || ""}
                      content={item.comments}
                      date={dayjs.unix(Number(item.created)).format("MMMM DD,YYYY")}
                      email={item.user?.email || ""}
                      username={item.user ? item.user?.firstname || "" + " " + item.user?.lastname || "" : "Anonymous"}
                      onRefetch={props.onRefetch}
                    />
                  ))
                ) : !loadingKuisine ? (
                  <EmptyApproval />
                ) : (
                  <></>
                )
              ) : feedType === "market" ? (
                listCommenMarket.length > 0 ? (
                  listCommenMarket.map((item) => (
                    <CommentItem
                      onSuccess={toggleRefresh}
                      type={feedType}
                      approval={item.approval}
                      itemId={item.id}
                      avatar={item.user?.photo || ""}
                      content={item.comment}
                      date={dayjs.unix(Number(item.created)).format("MMMM DD,YYYY")}
                      email={item.user?.email || ""}
                      username={item.user ? item.user?.firstname || "" + " " + item.user?.lastname || "" : "Anonymous"}
                      onRefetch={props.onRefetch}
                    />
                  ))
                ) : !loadingMarket ? (
                  <EmptyApproval />
                ) : (
                  <></>
                )
              ) : (
                <></>
              )}
            </Flex>
          )}
        </Col>
      </Row>
    </Modal>
  )
}
export default CommentApprovalModal
