import React, { useEffect, useState } from "react";
import { Container, Col, Row } from "react-bootstrap";
import { FcGoogle } from "react-icons/fc";
import { FaEye, FaEyeSlash } from "react-icons/fa";
import axios from "axios";
import md5 from "md5";

import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

function AuthPage() {
  const [formData, setFormData] = useState({
    username: "",
    email: "",
    password: "",
  });
  const [signin, setSignin] = useState(false);

  const notifyError = (message) => {
    toast.error(message);
  };

  function ToggleSign(event) {
    event.preventDefault();
    setSignin(!signin);
    setFormData({
      username: "",
      email: "",
      password: "",
    });
  }

  function handleInputChange(event) {
    const { name, value } = event.target;
    setFormData((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  }

  async function handleSubmit(event) {
    event.preventDefault();
    // check if username is there
    if (!formData.username.trim() && signin) {
      notifyError("Username cannot be empty");
      return;
    }

    // check email format
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!emailRegex.test(formData.email)) {
      notifyError("Enter a valid email address");
      return;
    }

    // restrict to somaiya emails
    if (formData.email.endsWith("@somaiya.edu") === false) {
      notifyError("Only @somaiya.edu emails are allowed");
      return;
    }

    // password validation
    if (formData.password.length < 8) {
      notifyError("Password must be at least 8 characters long");
      return;
    }
    try {
      const response = await axios.post(
        `http://localhost:8080/api/${!signin ? "login" : "register"}`,
        formData,
        { withCredentials: true }
      );

      if (response.status === 200) {
        const { user } = response.data;
        delete user.password;
        const gravatarUrl = `https://www.gravatar.com/avatar/${md5(
          user.email
        )}?d=identicon`;
        user.profilePicture = gravatarUrl;

        localStorage.setItem("user", JSON.stringify(user));

        window.location.href = "/Welcome";
      }
    } catch (error) {
      console.error("Authentication error:", error);
      notifyError(error.response?.data.message || "An error occurred");
    }
  }

  const handleGoogleLogin = (event) => {
    event.preventDefault();
    window.location.href = "http://localhost:8080/auth/google";
  };

  return (
    <>
      {/* <ToastContainer /> */}
      <div className="LoginPage">
        <Container className={`LoginPageContainer ${signin ? "active" : ""}`}>
          <Row>
            <Col xs={12} md={6}>
              <div className="form-container sign-up">
                <SignUpForm
                  formData={formData}
                  handleInputChange={handleInputChange}
                  handleGoogleLogin={handleGoogleLogin}
                  handleSubmit={handleSubmit}
                />
              </div>
              <div className="form-container sign-in">
                <SignInForm
                  formData={formData}
                  handleInputChange={handleInputChange}
                  handleGoogleLogin={handleGoogleLogin}
                  handleSubmit={handleSubmit}
                />
              </div>
            </Col>
            <Col md={6}>
              <TogglerContainer signin={signin} ToggleSign={ToggleSign} />
            </Col>
          </Row>
          <Row>
            <div className="OverlayAnimation">
              {signin ? (
                <div className="togglebtnlogin">
                  <button className="hidden" onClick={ToggleSign}>
                    Sign In
                  </button>
                  <span>Already Have an Account?</span>
                </div>
              ) : (
                <div className="togglebtnlogin">
                  <span>Don't have an account? Create one</span>
                  <button className="hidden" onClick={ToggleSign}>
                    Sign Up
                  </button>
                </div>
              )}
            </div>
          </Row>
        </Container>
      </div>
    </>
  );
}

function TogglerContainer(props) {
  return (
    <>
      <div className="toggle-container">
        <div className="toggle">
          <div className="toggle-panel toggle-left">
            <h1>Welcome to Appointment to Examiner</h1>
            <p>Already Have an Account?</p>
            <button className="hidden" onClick={props.ToggleSign}>
              Sign In
            </button>
          </div>
          <div className="toggle-panel toggle-right">
            <h1>Welcome to Appointment to Examiner</h1>
            <p>Don't have an account? Create one</p>
            <button className="hidden" onClick={props.ToggleSign}>
              Sign Up
            </button>
          </div>
        </div>
      </div>
    </>
  );
}

function SignUpForm(props) {
  const [showPassword, setShowPassword] = useState(false);
  return (
    <>
      <form onSubmit={props.handleSubmit}>
        <h1>Create Account</h1>
        <div className="Googlediv">
          <button
            type="button"
            className="GoogleBtn"
            onClick={props.handleGoogleLogin}
          >
            <FcGoogle className="icon" /> Sign up with Google
          </button>
        </div>
        <span>or use your email for registration</span>
        <input
          type="text"
          name="username"
          value={props.formData.username}
          onChange={props.handleInputChange}
          placeholder="Name"
          required
        />
        <input
          type="email"
          name="email"
          value={props.formData.email}
          onChange={props.handleInputChange}
          placeholder="Email"
          required
        />
        <div style={{ position: "relative", width: "100%" }}>
          <input
            type={showPassword ? "text" : "password"}
            name="password"
            value={props.formData.password}
            onChange={props.handleInputChange}
            placeholder="Password"
            required
            style={{ paddingRight: "40px" }}
          />
          <span
            onClick={() => setShowPassword(!showPassword)}
            style={{
              position: "absolute",
              right: "10px",
              top: "50%",
              transform: "translateY(-50%)",
              cursor: "pointer",
              color: "#666",
            }}
          >
            {showPassword ? <FaEyeSlash /> : <FaEye />}
          </span>
        </div>
        <button type="submit">Sign Up</button>
      </form>
    </>
  );
}

function SignInForm(props) {
  const [showPassword, setShowPassword] = useState(false);
  return (
    <>
      <form onSubmit={props.handleSubmit}>
        <h1>Sign In</h1>
        <div>
          <button
            type="button"
            className="GoogleBtn"
            onClick={props.handleGoogleLogin}
          >
            <FcGoogle className="icon" /> Sign in with Google
          </button>
        </div>
        <span>or use your email password</span>
        <input
          type="email"
          name="email"
          value={props.formData.email}
          onChange={props.handleInputChange}
          placeholder="Email"
          required
        />
        <div style={{ position: "relative", width: "100%" }}>
          <input
            type={showPassword ? "text" : "password"}
            name="password"
            value={props.formData.password}
            onChange={props.handleInputChange}
            placeholder="Password"
            required
            style={{ paddingRight: "40px" }}
          />
          <span
            onClick={() => setShowPassword(!showPassword)}
            style={{
              position: "absolute",
              right: "10px",
              top: "50%",
              transform: "translateY(-50%)",
              cursor: "pointer",
              color: "#666",
            }}
          >
            {showPassword ? <FaEyeSlash /> : <FaEye />}
          </span>
        </div>
        <a href="/ForgetPw">Forget Your Password?</a>
        <button type="submit">Sign In</button>
      </form>
    </>
  );
}

export default AuthPage;
