"use client"

import { formatCurrency } from "@/util/Common"
import { EditOutlined } from "@ant-design/icons"
import { Button, Col, Form, Input, Row, Typography, Upload } from "antd"
import { useTranslations } from "next-intl"
import Image from "next/image"
import HeaderBreadcrumb from "@component/Layout/HeaderBreadcrumb"
import { Link, useRouter } from "@/i18n/routing"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faPlus } from "@fortawesome/free-solid-svg-icons"
import TableAffiliate from "./TableAffiliate"
import { useEffect, useMemo, useRef, useState } from "react"
import { IUserProfile } from "@/type/User"
import { useGetListMyAffiliate, useUpdateMyAffiliate, useUpdateMyAffiliateWithdrawal } from "@/hook/useUsers"
import { useGetGeneral } from "@/hook/useCommon"
import { useNotificationContext } from "@component/Layout/NotificationContext"
import { LoadingBox } from "@component/Common/LoadingBox"
import classNames from "classnames"
import { AffiliateCss } from "./style"
import { handleUploadImage } from "@component/Account/Common"
import { AddAffiliate } from "./AddAffiliate"
import { AffiliateRules } from "./AffiliateRules"
import { useUpdateMyAccount } from "@/hook/useAuth"

type IProps = {
  user: IUserProfile
  isLoading: boolean
  onOpenFAQ: () => void
  onOpenProfile: () => void
  onReloadUser: () => void
}

