import { Button, Checkbox, Form, Input, Modal } from "antd";
import cx from "classnames";
import Link from "next/link";
import { useRouter } from "next/router";
import { FC, useState } from "react";
import OTPModal from "../otpModal/OTPModal";
import styles from "./signInModal.module.scss";
import * as LoginAPI from "../../../pages/api/login";
import firebase, { initializeApp } from "firebase/app";
import {
  getAuth,
  GoogleAuthProvider,
  signInWithPopup,
  FacebookAuthProvider,
} from "firebase/auth";

import firebaseConfig from "../../../constants/firebaseConfig";

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

const SingInModal: FC<any> = (props) => {
  const { isModalVisible, handleClose } = props;
  const [isOTPModalVisible, setIsOTPModalVisible] = useState(false);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isRemeberLogin, setIsRemeberLogin] = useState(false);

  const router = useRouter();
  function onChange(e: any) {
    console.log(`checked = ${e.target.checked}`);
    setIsRemeberLogin(!isRemeberLogin);
  }

  const onFinish = () => {
    const params = {
      email: email,
      password: password,
    };
    LoginAPI.loginFetch(params).then((res) => {
      console.log(res, "res");
      localStorage.setItem("loginDetails", JSON.stringify(res));
      handleClose();
      router.push({
        pathname: `/home`,
      });
    });
  };

  const signInWithGoogle = () => {
    const provider = new GoogleAuthProvider();
    provider.setCustomParameters({ prompt: "select_account" });
    signInWithPopup(auth, provider)
      .then((res) => {
        console.log(res, "res gmail");
        handleClose();
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const signInwithFacebook = () => {
    const provider = new FacebookAuthProvider();
    provider.setCustomParameters({ prompt: "select_account" });
    signInWithPopup(auth, provider)
      .then((res) => {
        console.log(res, "res face");
        handleClose();
      })
      .catch((err) => {
        console.log(err);
      });
  };

  return (
    <>
      <Modal
        width={830}
        visible={isModalVisible}
        onOk={handleClose}
        onCancel={handleClose}
        footer={null}
        destroyOnClose={true}
      >
        <h2 className={styles.headerTitle}>Sign in to your Account</h2>
        <h5 className={styles.headerSubTitle}>
          Why? For a faster, smarter & more rewarding shopping experience
        </h5>
        <div className={cx("ant-row")}>
          <div
            className={cx(
              "ant-col ant-col-sm-24 ant-col-md-8 ant-col-xl-12 mt-5 pr-10"
            )}
          >
            <Form
              name="normal_login"
              className="login-form"
              initialValues={{ remember: true }}
              onFinish={onFinish}
            >
              <Form.Item
                name="username"
                rules={[
                  {
                    required: true,
                    message: "Please Enter your Email Address!",
                  },
                  {
                    pattern: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
                    message: `Enter Valid Mail Address`,
                  },
                ]}
              >
                <Input
                  type="text"
                  placeholder="Email Address"
                  className={styles.userName}
                  value={email}
                  onChange={(event) => setEmail(event.target.value)}
                />
              </Form.Item>
              <Form.Item
                name="password"
                rules={[
                  { required: true, message: "Please Enter Your Password!" },
                ]}
              >
                <Input.Password
                  type="password"
                  placeholder="Password"
                  value={password}
                  onChange={(event) => setPassword(event.target.value)}
                  className={styles.userName}
                />
              </Form.Item>
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox
                  onChange={onChange}
                  checked={isRemeberLogin}
                  className={styles.checkboxLabel}
                >
                  Save for later use
                </Checkbox>
              </Form.Item>
              <Form.Item>
                <Button
                  type="primary"
                  block
                  htmlType="submit"
                  className={styles.buttonData}
                >
                  Submit
                </Button>
              </Form.Item>
            </Form>
            <div className={cx("ant-row my-5")}>
              <div className={styles.loginWithText}>Create new account? </div>
              <Link href={"/signUp"} passHref>
                <div className={cx("pl-1", styles.linkText)}>Signup</div>
              </Link>
            </div>
          </div>
          <div
            className={cx(
              "ant-col ant-col-sm-24 ant-col-md-8 ant-col-xl-12 mt-5 ",
              styles.loginWithSocialMain
            )}
          >
            {/* <div className={cx("ant-row mt-5")}>
              <div className={styles.loginWithText}>Login with </div>
              <span
                onClick={() => {
                  setIsOTPModalVisible(true), handleClose();
                }}
                className={cx("pl-1", styles.linkText)}
              >
                OTP
              </span>
            </div> */}
            <div className={cx("my-3", styles.socialLoginText)}>
              Continue with email or your social accounts
            </div>
            <div className={cx("ant-row my-2")}>
              <Button
                // onClick={signInwithFacebook}
                type="primary"
                ghost
                className={cx("mr-4", styles.buttonSize)}
              >
                Facebook
              </Button>
              <Button
                danger
                className={styles.buttonSize}
                // onClick={signInWithGoogle}
              >
                Google
              </Button>
            </div>
          </div>
        </div>
      </Modal>
      {/* <OTPModal
        handleOTPClose={() => {
          setIsOTPModalVisible(false);
        }}
        isOTPModalVisible={isOTPModalVisible}
      /> */}
    </>
  );
};
export default SingInModal;
