import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { GoogleLogin } from '@react-oauth/google'; // Import GoogleLogin component
import { getAuth, signInWithEmailAndPassword, signInWithPopup, GoogleAuthProvider } from 'firebase/auth'; // Firebase authentication methods
import './Page1.css';

// Firebase configuration
import { initializeApp } from 'firebase/app';
const firebaseConfig = {
    apiKey: "AIzaSyAFVUCBwz_YH7hq3J8pucRSa5elmzRfyCg",
    authDomain: "bos-app-4de46.firebaseapp.com",
    projectId: "bos-app-4de46",
    storageBucket: "bos-app-4de46.firebasestorage.app",
    messagingSenderId: "73474147810",
    appId: "1:73474147810:web:c9881eabf41b26d901e5bb",
    measurementId: "G-RW4J2ZB06P"
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app); // Firebase Auth instance

const Page1 = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [rememberMe, setRememberMe] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [isForgotPasswordVisible, setIsForgotPasswordVisible] = useState(false);
  const [resetEmail, setResetEmail] = useState('');
  const navigate = useNavigate();

  // Allowed credentials
  const allowedCredentials = [
    { email: "hodcomp@somaiya.edu", password: "hodcomp123!" },
    { email: "director.kjsse@somaiya.edu", password: "directorkjsse2024" },
    { email: "dean.engg@somaiya.edu", password: "deanengg2024" },
    { email: "hodextc@somaiya.edu", password: "hodextc2024" },
    { email: "hodetrx@somaiya.edu", password: "hodetrx2024" },
    { email: "hodit.engg@somaiya.edu", password: "hodit2024" },
    { email: "hodmech@somaiya.edu", password: "hodmech2024" },
    { email: "aaryaman.s@somaiya.edu", password: "aaryaman2024" },
    { email: "mansi.zala@somaiya.edu", password: "mansi2024" },
    { email: "deputydirector.kjsse@somaiya.edu", password: "deputydirector2024" },
    { email: "deanap@somaiya.edu", password: "deanap2024" },
  ];

  // Handle normal login (email/password)
  const handleLogin = (event) => {
    event.preventDefault();

    // Check if credentials match allowed credentials
    const validCredential = allowedCredentials.find(
      (credential) => credential.email === email && credential.password === password
    );

    if (validCredential) {
      alert("Login Successful!");

      if (rememberMe) {
        localStorage.setItem("rememberedEmail", email);
      } else {
        localStorage.removeItem("rememberedEmail");
      }

      setTimeout(() => {
        navigate('/page2');
      }, 1000);
    } else {
      // Firebase login logic if the credentials are not in allowed credentials
      signInWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
          const user = userCredential.user;
          alert("Firebase Login Successful!");

          if (rememberMe) {
            localStorage.setItem("rememberedEmail", email);
          } else {
            localStorage.removeItem("rememberedEmail");
          }

          setTimeout(() => {
            navigate('/page2');
          }, 1000);
        })
        .catch((error) => {
          setErrorMessage("Invalid email or password. Please check your credentials.");
        });
    }
  };

  // Handle password reset
  const handleResetPassword = (event) => {
    event.preventDefault();
    alert(`A password reset link has been sent to ${resetEmail}.`);
    setIsForgotPasswordVisible(false);
  };

  // Google login success handler
  const handleGoogleLoginSuccess = (response) => {
    const provider = new GoogleAuthProvider();
    signInWithPopup(auth, provider)
      .then((result) => {
        console.log("Google login success:", result);
        alert("Google Login Successful!");
        navigate('/page2');
      })
      .catch((error) => {
        console.error("Google login error:", error);
        alert("Google Login Failed. Please try again.");
      });
  };

  // Google login failure handler
  const handleGoogleLoginFailure = (error) => {
    console.error("Google login error:", error);
    alert("Google Login Failed. Please try again.");
  };

  return (
    <div className="wrapper">
      <form id="login-form" onSubmit={handleLogin}>
        <img src="../src/image.png" alt="Responsive" className="responsive-image" />
        <h2>Board Of Studies</h2>

        <div className="input-box">
          <input
            type="email"
            id="email"
            className="form-control"
            placeholder="Enter Somaiya email ID"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
          <i className="fas fa-user icon"></i>
        </div>

        <div className="input-box">
          <input
            type="password"
            id="password"
            className="form-control"
            placeholder="Enter Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />
          <i className="fas fa-lock icon"></i>
        </div>

        {errorMessage && <p id="error-message" style={{ color: 'red' }}>{errorMessage}</p>}

        <div className="remember-forget">
          <label>
            <input
              type="checkbox"
              id="remember-me"
              checked={rememberMe}
              onChange={() => setRememberMe(!rememberMe)}
            /> Remember me
          </label>
          <a href="#forgot-password" onClick={(e) => { e.preventDefault(); setIsForgotPasswordVisible(true); }}>
            <pre>Forgot password?</pre>
          </a>
        </div>

        <input className="btn btn-outline-danger" type="submit" value="Login" />
      </form>

      {/* Forgot Password Form */}
      {isForgotPasswordVisible && (
        <div id="forgot-password-form" className="forgot-password-form">
          <h3>Reset Your Password</h3>
          <form id="reset-password-form" onSubmit={handleResetPassword}>
            <input
              type="email"
              id="reset-email"
              placeholder="Enter your registered email"
              value={resetEmail}
              onChange={(e) => setResetEmail(e.target.value)}
              required
            />
            <button type="submit">Send Reset Link</button>
          </form>
          <button id="cancel-reset-password" onClick={() => setIsForgotPasswordVisible(false)}>Cancel</button>
        </div>
      )}

      {/* Google Login Button */}
      <div className="google-login">
        <GoogleLogin
          onSuccess={handleGoogleLoginSuccess}
          onError={handleGoogleLoginFailure}
          useOneTap
          clientId="YOUR_GOOGLE_CLIENT_ID" // Replace with your Firebase client ID
        />
      </div>
    </div>
  );
};

export default Page1;