export default function Affiliate({ user, isLoading, onOpenFAQ, onOpenProfile, onReloadUser }: IProps) {
  const [formRef] = Form.useForm()
  const { notify } = useNotificationContext()
  const router = useRouter()
  const refModalAddCode = useRef<null | { showModal: () => void }>(null)

  const trans = useTranslations("profile")
  const tranButton = useTranslations("button")
  const transMessage = useTranslations("message")
  const tranRequired = useTranslations("required")

  const [isEditDescription, setIsEditDescription] = useState(false)
  const [isLoadingRequestAmount, setIsLoadingRequestAmount] = useState(false)

  const { data: listAffiliate } = useGetListMyAffiliate()
  const { data: general } = useGetGeneral()
  const updateMyAffiliate = useUpdateMyAffiliate()
  const updateMyAffiliateWithdrawal = useUpdateMyAffiliateWithdrawal()

  const { dataUploadImage, isPending, uploadFileImage } = handleUploadImage()

  const codeCount = useMemo(() => listAffiliate?.data?.length || 0, [listAffiliate?.data])
  const [openModalSubscribe, setOpenModalSubscribe] = useState(false)
  const updateMyAccount = useUpdateMyAccount()
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (user && !user?.affiliate_accept) {
      setOpenModalSubscribe(true)
    } else setOpenModalSubscribe(false)
  }, [user])

  const renderInfoAffiliate = (colLeft: any, colRight: any, classLeft?: string, classRight?: string) => {
    return (
      <>
        <Col
          xs={{ span: 12 }}
          sm={{ span: 12 }}
          md={{ span: 12 }}
          lg={{ span: 12 }}>
          <Typography.Text className={`font-normal text-base leading-[22px] text-[var(--secondary-100)] ${classLeft}`}>{colLeft}</Typography.Text>
        </Col>
        <Col
          className="text-right"
          xs={{ span: 12 }}
          sm={{ span: 12 }}
          md={{ span: 12 }}
          lg={{ span: 12 }}>
          <Typography.Text className={`font-semibold text-base leading-[22px] text-[var(--secondary-100)] ${classRight}`}>{colRight}</Typography.Text>
        </Col>
      </>
    )
  }

  const handleUpdateMyAffiliate = (typeUpdate: "logo" | "desc") => {
    const dataForm = formRef.getFieldsValue()
    const dataRq = {
      ...(dataForm?.affiliate_desc && typeUpdate === "desc" && isEditDescription && { affiliate_desc: dataForm?.affiliate_desc }),
      ...(dataForm?.affiliate_logo && typeUpdate === "logo" && dataUploadImage?.data?.data?.name && { affiliate_logo: dataUploadImage?.data?.data?.name }),
    }

    updateMyAffiliate
      .mutateAsync(dataRq)
      .then(() => {
        setIsEditDescription(false)
        notify({
          type: "success",
          message: transMessage("congratulation"),
          description: transMessage("update_successfully"),
        })
      })
      .catch((error) => {
        const concatenatedMsgs = error?.response?.data.msgs || transMessage("fail")

        notify({
          type: "error",
          message: transMessage("something_wrong"),
          description: concatenatedMsgs,
        })
      })
  }

  useEffect(() => {
    if (dataUploadImage?.data?.data?.name) {
      handleUpdateMyAffiliate("logo")
    }
  }, [dataUploadImage])

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e
    }
    return e?.fileList
  }

  const handleUpdateMyAffiliateWithdrawal = () => {
    setIsLoadingRequestAmount(true)

    updateMyAffiliateWithdrawal
      .mutateAsync()
      .then(() => {
        notify({
          type: "success",
          message: transMessage("congratulation"),
          description: transMessage("update_successfully"),
        })
      })
      .catch((error) => {
        const concatenatedMsgs = error?.response?.data.msgs || transMessage("fail")

        notify({
          type: "error",
          message: transMessage("something_wrong"),
          description: concatenatedMsgs,
        })
      })
      .finally(() => {
        setTimeout(() => {
          setIsLoadingRequestAmount(false)
        }, 3000)
      })
  }

  const handleEmailClick = () => {
    router.push(`mailto:${general?.data?.admin_email || "administration@wizzor.net"}`)
  }

  const handleSubscribe = () => {
    setLoading(true)
    setOpenModalSubscribe(false)
    const params = {
      affiliate_accept: true,}
    updateMyAccount
      .mutateAsync(params)
      .then(() => {
        notify({
          type: "success",
          message: transMessage("congratulation"),
          description: "Update profile successfully",
        })
        onReloadUser()
      })
      .catch((errors) => {
        const message =
          errors?.response?.data?.msgs && typeof errors?.response?.data?.msgs === "object"
            ? Object.values(errors?.response?.data?.msgs).join("<br />")
            : errors?.response?.data?.msgs || transMessage("fail")
        notify({
          type: "error",
          message: transMessage("something_wrong"),
          description: message,
        })
      })
      .finally(() => {
        setLoading(false)
      })
    
  }

  return isLoading ? (
    <LoadingBox />
  ) : (
    <>
      {openModalSubscribe ? (
        <AffiliateRules
          isLoading={loading}
          onAccept={handleSubscribe}
          onCancel={() => onOpenProfile()}
        />
      ) : (
        <Form
          name="affiliate"
          form={formRef}
          autoComplete="off"
          className={classNames(AffiliateCss)}
          layout="vertical">
          <div className="flex flex-col xl:flex-row gap-6 py-5 max-w-full border border-[var(--secondary-30)] rounded-lg">
            <div className="mx-4 xl:ml-4 xl:mr-0 flex flex-col items-center shrink-0">
              <Form.Item
                noStyle
                shouldUpdate={(prevValues, currentValues) => prevValues.affiliate_logo !== currentValues.affiliate_logo}>
                {({ getFieldValue }) => {
                  const fileList = getFieldValue("affiliate_logo")
                  return (
                    <>
                      <div className={`items-center bg-white px-2`}>
                        <div className="grow h-full">
                          {(dataUploadImage?.data && fileList) || user?.affiliate_logo ? (
                            <Image
                              src={user?.affiliate_logo || ""}
                              alt="logo affiliate"
                              width={134}
                              height={134}
                              className="rounded-lg aspect-square max-w-full mb-6"
                            />
                          ) : (
                            <LoadingBox />
                          )}
                        </div>
                      </div>
                      <Form.Item
                        label=""
                        name="affiliate_logo"
                        valuePropName="fileList"
                        getValueFromEvent={normFile}
                        rules={[{ required: true, message: tranRequired("cannot_empty") }]}>
                        <Upload
                          accept="image/png, image/jpg"
                          showUploadList={false}
                          listType="picture-card"
                          maxCount={1}
                          customRequest={uploadFileImage}
                          className="group custom_upload">
                          <Button
                            loading={isPending}
                            type="default"
                            icon={<EditOutlined />}
                            className="md:!text-base font-bold !h-10 !rounded-lg">
                            {trans("update_logo")}
                          </Button>
                        </Upload>
                      </Form.Item>
                    </>
                  )
                }}
              </Form.Item>
            </div>
            <div className="border-b xl:border-r border-[var(--secondary-20)] border-solid"></div>

            <div className="mx-4 xl:ml-0 xl:mr-4">
              <Row
                className="mb-6"
                justify="end"
                gutter={[0, 15]}>
                {renderInfoAffiliate(`${trans("total_affiliate_code_limit")}:`, general?.data?.affiliate?.code_num_limit || 0)}
                {renderInfoAffiliate(`${trans("your_affiliate_code_count")}:`, codeCount)}
                {renderInfoAffiliate(`${trans("your_balance")}:`, `$${formatCurrency(user?.balance || 0)}`)}
                {renderInfoAffiliate(`${trans("minimum_withdraw_request")}:`, `$${formatCurrency(general?.data?.affiliate?.min_withdrawal_limit || 0)}`)}
              </Row>

              <div className="flex items-center gap-2 justify-center">
                <Button
                  onClick={handleEmailClick}
                  type="primary"
                  className="flex-1 md:!text-base font-bold !h-10 md:!h-12 !rounded-lg">
                  {trans("email_invites")}
                </Button>
                <Button
                  onClick={handleUpdateMyAffiliateWithdrawal}
                  loading={isLoadingRequestAmount}
                  className="flex-1 md:!text-base font-bold !h-10 md:!h-12 !rounded-lg !text-white !border-[var(--secondary-100)] !bg-[var(--secondary-100)]">
                  {trans("request_mount")}
                </Button>
              </div>
            </div>
          </div>
          <div className="font-normal text-base leading-[22px] text-[var(--secondary-100)] my-6">
            {isEditDescription ? (
              <div>
                <Form.Item name="affiliate_desc">
                  <Input.TextArea
                    rows={4}
                    maxLength={256}
                    defaultValue={user?.affiliate_desc || ""}
                  />
                </Form.Item>
                <div className="flex">
                  <Button
                    loading={updateMyAffiliate?.isPending}
                    type="default"
                    onClick={() => setIsEditDescription(false)}
                    className="rounded-lg border border-solid border-[var(--secondary-20)] !h-12 px-8 font-semibold bg-[var(--secondary-10)] hover:border-[var(--primary--70)] hover:text-[var(--primary--70)]">
                    {tranButton("cancel")}
                  </Button>
                  <Button
                    loading={updateMyAffiliate?.isPending}
                    type="primary"
                    onClick={() => {
                      handleUpdateMyAffiliate("desc")
                    }}
                    className="rounded-lg border border-solid border-[var(--primary--70)] !h-12 px-8 font-semibold bg-[var(--primary--70)] text-white hover:opacity-80 ml-2">
                    {tranButton("update")}
                  </Button>
                </div>
              </div>
            ) : (
              <div className="flex">
                <p>{user?.affiliate_desc || ""}</p>
                <Button
                  className="-mt-1 ml-1 !shadow-none !border-0 !border-white !bg-white"
                  type="default"
                  icon={<EditOutlined />}
                  onClick={() => {
                    setIsEditDescription(true)
                  }}
                />
              </div>
            )}
            <p>
              You can check:{" "}
              <Link
                href="#"
                scroll={false}
                onClick={onOpenFAQ}
                className="hover:underline text-blue-500">
                How does it work?
              </Link>
            </p>
          </div>
          <div className="border border-[var(--secondary-20)] rounded-lg">
            <HeaderBreadcrumb
              className="flex-col !items-start xl:flex-row xl:!items-center"
              classNameContent="mb-2 xl:mb-0"
              showButton={false}
              items={[
                {
                  aria_label: trans("my_affiliate_code_list"),
                  href: "#",
                  title: trans("my_affiliate_code_list"),
                },
              ]}
              subtitle={trans("you_can_check_who_used_your_code")}
              slot={
                <div>
                  <Link
                    href={"#"}
                    aria-label="Edit album"
                    onClick={() => refModalAddCode?.current?.showModal()}
                    className="inline-block 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_affiliate_code")}`}
                  </Link>
                </div>
              }
            />
            <div className="flex flex-col-reverse lg:flex-row overflow-hidden">
              <TableAffiliate dataSourceAffiliate={listAffiliate?.data || []} />
            </div>
          </div>
        </Form>
      )}
      <AddAffiliate ref={refModalAddCode} />
    </>
  )
}
