import { Button, Form, Image, Input, Radio, Space, Spin } from "antd";
import cx from "classnames";
import { FC, useEffect, useState } from "react";
import styles from "./signUpForm.module.scss";
import * as UserAPI from "../../pages/api/createUser";
import SingInModal from "../modal/singInModel/SingInModal";
import { useRouter } from "next/router";
import Router from "next/router";

const SignUpForm: FC<any> = () => {
  const router = useRouter();
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [selectUser, setSelectUser] = useState(1);
  const [pincode, setPincode] = useState("");
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [companyName, setCompanyName] = useState("");
  const [gst, SetGst] = useState("");
  const [pan, SetPan] = useState("");

  useEffect(() => {
    const phone2: any = localStorage.getItem("phoneData");

    setPhone(phone2);
  }, [phone]);

  const onFinish = () => {
    setLoading(true);
    if (firstName == "") {
      alert("Please Enter First Name");
    } else if (lastName == "") {
      alert("Please Enter Last Name");
    } else if (email == "") {
      alert("Please Enter Email Name");
    } else if (phone == "") {
      alert("Please Enter Phone Name");
    } else if (password == "") {
      alert("Please Enter Password ");
    } else if (password !== confirmPassword) {
      alert("Passwords don't match");
    } else {
      const params = {
        first_name: firstName,
        last_name: lastName,
        email: email,
        password: password,
        phone: phone,
        password_confirmation: confirmPassword,
        bussiness_type: selectUser,
        pincode: pincode,
        company_name: companyName,
        company_gst: gst,
        company_pan: pan,
      };
      UserAPI.createUserFetch(params).then((res) => {
        setLoading(false);
        if (res?.status) {
          const key = Object.keys(res.data)[0];
          alert(res.data[key]);
        } else {
          localStorage.setItem("loginDetails", JSON.stringify(res));

          console.log(res, "res user");
          Router.push("/home");
        }
      });
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  const img = (
    <Image
      src={"/images/loaderindispare.gif"}
      width={"100%"}
      style={{ background: "#fff", width: "200px", height: "100px" }}
    />
  );
  return (
    <>
      <div className={styles.signUpMain}>
        <div className={cx("ant-row my-7")}>
          <div
            className={cx("ant-col ant-col-sm-24 ant-col-md-24 ant-col-xl-10")}
          >
            <div className={styles.bgImageParent}>
              <div className={styles.imagesBackGround} />
              <Image
                height={"auto"}
                width={"100%"}
                src={"/images/signUp.svg"}
                alt="/images/signUp.svg"
                className={styles.m_bgImage}
              />
            </div>
          </div>
          <div
            className={cx(
              "ant-col ant-col-sm-24 ant-col-md-24 ant-col-xl-14 py-10"
            )}
          >
            <div className={styles.formMain}>
              <div className={cx("ant-row")}>
                <Button
                  className={cx("mr-2")}
                  onClick={() => setIsModalVisible(!isModalVisible)}
                >
                  Sign In
                </Button>
                <Button type="primary">Sign Up</Button>
              </div>
              <h2 className={cx("my-6", styles.titleText)}>Sign Up</h2>
              <div className={cx("my-5")}>
                <Form
                  name="normal_login"
                  className="login-form"
                  initialValues={{ remember: true }}
                  onFinish={onFinish}
                  onFinishFailed={onFinishFailed}
                >
                  <div className={cx("ant-row")}>
                    <Form.Item
                      label="First Name"
                      className={cx(
                        "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12"
                      )}
                    >
                      <Input
                        className={cx("pr-5", styles.formInput)}
                        placeholder="Please Enter First Name"
                        value={firstName}
                        onChange={(evt) => setFirstName(evt.target.value)}
                      />
                    </Form.Item>
                    <Form.Item
                      label="Last Name"
                      className={cx(
                        "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12"
                      )}
                    >
                      <Input
                        className={styles.formInput}
                        placeholder="Please Enter Last Name"
                        value={lastName}
                        onChange={(evt) => setLastName(evt.target.value)}
                      />
                    </Form.Item>
                  </div>
                  <div className={cx("ant-row")}>
                    <Form.Item
                      name="Email"
                      rules={[
                        {
                          required: false,
                          message: "Please Enter your Email Address!",
                        },
                        {
                          required: true,
                          pattern:
                            /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
                          message: `Enter Valid Mail Address`,
                        },
                      ]}
                      label="Email Address"
                      className={cx(
                        "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12 pr-3"
                      )}
                    >
                      <Input
                        className={styles.formInput}
                        placeholder="Please Enter Email"
                        value={email}
                        onChange={(evt) => setEmail(evt.target.value)}
                      />
                    </Form.Item>
                    <Form.Item
                      label="Mobile Number"
                      className={cx(
                        "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12"
                      )}
                    >
                      <Input
                        className={styles.formInput}
                        placeholder="Please Enter Mobile Number"
                        value={phone}
                        onChange={(evt) => setPhone(evt.target.value)}
                      />
                    </Form.Item>
                  </div>
                  <div className={cx("ant-row")}>
                    <Form.Item
                      name="password"
                      label="Password"
                      className={cx(
                        "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12 pr-3"
                      )}
                      rules={[
                        {
                          required: true,
                          pattern: /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/,
                          message:
                            "Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters!",
                        },
                      ]}
                    >
                      <Input
                        type="password"
                        className={styles.formInput}
                        placeholder="At Least 8 Characters"
                        value={password}
                        onCopy={(e)=>{
                          e.preventDefault()
                          return false;
                        }}
                        onChange={(evt) => setPassword(evt.target.value)}
                      />
                    </Form.Item>
                    <Form.Item
                      name="confirmPassword"
                      label="Confirm Password"
                      className={cx(
                        "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12"
                      )}
                      dependencies={["password"]}
                      rules={[
                        {
                          required: true,
                          message: "Please Enter Confirm Password!",
                        },
                        ({ getFieldValue }) => ({
                          validator(_, value) {
                            if (!value || getFieldValue("password") === value) {
                              return Promise.resolve();
                            }
                            return Promise.reject(
                              new Error(
                                "The two passwords that you entered do not match!"
                              )
                            );
                          },
                        }),
                      ]}
                    >
                      <Input
                        className={styles.formInput}
                        type="password"
                        placeholder="Please Confirm Your Password"
                        value={confirmPassword}
                        onPaste={(e)=>{
                          e.preventDefault()
                          return false;
                        }}
                        onChange={(evt) => setConfirmPassword(evt.target.value)}
                      />
                    </Form.Item>
                  </div>
                  <div className={cx("ant-row")}>
                    <Form.Item
                      label="Please Select"
                      className={cx(
                        "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12"
                      )}
                    >
                      <Radio.Group
                        value={selectUser}
                        onChange={(evt) => setSelectUser(evt.target.value)}
                      >
                        <Space direction="vertical">
                          <Radio value={1}>I am an Individual Buyer</Radio>
                          <Radio value={2}>I am a Service Engineer</Radio>
                          <Radio value={3}>I am a Business</Radio>
                        </Space>
                      </Radio.Group>
                    </Form.Item>
                    <Form.Item
                      label="Pincode"
                      className={cx(
                        "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12 pr-3"
                      )}
                    >
                      <Input
                        className={styles.formInput}
                        placeholder="Please Enter an Indian Pincode"
                        value={pincode}
                        onChange={(evt) => setPincode(evt.target.value)}
                      />
                    </Form.Item>
                  </div>
                  {selectUser === 3 ? (
                    <div style={{ width: "100%" }}>
                      <Form.Item
                        label="Company Name"
                        className={cx(
                          "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12",
                          styles.formItem
                        )}
                        rules={[
                          {
                            required: true,
                            message: "Please Enter Company Name!",
                          },
                        ]}
                      >
                        <Input
                          className={styles.formInput}
                          placeholder="Please Enter Your Company Name "
                          value={companyName}
                          onChange={(evt) => setCompanyName(evt.target.value)}
                        />
                      </Form.Item>
                      <Form.Item
                        name="GST"
                        rules={[
                          {
                            required: false,
                            message: "Please Enter GST Number!",
                          },
                          {
                            required: true,
                            pattern:
                              /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/,
                            message: `Enter Valid GST Number!`,
                          },
                        ]}
                        label="GST Number"
                        className={cx(
                          "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12",
                          styles.formItem
                        )}
                      >
                        <Input
                          maxLength={15}
                          className={styles.formInput}
                          placeholder="Please Enter GST Number"
                          value={gst}
                          onChange={(evt) => SetGst(evt.target.value)}
                        />
                      </Form.Item>
                      <Form.Item
                        name="Pan"
                        rules={[
                          {
                            required: false,
                            message: "Please Enter Pan Number!",
                          },
                          {
                            required: true,
                            pattern: /[A-Z]{5}[0-9]{4}[A-Z]{1}$/,
                            message: `Enter Valid Pan Number`,
                          },
                        ]}
                        label="PAN Card"
                        className={cx(
                          "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12",
                          styles.formItem
                        )}
                      >
                        <Input
                          maxLength={15}
                          className={styles.formInput}
                          placeholder="Please Enter a PAN"
                          value={pan}
                          onChange={(evt) => SetPan(evt.target.value)}
                        />
                      </Form.Item>
                    </div>
                  ) : null}
                  <Form.Item>
                    <Button type="primary" htmlType="submit">
                      Signup
                    </Button>
                  </Form.Item>
                </Form>
              </div>
            </div>
          </div>
        </div>
        <SingInModal
          handleClose={() => {
            setIsModalVisible(false);
          }}
          isModalVisible={isModalVisible}
          page={"home"}
        />
        <div
          className={cx("justify-center align-center")}
          style={{
            width: "100%",
            left: "50%",
            top: "50%",
            position: "absolute",
            background: "tranparent",
          }}
        >
          <Spin
            spinning={loading}
            indicator={img}
            size="large"
            tip="Loading..."
          />
        </div>
      </div>
    </>
  );
};
export default SignUpForm;
