import { memo, useCallback, useState } from "react";
import {
  Card,
  Input,
  InputPassword,
  Button,
  Box,
  Select,
  // InputTextArea
} from "components/Common";
import {
  Typography,
  Form,
  Divider,
  Checkbox,
  Row,
  Col,
  Modal,
} from "antd";
import styled from "styled-components";
import { AtSign, User } from "react-feather";
import { useTranslation } from "react-i18next";
import axios from "axios";
import { toast } from "react-hot-toast";
import usePath from "hooks/usePath";
import UploadButton from "components/UploadButton";
import LoadImage from "components/LoadImage";

const VisitorRegisterForm = memo(() => {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [interested, setInterested] = useState<any>([]);
  const { goToPath } = usePath();
  const [userToken, setUserToken] = useState<string>();
  const [userId, setUserId] = useState();
  const [hasUploadLogo, setHasUploadLogo] = useState(false);

  const validatePassword = useCallback(
    (rule: any, value: any, callback: any) => {
      const password = form.getFieldValue("password");
      if (value && value !== password) {
        callback("Password do not match!");
      } else {
        callback();
      }
    },
    [form]
  );

  const handleRegister = useCallback(async (data) => {
    setLoading(true);
    try {
      const { data: res } = await axios.post("/visitors/register", {
        email: data.email,
        password: data.password,
        onsite: 0,
        title: data.title,
        contact: data.contractName,
        position: data.contractPosition ?? "-",
        organization: data.contractOrg ?? "-",
        bussinessType: JSON.stringify(data.interested),
        bussinessField: data.contractBusiness,
        otherInterest: data.otherInterests || "",
        agreement: data.policyCheck,
        subscription: data.subscriptionCheck || 0,
        // address: data.address,
        tel: data.tel,
      });

      toast.success("Registration successfully!");
      setUserToken(res.token);
      setUserId(res.visitor_id);
      // goToPath({ pathname: "/login/visitor" });
    } catch (error: any) {
      if (error.response.status === 406) {
        toast.error("This email address is already being used");
      } else {
        toast.error("Registration failed! Please try again later.");
      }
      setLoading(false);
    }
  }, []);

  return (
    <>
      <Form
        style={{ width: "100%", height: "100%" }}
        layout="vertical"
        form={form}
        onFinish={handleRegister}
      >
        <Card
          padding="20px"
          direction="column"
          height="auto"
          margin_bottom="20px"
        >
          <Typography.Title level={4}>
            {t("REGISTER.VISITOR_TITLE")}
          </Typography.Title>

          <Typography.Paragraph>
            <p>{t("REGISTER.VISITOR_DES_1")}</p>
            <p>{t("REGISTER.VISITOR_DES_2")}</p>
            <p><b>{t("REGISTER.VISITOR_DES_3")}</b></p>
            <p>{t("REGISTER.VISITOR_DES_4")}</p>
            <p>{t("REGISTER.VISITOR_DES_5")}</p>
          </Typography.Paragraph>

          <Typography.Paragraph style={{ color: "var(--danger)" }}>
            * {t("REGISTER.REQUIRED")}
          </Typography.Paragraph>
        </Card>

        {/* <Card
          padding="20px"
          direction="column"
          height="auto"
          hideBorderTop
          margin_bottom="20px"
        >
          <FormItem
            name="visit"
            label={t("REGISTER.VISIT")}
            rules={[
              {
                required: true,
                message: "Please select",
              },
            ]}
          >
            <Radio.Group>
              <Radio value={0}>{t("REGISTER.VISIT_TYPE.ONLINE")}</Radio>
              <Radio value={1}>{t("REGISTER.VISIT_TYPE.ONSITE")}</Radio>
            </Radio.Group>
          </FormItem>
        </Card> */}

        <Card
          padding="20px"
          direction="column"
          height="auto"
          hideBorderTop
          margin_bottom="20px"
        >
          <Box align="center">
            <AtSign
              size={30}
              style={{
                marginRight: "10px",
                color: "var(--secondary)",
                backgroundColor: "var(--primary)",
                border: "2px solid var(--primary)",
                borderRadius: "var(--border-radius-circle)",
                padding: "5px",
              }}
            />
            <Typography.Title level={5} style={{ margin: 0 }}>
              {t("REGISTER.ACCOUNT")}
            </Typography.Title>
          </Box>
          <Divider style={{ marginTop: "10px" }} />

          <FormItem
            name="email"
            label={t("REGISTER.EMAIL")}
            rules={[
              {
                required: true,
                type: "email",
                message: "Please input your email",
              },
              ({ getFieldValue }) => ({
                validator() {
                  if (
                    getFieldValue("email") !==
                    getFieldValue("email").toLowerCase()
                  ) {
                    return Promise.reject(
                      new Error(
                        "Please input your email with lower cases [a-z] only"
                      )
                    );
                  }
                  return Promise.resolve();
                },
              }),
            ]}
          >
            <Input placeholder={t("REGISTER.EMAIL")} />
          </FormItem>
          <FormItem
            name="confirmEmail"
            label={t("REGISTER.CONFIRMEMAIL")}
            rules={[
              {
                required: true,
                type: "email",
                message: "Please input your email",
              },
              ({ getFieldValue }) => ({
                validator() {
                  if (
                    getFieldValue("email") !== getFieldValue("confirmEmail")
                  ) {
                    return Promise.reject(
                      new Error("Email confirmation does not match")
                    );
                  }
                  return Promise.resolve();
                },
              }),
            ]}
          >
            <Input placeholder={t("REGISTER.CONFIRMEMAIL")} />
          </FormItem>

          <FormItem
            name="password"
            label={t("REGISTER.PASSWORD")}
            rules={[
              {
                required: true,
                message: "Please input your password",
              },
            ]}
          >
            <InputPassword placeholder={t("REGISTER.PASSWORD")} />
          </FormItem>

          <FormItem
            name="confirmPassword"
            label={t("REGISTER.CONFIRM_PASSWORD")}
            rules={[
              {
                required: true,
                message: "Please input your password",
              },
              { validator: validatePassword },
            ]}
          >
            <InputPassword placeholder={t("REGISTER.CONFIRM_PASSWORD")} />
          </FormItem>
        </Card>

        <Card
          padding="20px"
          direction="column"
          height="auto"
          hideBorderTop
          margin_bottom="20px"
        >
          <Box align="center">
            <User
              size={30}
              style={{
                marginRight: "10px",
                color: "var(--secondary)",
                backgroundColor: "var(--primary)",
                border: "2px solid var(--primary)",
                borderRadius: "var(--border-radius-circle)",
                padding: "5px",
              }}
            />
            <Typography.Title level={5} style={{ margin: 0 }}>
              {t("REGISTER.PROFILE")}
            </Typography.Title>
          </Box>
          <Divider style={{ marginTop: "10px" }} />

          <Row gutter={[10, 0]}>
            <Col flex="100px">
              <FormItem
                name="title"
                label={t("REGISTER.TITLE")}
                rules={[
                  {
                    required: true,
                    message: "Please select your title",
                  },
                ]}
              >
                <Select placeholder={t("REGISTER.TITLE")}>
                  <Select.Option value="mr.">
                    {t("REGISTER.TITLE_TYPE.MR")}
                  </Select.Option>
                  <Select.Option value="ms.">
                    {t("REGISTER.TITLE_TYPE.MS")}
                  </Select.Option>
                  <Select.Option value="mrs.">
                    {t("REGISTER.TITLE_TYPE.MRS")}
                  </Select.Option>
                  <Select.Option value="other">
                    {t("REGISTER.OTHER")}
                  </Select.Option>
                </Select>
              </FormItem>
            </Col>

            <Col flex="auto">
              <FormItem
                name="contractName"
                label={t("REGISTER.CONTRACT_NAME")}
                rules={[
                  {
                    required: true,
                    message: "Please input your full name",
                  },
                ]}
              >
                <Input placeholder={t("REGISTER.CONTRACT_NAME")} />
              </FormItem>
            </Col>
          </Row>

          <FormItem
            name="contractPosition"
            label={t("REGISTER.POSITION")}
          >
            <Input placeholder={t("REGISTER.POSITION")} />
          </FormItem>

          <FormItem
            name="contractOrg"
            label={t("REGISTER.COMPANY_NAME")}
          >
            <Input placeholder={t("REGISTER.COMPANY_NAME")} />
          </FormItem>

          <FormItem
            name="contractBusiness"
            label={t("REGISTER.TYPE_OF_BUSINESS")}
            rules={[
              {
                required: true,
                message: "Please input your business type",
              },
            ]}
          >
            <Input placeholder={t("REGISTER.TYPE_OF_BUSINESS")} />
          </FormItem>

          <FormItem
            name="interested"
            label={t("REGISTER.INTERESTED_IN")}
            rules={[
              { required: true, message: "Please select what interests you" },
            ]}
          >
            <Select
              mode="multiple"
              allowClear
              placeholder={t("REGISTER.INTERESTED_IN")}
              onSelect={(e) => setInterested((prev: any) => [...prev, e])}
            >
              <Select.Option value="Automobiles and Components">
                {t("REGISTER.BUSINESS_TYPE.AUTOMOBILES_AND_COMPONENTS")}
              </Select.Option>
              <Select.Option value="Banks">
                {t("REGISTER.BUSINESS_TYPE.BANKS")}
              </Select.Option>
              <Select.Option value="Capital Goods">
                {t("REGISTER.BUSINESS_TYPE.CAPITAL_GOODS")}
              </Select.Option>
              <Select.Option value="Commercial and Professional Services">
                {t(
                  "REGISTER.BUSINESS_TYPE.COMMERCIAL_AND_PROFESSIONAL_SERVICES"
                )}
              </Select.Option>
              <Select.Option value="Consumer Durables and Apparel">
                {t("REGISTER.BUSINESS_TYPE.CONSUMER_DURABLES_AND_APPAREL")}
              </Select.Option>
              <Select.Option value="Consumer Services">
                {t("REGISTER.BUSINESS_TYPE.CONSUMER_SERVICES")}
              </Select.Option>
              <Select.Option value="Diversified Financials">
                {t("REGISTER.BUSINESS_TYPE.DIVERSIFIED_FINANCIALS")}
              </Select.Option>
              <Select.Option value="Education">
                {t("REGISTER.BUSINESS_TYPE.EDUCATION")}
              </Select.Option>
              <Select.Option value="Energy">
                {t("REGISTER.BUSINESS_TYPE.ENERGY")}
              </Select.Option>
              <Select.Option value="Food, Beverage, and Tobacco">
                {t("REGISTER.BUSINESS_TYPE.FOOD_BEVERAGE_AND_TOBACCO")}
              </Select.Option>
              <Select.Option value="Food and Staples Retailing">
                {t("REGISTER.BUSINESS_TYPE.FOOD_AND_STAPLES_RETAILING")}
              </Select.Option>
              <Select.Option value="Health Care Equipment and Services">
                {t("REGISTER.BUSINESS_TYPE.HEALTH_CARE_EQUIPMENT_AND_SERVICES")}
              </Select.Option>
              <Select.Option value="Household and Personal Products">
                {t("REGISTER.BUSINESS_TYPE.HOUSEHOLD_AND_PERSONAL_PRODUCTS")}
              </Select.Option>
              <Select.Option value="Insurance">
                {t("REGISTER.BUSINESS_TYPE.INSURANCE")}
              </Select.Option>
              <Select.Option value="Materials">
                {t("REGISTER.BUSINESS_TYPE.MATERIALS")}
              </Select.Option>
              <Select.Option value="Media and Entertainment">
                {t("REGISTER.BUSINESS_TYPE.MEDIA_AND_ENTERTAINMENT")}
              </Select.Option>
              <Select.Option value="Pharmaceuticals, Biotechnology, and Life -Sciences">
                {t(
                  "REGISTER.BUSINESS_TYPE.PHARMACEUTICALS_BIOTECHNOLOGY_AND_LIFE-SCIENCES"
                )}
              </Select.Option>
              <Select.Option value="Real Estate">
                {t("REGISTER.BUSINESS_TYPE.REAL_ESTATE")}
              </Select.Option>
              <Select.Option value="Retailing">
                {t("REGISTER.BUSINESS_TYPE.RETAILING")}
              </Select.Option>
              <Select.Option value="Semiconductors and Semiconductor -Equipment">
                {t(
                  "REGISTER.BUSINESS_TYPE.SEMICONDUCTORS_AND_SEMICONDUCTOR-EQUIPMENT"
                )}
              </Select.Option>
              <Select.Option value="Software and Services">
                {t("REGISTER.BUSINESS_TYPE.SOFTWARE_AND_SERVICES")}
              </Select.Option>
              <Select.Option value="Technology Hardware and Equipment">
                {t("REGISTER.BUSINESS_TYPE.TECHNOLOGY_HARDWARE_AND_EQUIPMENT")}
              </Select.Option>
              <Select.Option value="Telecommunication Services">
                {t("REGISTER.BUSINESS_TYPE.TELECOMMUNICATION_SERVICES")}
              </Select.Option>
              <Select.Option value="Transportation">
                {t("REGISTER.BUSINESS_TYPE.TRANSPORTATION")}
              </Select.Option>
              <Select.Option value="Utilities">
                {t("REGISTER.BUSINESS_TYPE.UTILITIES")}
              </Select.Option>
              <Select.Option value="Other">{t("REGISTER.OTHER")}</Select.Option>
            </Select>
          </FormItem>

          {interested.includes("Other") ? (
            <FormItem
              name="otherInterests"
              label={t("REGISTER.OTHER_INTERESTS")}
              rules={[
                {
                  required: true,
                  message: "Please input what interests you",
                },
              ]}
            >
              <Input placeholder={t("REGISTER.OTHER_INTERESTS")} />
            </FormItem>
          ) : (
            ""
          )}

          {/* <FormItem
            name="address"
            label={t("REGISTER.ADDRESS")}
            rules={[
              {
                required: true,
                message: "Please input your company address",
              },
            ]}
          >
            <InputTextArea
              autoSize={{ minRows: 2 }}
              placeholder={t("REGISTER.ADDRESS")}
            />
          </FormItem> */}

          <FormItem
            name="tel"
            label={t("REGISTER.CONTRACT_PHONE_NUMBER")}
            rules={[
              {
                required: true,
                message: "Please input your phone number",
              },
              {
                max: 14,
                message: "Please input your phone number maximum 15 digits",
              },
              ({ getFieldValue }) => ({
                validator() {
                  if (!/^[0-9+]*$/.test(getFieldValue("tel"))) {
                    return Promise.reject(
                      new Error(
                        "Please input your phone number with [0-9] or + only"
                      )
                    );
                  }
                  return Promise.resolve();
                },
              }),
            ]}
          >
            <Input placeholder={t("REGISTER.CONTRACT_PHONE_NUMBER")} />
          </FormItem>
        </Card>

        <FormItem name="subscriptionCheck" valuePropName="checked">
          <Checkbox>{t("REGISTER.ACCEPT_NEWS")}</Checkbox>
        </FormItem>

        <FormItem
          name="policyCheck"
          valuePropName="checked"
          rules={[
            {
              validator: (rule, value, callback) => {
                value ? callback() : callback("");
              },
            },
          ]}
        >
          <Checkbox>
            {t("REGISTER.ACCEPT_POLICY_1")}{" "}
            <span>
              <a href="https://online.cn-ves.com/Meta-EX/PDPA/Policy%20of%20META-EX%20VIRTUAL%20EXHIBITION%20PLATFORM.pdf" target="_blank" rel="noreferrer">(click)</a>
            </span>{" "}
            {t("REGISTER.ACCEPT_POLICY_2")}{" "}
            <span style={{ color: "var(--danger)" }}>*</span>
          </Checkbox>
        </FormItem>

        <FormItem shouldUpdate>
          {() => (
            <Button
              size="large"
              disabled={
                form.getFieldsError().filter(({ errors }) => errors.length)
                  .length > 0
              }
              loading={loading}
              type="primary"
              htmlType="submit"
              margin_bottom="40px"
            >
              {t("AUTH.REGISTER")}
            </Button>
          )}
        </FormItem>
      </Form>

      <Modal
        visible={userToken !== undefined}
        footer={false}
        closable={false}
        maskClosable={false}
        title={t("REGISTER.UPLOAD_AVATAR")}
      >
        {/* avatar */}
        <Box direction="column" height="auto">
          {hasUploadLogo ? (
            <LoadImage
              src={`${process.env.REACT_APP_STORAGE_URL}/visitor/${userId}/booth/avatar`}
            />
          ) : (
            ""
          )}
          <UploadButton
            title={
              hasUploadLogo ? t("BUTTON.CHANGE_FILE") : t("BUTTON.ADD_FILE")
            }
            name="avatar"
            headers={{
              "Content-Type": "multipart/form-data",
              Authorization: `Bearer ${userToken}`,
            }}
            path="/media/visitors/upload"
            clearPath="/media/visitors/clear"
            fallback={() => {
              setHasUploadLogo(true);
            }}
            onUpload={() => {
              setHasUploadLogo(false);
            }}
          />
        </Box>

        <Button
          type="primary"
          margin_top="24px"
          // disabled={!hasUploadLogo}
          onClick={() => {
            localStorage.setItem("verify", "/login/visitor");
            goToPath({ pathname: "/verify" });
          }}
        >
          {t("REGISTER.NEXT")}
        </Button>
      </Modal>
    </>
  );
});

const FormItem = styled(Form.Item)`
  width: 100%;
`;

export default VisitorRegisterForm;
