"use client"

import { Button, Drawer, Form, Input, Upload } from "antd"
import { useTranslations } from "next-intl"
import { useEffect, useState } from "react"
import { useNotificationContext } from "../Layout/NotificationContext"
import { useUploadImage } from "@/hook/useMedia"
import classNames from "classnames"
import { SelectCountry } from "../Common/SelectCountries"
import { css } from "@emotion/css"
import { DrawerCss } from "../Contact/MyContactList/style"
import Image from "next/image"
import { LoadingBox } from "../Common/LoadingBox"
import { useUpdateMyAccount } from "@/hook/useAuth"

type IProps = {
  user: any
  isOpen: boolean
  setOpen: (value: boolean) => void
  onSuccess: () => void
}

export default function EditProfile({ user, isOpen, setOpen, onSuccess }: IProps) {
  const [formRef] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const tranButton = useTranslations("button")
  const tranForm = useTranslations("form")
  const transMessage = useTranslations("message")
  const trans = useTranslations("account")
  const transGeneral = useTranslations("general")
  const tranRequired = useTranslations("required")
  const { notify } = useNotificationContext()
  const uploadImage = useUploadImage()
  const updateMyAccount = useUpdateMyAccount()

  useEffect(() => {
    if (user) {
      formRef.setFieldsValue({
        firstname: user.firstname,
        lastname: user.lastname,
        email: user.email,
        phone_cc: user.phone_cc.includes("+") ? user.phone_cc : `+${user.phone_cc}`,
        phonenumber: user.phonenumber,
        address: user.address,
        city: user.city,
        state: user.state,
        countrycode: user.countrycode,
        zipcode: user.zipcode,
        paypalid: user.paypalid,
        photo: user?.photo
          ? [
              {
                uid: "-1",
                name: "image.png",
                status: "done",
                url: user.photo,
                response: {
                  url: user.photo || "/img/clipped.svg",
                },
              },
            ]
          : undefined,
      })
    }
  }, [user, isOpen])

  const onFinish = () => {
    formRef.validateFields().then((values: any) => {
      setLoading(true)
      const params = Object.assign({}, values)
      const fileList = formRef.getFieldValue("photo")
      if (fileList && fileList[0].response?.name) {
        params.photo = fileList[0].response?.name
      } else delete params.photo
      updateMyAccount
        .mutateAsync(params)
        .then(() => {
          notify({
            type: "success",
            message: transMessage("congratulation"),
            description: "Update profile successfully",
          })
          onSuccess()
        })
        .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)
        })
    })
  }

  const handleCancel = () => {
    setOpen(false)
    setLoading(false)
  }

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

  const handleUpload = async (options: any) => {
    const { file, onSuccess, onError } = options
    try {
      const response = await uploadImage.mutateAsync({ image: file })
      if (response.data.success) {
        notify({
          type: "success",
          message: transMessage("congratulation"),
          description: transMessage("uploaded_successfully"),
        })
        onSuccess(response.data.data)
      }
    } catch (error: any) {
      const message =
        error?.response?.data?.msgs && typeof error?.response?.data?.msgs === "object"
          ? error?.response?.data?.msgs?.image
          : error?.response?.data?.msgs || transMessage("error_during_upload")
      notify({
        type: "error",
        message: transMessage("fail"),
        description: message,
      })
      onError(error)
    }
  }

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

  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;
    }
  `

  return (
    <Drawer
      className={classNames(``, DrawerCss)}
      closable
      destroyOnClose
      title={<p>Edit User Profile</p>}
      placement="right"
      open={isOpen}
      onClose={() => setOpen(false)}
      width={450}>
      <Form
        name="form_profile"
        form={formRef}
        onFinish={onFinish}
        autoComplete="off"
        layout="vertical">
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.photo !== currentValues.photo}>
          {({ getFieldValue }) => {
            const fileList = getFieldValue("photo")
            return (
              <div>
                <div className="flex justify-center items-center pb-4">
                  <div className="relative w-28 h-28">
                    {fileList && fileList[0] && fileList[0]?.response ? (
                      <Image
                        alt=""
                        src={fileList[0]?.response ? fileList[0]?.response?.url : URL.createObjectURL(fileList[0]?.originFileObj)}
                        width={120}
                        height={120}
                        className="max-w-full w-28 h-28 max-h-full rounded-full object-cover"
                        onError={(e) => (e.currentTarget.src = "/img/clipped.svg")}
                      />
                    ) : fileList && fileList[0] && fileList[0]?.error ? (
                      <Image
                        alt=""
                        src="/img/default_image.jpg"
                        width={120}
                        height={120}
                        className="max-w-full max-h-full w-28 h-28 object-cover rounded-full"
                      />
                    ) : (
                      <LoadingBox />
                    )}
                    <button
                      type="button"
                      onClick={triggerUpload}
                      className="group bg-[var(--secondary-100)] inline-flex justify-center items-center rounded-full hover:opacity-80 w-12 h-12 absolute right-0 bottom-0 z-10">
                      <Image
                        src="/img/icon/edit-white.svg"
                        alt=""
                        width={24}
                        height={24}
                        className="w-6 h-auto"
                      />
                    </button>
                  </div>
                </div>
                <Form.Item
                  label=""
                  name="photo"
                  valuePropName="fileList"
                  getValueFromEvent={normFile}
                  className="hidden"
                  rules={[{ required: true, message: "Input Thumbnail" }]}>
                  <Upload
                    accept="image/*"
                    showUploadList={false}
                    maxCount={1}
                    customRequest={handleUpload}
                    listType="picture-card"
                    className="custom-upload-thumbnail"></Upload>
                </Form.Item>
              </div>
            )
          }}
        </Form.Item>
        <div className="grid gap-4 grid-cols-2">
          <Form.Item
            label={trans("first_name")}
            name="firstname"
            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({
                  firstname: e.target.value.trim(),
                })
              }}
              className="lg:h-12 xl:h-14 text-[var(--secondary-100)]"
            />
          </Form.Item>
          <Form.Item
            label="Last Name"
            name="lastname"
            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({
                  lastname: e.target.value.trim(),
                })
              }}
              className="lg:h-12 xl:h-14 text-[var(--secondary-100)]"
            />
          </Form.Item>
        </div>
        <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={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"
            disabled
            onBlur={(e) => {
              formRef.setFieldsValue({
                email: e.target.value.trim(),
              })
            }}
            className="lg:h-12 xl:h-14 !text-[var(--secondary-100)]"
          />
        </Form.Item>
        <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="countrycode"
          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="zipcode"
          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({
                zipcode: 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>
        <div className="pt-4 flex items-center justify-end gap-2">
          <Button
            className="grow md:!text-base lg:!text-lg font-bold !h-10 md:!h-12 !rounded-lg !border-[var(--secondary-20)] !bg-white !px-6 hover:!border-[var(--primary--70)]"
            loading={loading}
            onClick={handleCancel}>
            {tranButton("cancel")}
          </Button>
          <Button
            type="primary"
            htmlType="submit"
            onClick={onFinish}
            className="w-1/2 shrink-0 md:!text-base lg:!text-lg font-bold !h-10 md:!h-12 !rounded-lg !px-8 xl:!px-10"
            loading={loading}>
            {tranButton("submit")}
          </Button>
        </div>
      </Form>
    </Drawer>
  )
}
