"use client"

import { Link, useRouter } from "@/i18n/routing"
import { css } from "@emotion/css"
import { Button, Form, Input, Modal, Upload } from "antd"
import classNames from "classnames"
import { useTranslations } from "next-intl"
import { FormRegisterCss } from "./style"
import { useCreateNPAccount } from "@/hook/useAuth"
import { useNotificationContext } from "../Layout/NotificationContext"
import { SelectCountry } from "@component/Common/SelectCountries"
import { handleUploadFileIdProof } from "./Common"
import { LoadingBox } from "../Common/LoadingBox"
import Image from "next/image"
import { CloudUploadOutlined } from "@ant-design/icons"
import { useEffect, useState } from "react"
import { useSearchParams } from "next/navigation"
import { useCookies } from "next-client-cookies"

type Props = {
  type: any
}

export default function FormNPAccount() {
  const router = useRouter()
  const [formRef] = Form.useForm()
  const { notify } = useNotificationContext()
  const [modal, modalContextHolder] = Modal.useModal()

  const transMessage = useTranslations("message")
  const trans = useTranslations("account")
  const tranForm = useTranslations("form")
  const transButton = useTranslations("button")
  const transMarket = useTranslations("market")
  const transGeneral = useTranslations("general")
  const tranRequired = useTranslations("required")
  const transDocument = useTranslations("document")

  const createNPAccount = useCreateNPAccount()
  const { dataUploadFileIdProof, uploadFileIdProof } = handleUploadFileIdProof()

  const [code, setCode] = useState<string>("")
  const searchParams = useSearchParams()
  const cookies = useCookies()

  useEffect(() => {
    const referral = searchParams.get("referral")
    const oldCode = cookies.get("referral")
    if (referral) {
      setCode(referral)
      formRef.setFieldsValue({
        referral_code: referral,
      })
    } else if (oldCode) {
      setCode(oldCode)
    } else {
      setCode("")
    }
  }, [searchParams])

  const onFinish = (values: any) => {
    const dataReq = {
      firstname: values?.first_name,
      lastname: values?.last_name,
      username: values?.username,
      email: values?.email,
      password: values?.password,
      password_confirm: values?.confirm_password,
      phonenumber: values?.phonenumber,
      phone_cc: values?.phone_cc,
      address: values?.address,
      countrycode: values?.country,
      state: values?.state,
      city: values?.city,
      zipcode: values?.postal_code,
      idproof_file: dataUploadFileIdProof?.data?.data?.name,
      websiteurl: values?.website_url,
      referral: values?.referral_code || "",
    }

    if (!values?.referral_code && code) {
      dataReq.referral = code
    }
      createNPAccount
        .mutateAsync(dataReq)
        .then((res) => {
          // notify({
          //   type: "success",
          //   message: transMessage("congratulation"),
          //   description: trans("registration_successful"),
          // })
          notifyPlCheckMail()
        })
        .catch((error) => {
          const concatenatedMsgs = error?.response?.data.msgs ? Object.values(error?.response?.data.msgs).join("<br />") : transMessage("fail")

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

  const SelectCss = css`
    .ant-select-selection-item {
      color: var(--secondary-100) !important;
    }
    @media (min-width: 1024px) {
      height: 3rem !important;
    }

    @media (min-width: 1280px) {
      height: 3.5rem !important;
    }
  `

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

  const notifyPlCheckMail = () => {
    modal.success({
      title: `${trans("registration_successful")}, ${transGeneral("info_check_mail")}`,
      okText: transButton("ok"),
      onOk() {
        router.push("/login")
      },
    })
  }

  const triggerUpload = () => {
    const fileInput = document.querySelector("input[type='file']") as HTMLInputElement
    fileInput?.click()
  }

  return (
    <div className={classNames(FormRegisterCss)}>
      <Form
        name="p_account"
        form={formRef}
        onFinish={onFinish}
        autoComplete="off"
        layout="vertical">
        <Form.Item
          label={trans("username")}
          name="username"
          rules={[
            { required: true, message: trans("input_username_please") },
            { min: 2, message: trans("name_minimum_num_characters", { name: trans("username"), num: 2 }) },
            { max: 254, message: trans("name_maxnimum_num_characters", { name: trans("username"), num: 254 }) },
          ]}>
          <Input
            placeholder={trans("enter_your_username")}
            size="large"
            onBlur={(e) => {
              formRef.setFieldsValue({
                username: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 text-[var(--secondary-100)]"
          />
        </Form.Item>
        <Form.Item
          label={trans("password")}
          name="password"
          rules={[
            { required: true, message: trans("input_password_please") },
            { min: 8, message: trans("name_minimum_num_characters", { name: trans("password"), num: 8 }) },
            { max: 20, message: trans("name_maxnimum_num_characters", { name: trans("password"), num: 20 }) },
            {
              validator: (_, value) => {
                if (value && /\s/.test(value) && value.length <= 20 && value.length >= 8) {
                  return Promise.reject(new Error(trans("password_must_not_contain_spaces")))
                }
                return Promise.resolve()
              },
            },
          ]}>
          <Input.Password
            placeholder={trans("enter_your_password")}
            size="large"
            onBlur={(e) => {
              formRef.setFieldsValue({
                password: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 text-[var(--secondary-100)]"
          />
        </Form.Item>
        <Form.Item
          label={trans("confirm_password")}
          name="confirm_password"
          dependencies={["password"]}
          rules={[
            { required: true, message: trans("input_confirm_password_please") },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue("password") === value) {
                  return Promise.resolve()
                }
                return Promise.reject(new Error(trans("reentered_password_does_not_match")))
              },
            }),
          ]}>
          <Input.Password
            placeholder={trans("reenter_your_password")}
            size="large"
            onBlur={(e) => {
              formRef.setFieldsValue({
                confirm_password: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 text-[var(--secondary-100)]"
          />
        </Form.Item>
        <div className="grid gap-4 grid-cols-2">
          <Form.Item
            label={trans("first_name")}
            name="first_name"
            rules={[
              { required: true, message: trans("input_first_name_please") },
              { max: 256, message: trans("name_maxnimum_num_characters", { name: trans("first_name"), num: 256 }) },
            ]}>
            <Input
              placeholder={trans("enter_your_first_name")}
              size="large"
              onBlur={(e) => {
                formRef.setFieldsValue({
                  first_name: e.target.value.trim(),
                })
              }}
              className="lg:h-12 xl:h-14 text-[var(--secondary-100)]"
            />
          </Form.Item>
          <Form.Item
            label="Last Name"
            name="last_name"
            rules={[
              { required: true, message: trans("input_last_name_please") },
              { max: 256, message: trans("name_maxnimum_num_characters", { name: trans("last_name"), num: 256 }) },
            ]}>
            <Input
              placeholder={trans("enter_your_last_name")}
              size="large"
              onBlur={(e) => {
                formRef.setFieldsValue({
                  last_name: e.target.value.trim(),
                })
              }}
              className="lg:h-12 xl:h-14 text-[var(--secondary-100)]"
            />
          </Form.Item>
        </div>
        <Form.Item
          label={trans("email_ID")}
          name="email"
          rules={[
            { required: true, message: trans("input_email_please") },
            { type: "email", message: trans("input_email_type") },
            { max: 256, message: trans("name_maxnimum_num_characters", { name: trans("email_ID"), num: 256 }) },
          ]}>
          <Input
            placeholder={trans("enter_your_email_address")}
            size="large"
            onBlur={(e) => {
              formRef.setFieldsValue({
                email: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 !text-[var(--secondary-100)]"
          />
        </Form.Item>
        <p className="mb-1 text-[var(--secondary-100)] lg:text-base font-semibold">
          <span className="text-red-500">*</span> {` ${trans("phone_number")}`}
        </p>
        <div className="grid grid-cols-12 gap-2">
          <Form.Item
            className="col-span-4 lg:col-span-3 xl:col-span-2"
            label=""
            name="phone_cc"
            rules={[
              { required: true, message: tranRequired("cannot_empty") },
              {
                pattern: /^\+\d{1,4}$/,
                message: `${transGeneral("invalid_country_code")} (e.g., +84, +1)`,
              },
            ]}>
            <Input
              placeholder="+1"
              size="large"
              onBlur={(e) => {
                const value = e.target.value.trim()
                if (!value.startsWith("+")) {
                  formRef.setFieldsValue({
                    phone_cc: `+${value}`,
                  })
                } else {
                  formRef.setFieldsValue({ phone_cc: value })
                }
              }}
              className="lg:h-12 xl:h-14 !text-[var(--secondary-100)]"
            />
          </Form.Item>
          <Form.Item
            className="col-span-8 lg:col-span-9 xl:col-span-10"
            label=""
            name="phonenumber"
            rules={[
              { required: true, message: trans("input_phone_number_please") },
              { pattern: /^\+?[0-9]+$/, message: trans("invalid_phone_number") },
              { min: 10, message: trans("invalid_phone_number") },
              { max: 15, message: trans("invalid_phone_number") },
            ]}>
            <Input
              placeholder="00 000 0000"
              size="large"
              onBlur={(e) => {
                formRef.setFieldsValue({
                  phonenumber: e.target.value.trim(),
                })
              }}
              className="lg:h-12 xl:h-14 !text-[var(--secondary-100)]"
            />
          </Form.Item>
        </div>
        <Form.Item
          label={tranForm("address")}
          name="address"
          rules={[
            { required: true, message: tranRequired("cannot_empty") },
            { max: 4096, message: trans("name_maxnimum_num_characters", { name: tranForm("address"), num: 4096 }) },
          ]}>
          <Input
            placeholder={trans("input_your_contact_address")}
            size="large"
            onBlur={(e) => {
              formRef.setFieldsValue({
                address: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 !text-[var(--secondary-100)]"
          />
        </Form.Item>
        <Form.Item
          label={tranForm("city")}
          name="city"
          rules={[
            { required: true, message: tranRequired("cannot_empty") },
            { max: 4096, message: trans("name_maxnimum_num_characters", { name: tranForm("city"), num: 4096 }) },
          ]}>
          <Input
            placeholder={transMessage("placehoder_input_the_name", { name: tranForm("city") })}
            size="large"
            onBlur={(e) => {
              formRef.setFieldsValue({
                city: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 !text-[var(--secondary-100)]"
          />
        </Form.Item>
        <Form.Item
          label={tranForm("state")}
          name="state"
          rules={[
            { required: true, message: tranRequired("cannot_empty") },
            { max: 4096, message: trans("name_maxnimum_num_characters", { name: tranForm("state"), num: 4096 }) },
          ]}>
          <Input
            placeholder={trans("input_your_contact_state")}
            size="large"
            onBlur={(e) => {
              formRef.setFieldsValue({
                state: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 !text-[var(--secondary-100)]"
          />
        </Form.Item>
        <Form.Item
          label={tranForm("country")}
          name="country"
          rules={[{ required: true, message: trans("select_please") }]}>
          <SelectCountry
            className={classNames("lg:h-12 xl:h-14", SelectCss)}
            refetchOnMount={false}
          />
        </Form.Item>
        <Form.Item
          label={tranForm("postal_code")}
          name="postal_code"
          rules={[
            { required: true, message: trans("input_postal_code_please") },
            { max: 256, message: trans("name_maxnimum_num_characters", { name: tranForm("postal_code"), num: 256 }) },
          ]}>
          <Input
            placeholder={trans("enter_postal_code")}
            size="large"
            onBlur={(e) => {
              formRef.setFieldsValue({
                postal_code: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 !text-[var(--secondary-100)]"
          />
        </Form.Item>
        {/* <Form.Item
          label={trans("ID_proof")}
          name="proof"
          rules={[{ required: true, message: trans("select_ID_proof_please") }]}
          valuePropName="fileList"
          getValueFromEvent={normFile}>
          <Upload maxCount={1}>
            <button
              type="button"
              className="bg-[var(--secondary-100)] text-white w-full rounded-lg h-14">
              {trans("select_file")}
            </button>
          </Upload>
        </Form.Item> */}

        {/* <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.proof !== currentValues.proof}>
          {({ getFieldValue }) => {
            const fileList = getFieldValue("proof")
            return (
              <Form.Item
                label={trans("ID_proof")}
                name="proof"
                rules={[{ required: true, message: trans("select_ID_proof_please") }]}
                valuePropName="fileList"
                getValueFromEvent={normFile}>
                {dataUploadFileIdProof?.data && fileList ? (
                  <div className="flex mb-2">
                    <p className="m-0 mt-1 mx-2 line-clamp-1 h-5">{fileList?.[0]?.name}</p>
                    <Button
                      icon={
                        <FontAwesomeIcon
                          icon={faTrash}
                          className="text-[#e8262d]"
                        />
                      }
                      onClick={() => {
                        formRef.setFieldsValue({ proof: "" })
                      }}
                      type="default"
                      className="hover:border-[var(--primary--70)]"></Button>
                  </div>
                ) : (
                  <Upload
                    accept="image/png, image/jpg, image/gif"
                    maxCount={1}
                    showUploadList={false}
                    customRequest={handleUploadFileIdProof}>
                    <Button
                      loading={isLoadingUploadFileIdProof}
                      type="default"
                      className="!bg-[var(--secondary-100)] !text-white hover:!text-[var(--primary--70)] w-full rounded-lg !h-14">
                      {trans("select_file")}
                    </Button>
                  </Upload>
                )}
              </Form.Item>
            )
          }}
        </Form.Item> */}

        <div className="mb-4">
          <p className="text-base font-semibold mb-6">
            <span className="text-[var(--danger-50)]">*</span> {trans("ID_proof")} (2MB)
          </p>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.proof !== currentValues.proof}>
            {({ getFieldValue }) => {
              const fileList = getFieldValue("proof")
              return (
                <>
                  <div
                    className={`items-center gap-2 md:gap-6 lg:gap-2 xl:gap-4 bg-white px-2 xl:px-4 py-4 rounded-lg border-[2px] border-dashed border-[var(--secondary-40)] h-52 ${
                      fileList ? "flex" : "hidden"
                    }`}>
                    <div className="grow h-full">
                      {dataUploadFileIdProof?.data && fileList ? (
                        <Image
                          alt=""
                          src={
                            dataUploadFileIdProof?.data?.data?.url ? dataUploadFileIdProof?.data?.data?.url : URL.createObjectURL(fileList[0]?.originFileObj)
                          }
                          width={274}
                          height={216}
                          style={{
                            width: "100%",
                            height: "100%",
                          }}
                          className="max-w-full max-h-full object-cover"
                        />
                      ) : (
                        <LoadingBox />
                      )}
                    </div>
                    <div className="flex flex-col shrink-0 basis-[2rem] w-8 gap-4">
                      <button
                        type="button"
                        onClick={triggerUpload}
                        className="group bg-[var(--secondary-100)] inline-flex justify-center items-center rounded hover:opacity-80 w-8 h-8">
                        <Image
                          src="/img/icon/refresh_white.svg"
                          alt="share"
                          width={24}
                          height={24}
                        />
                      </button>
                      <button
                        type="button"
                        onClick={() => formRef.setFieldsValue({ proof: null })}
                        className="group bg-[var(--secondary-20)] inline-flex justify-center items-center rounded hover:bg-[var(--primary--70)] w-8 h-8">
                        <Image
                          src="/img/icon/trash_outline.svg"
                          alt="share"
                          width={24}
                          height={24}
                          className="group-hover:hidden"
                        />
                        <Image
                          src="/img/icon/trash_outline_white.svg"
                          alt="share"
                          width={24}
                          height={24}
                          className="hidden group-hover:block"
                        />
                      </button>
                    </div>
                  </div>
                  <Form.Item
                    label=""
                    name="proof"
                    valuePropName="fileList"
                    getValueFromEvent={normFile}
                    className={fileList ? "hidden" : ""}
                    rules={[{ required: true, message: trans("select_ID_proof_please") }]}>
                    <Upload
                      accept="image/png, image/jpg"
                      showUploadList={false}
                      listType="picture-card"
                      maxCount={1}
                      customRequest={uploadFileIdProof}
                      className="group">
                      <span className="flex gap-2 text-[var(--primary--90)] bg-[var(--primary--20)] font-semibold px-4 py-2 rounded-lg transition-transform duration-100 ease-in-out group-hover:scale-110">
                        <span>{tranForm("upload_file")}</span>
                        <CloudUploadOutlined />
                      </span>
                    </Upload>
                  </Form.Item>
                </>
              )
            }}
          </Form.Item>
        </div>

        <Form.Item
          label={transMarket("website_url")}
          name="website_url"
          rules={[
            { required: true, message: tranRequired("cannot_empty") },
            {
              pattern: /^(https?:\/\/)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(\/.*)?$/,
              message: transMessage("invalid_url"),
            },
          ]}>
          <Input
            placeholder="https://abc.com"
            size="large"
            onBlur={(e) => {
              formRef.setFieldsValue({
                website_url: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 !text-[var(--secondary-100)]"
          />
        </Form.Item>
        {/* <Form.Item
          label={trans("are_you_member_news_association")}
          name="new_association"
          rules={[{ required: true, message: trans("select_please") }]}>
          <Radio.Group>
            <Radio value="yes"> Yes </Radio>
            <Radio value="no"> No </Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label={trans("organization")}
          name="organization"
          rules={[{ max: 256, message: trans("name_maxnimum_num_characters", { name: trans("organization"), num: 256 }) }]}>
          <Input
            placeholder={trans("enter_your_organization")}
            size="large"
            onBlur={(e) => {
              formRef.setFieldsValue({
                organization: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 !text-[var(--secondary-100)]"
          />
        </Form.Item>
        <Form.Item
          label={trans("affiliated_publisher")}
          name="affiliated_publisher"
          rules={[{ max: 256, message: trans("name_maxnimum_num_characters", { name: trans("affiliated_publisher"), num: 256 }) }]}>
          <Input
            placeholder={trans("enter_affiliated_publisher")}
            size="large"
            onBlur={(e) => {
              formRef.setFieldsValue({
                affiliated_publisher: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 !text-[var(--secondary-100)]"
          />
        </Form.Item> */}
        <Form.Item
          label={trans("referral_code")}
          name="referral_code"
          rules={[{ max: 256, message: trans("name_maxnimum_num_characters", { name: trans("referral_code"), num: 256 }) }]}>
          <Input
            placeholder={trans("enter_referral_code")}
            size="large"
            onBlur={(e) => {
              formRef.setFieldsValue({
                referral_code: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 !text-[var(--secondary-100)]"
          />
        </Form.Item>
        <Form.Item
          label="Paypal Email"
          name="paypalid"
          rules={[
            { required: true, message: tranRequired("cannot_empty") },
            { max: 4096, message: trans("name_maxnimum_num_characters", { name: "Paypal Email", num: 4096 }) },
          ]}>
          <Input
            placeholder=""
            size="large"
            onBlur={(e) => {
              formRef.setFieldsValue({
                paypalid: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 !text-[var(--secondary-100)]"
          />
        </Form.Item>
        <Form.Item className="!my-10">
          <Button
            type="primary"
            htmlType="submit"
            className="w-full md:!text-base lg:!text-lg font-bold !h-12 md:!h-14 xl:!h-16 !rounded-lg uppercase"
            loading={createNPAccount?.isPending}>
            {transButton("submit")}
          </Button>
        </Form.Item>
      </Form>
      {/* <hr className="mb-6" />
      <p className="pb-8">
        {trans("by_pressing_submit_agree")}
        <Link
          href="/terms-conditions"
          scroll={false}
          className="px-2 font-semibold text-[var(--blue-70)] hover:underline">
          {trans("terms_of_service")}
        </Link>
        {trans("and")}{" "}
        <Link
          href="/privacy-policy"
          scroll={false}
          className="pl-2 font-semibold text-[var(--blue-70)] hover:underline">
          {trans("privacy_policy")}
        </Link>
        .
      </p> */}
      {modalContextHolder}
    </div>
  )
}
