"use client"

import React, { useEffect, useMemo, useRef, useState } from "react"
import { Button, Table } from "antd"
import { renderTooltipText } from "@component/Common/TooltipText"
import NotFoundBox from "@/component/Notfound"
import { useTranslations } from "next-intl"
import { IAffiliateRespon } from "@/type/Affiliate"
import { useGetListMyAffiliateByCode } from "@/hook/useUsers"
import AffiliateShareInfo from "./AffiliateShareInfo"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faCopy, faPenToSquare } from "@fortawesome/free-regular-svg-icons"
import { useCopyToClipboard } from "@/hook/useCommon"
import { AddAffiliate } from "./AddAffiliate"

interface IProps {
  dataSourceAffiliate: IAffiliateRespon[]
}

const TableAffiliate = (props: IProps) => {
  const trans = useTranslations("profile")
  const transMusic = useTranslations("music")
  const refModalAddCode = useRef<null | { showModal: () => void }>(null)

  const [widthCol, setWidthCol] = useState<number>(40)
  const [openDrawer, setOpenDrawer] = useState<boolean>(false)
  const [codeAffiliate, setCodeAffiliate] = useState("")
  const { isCopied, handleCopy } = useCopyToClipboard()
  const [codeSelected, setCodeSelected] = useState<string>("")

  const { data: ListMyAffiliateByCode, isLoading } = useGetListMyAffiliateByCode(codeAffiliate, Boolean(codeAffiliate))

  const widthNumber = useMemo(() => (props?.dataSourceAffiliate?.length > 99 ? "w-12" : "w-10"), [props?.dataSourceAffiliate?.length])

  useEffect(() => {
    const updateTabPosition = () => {
      setWidthCol(window.innerWidth >= 768 ? 55 : 48)
    }
    updateTabPosition()
    window.addEventListener("resize", updateTabPosition)

    return () => {
      window.removeEventListener("resize", updateTabPosition)
    }
  }, [])

  const handleCopyLink = (record: any) => {
    const link = `${window.location.origin}/register?referral=${record?.code}`
    handleCopy(link)
  }

  const columns: any = useMemo(
    () => [
      {
        title: trans("no"),
        key: "stt",
        dataIndex: "stt",
        align: "center",
        className: "!p-0",
        width: widthCol,
        ellipsis: {
          showTitle: false,
        },
        render: (_: any, record: any, index: number) => {
          return <div className={`text-base leading-[22px] text-[var(--secondary-100)] font-light px-2.5 py-[11px] ${widthNumber}`}>{index + 1}</div>
        },
      },
      {
        title: trans("code"),
        dataIndex: "code",
        key: "code",
        align: "center",
        className: "!p-1",
        width: 110,
        ellipsis: {
          showTitle: false,
        },
        render: (code: string) => {
          // return renderTooltipText(code, "font-semibold")
          return (
            <div className="flex items-center">
              <Button icon={<FontAwesomeIcon icon={faPenToSquare} />} className="!p-0" onClick={() => handleUpdateCode(code)}></Button>
              {renderTooltipText(code, "font-semibold text-left")}
            </div>
          )
        },
      },
      {
        title: trans("link"),
        key: "link",
        align: "left",
        width: 230,
        ellipsis: {
          showTitle: false,
        },
        render: (record: any) => {
          return (
            <Button
              type="link"
              onClick={() => handleCopyLink(record)}
              className="!p-0">
              <FontAwesomeIcon
                icon={faCopy}
                className=""
              />
              {/* <span>{trans("generate_link")}</span> */}
              <span>{`${window ? window.location.origin : "https://wizzor.net"}/register?referral=${record?.code}`}</span>
            </Button>
          )
        },
      },
      {
        title: trans("used_count"),
        dataIndex: "used",
        key: "used",
        align: "center",
        className: "!p-0",
        width: 120,
        ellipsis: {
          showTitle: false,
        },
        render: (used: string) => {
          return renderTooltipText(used, "font-light")
        },
      },
      {
        title: trans("used_list"),
        dataIndex: "code",
        key: "code",
        align: "center",
        className: "!p-0",
        width: 130,
        ellipsis: {
          showTitle: false,
        },
        render: (code: string) =>
          code ? (
            <Button
              type="link"
              onClick={() => {
                setOpenDrawer(true)
                setCodeAffiliate(code)
              }}>
              {trans("view_list")}
            </Button>
          ) : (
            "--"
          ),
      },
    ],
    [props?.dataSourceAffiliate],
  )

  const handleUpdateCode = (code: string) => {
    setCodeSelected(code)
    refModalAddCode?.current?.showModal()
  }

  return (
    <div className="flex-1 min-w-0 h-full overflow-y-auto">
      <Table
        rowKey={"id"}
        columns={columns}
        dataSource={props?.dataSourceAffiliate || []}
        pagination={false}
        scroll={{ y: 390 }}
        className="flex-1"
        locale={{
          emptyText: (
            <NotFoundBox
              className="!bg-[var(--secondary-10)] py-8 rounded-3xl"
              backHome={false}
              message={transMusic("we_found_nothing_here")}
            />
          ),
        }}
      />

      <AffiliateShareInfo
        open={openDrawer}
        setOpen={setOpenDrawer}
        loading={isLoading}
        ListMyAffiliateByCode={ListMyAffiliateByCode?.data?.data || []}
        codeAffiliate={codeAffiliate}
        setCodeAffiliate={setCodeAffiliate}
        dataSourceAffiliate={props?.dataSourceAffiliate}
      />
      <AddAffiliate
        ref={refModalAddCode}
        code={codeSelected}
      />
    </div>
  )
}

export default TableAffiliate
