import { useMsal } from '@azure/msal-react';
import { loginRequest } from '../auth/authConfig';
import { useNavigate, useLocation } from 'react-router-dom';
import { useState, useEffect } from 'react';
import styles from './Login.module.css';
import agentDiagram from '../assets/Frame 43.png';
import logo from '../assets/LogoPowerOn.png';
import { useAuth, useMsalAuth } from '../hooks/useAuthentication';

function Login() {
  const { instance, accounts, inProgress } = useMsal();
  const navigate = useNavigate();
  const location = useLocation();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const { login, error: loginError, isLoading: isLoginLoading } = useAuth();
  const { loginWithMsal, error: msalError, isLoading: isMsalLoading } = useMsalAuth();
  
  // Get the page the user was trying to visit
  const from = location.state?.from?.pathname || "/";
  
  // Debug information about accounts
  useEffect(() => {
    if (accounts.length > 0) {
      console.log("MSAL accounts found:", accounts.map(acc => ({
        username: acc.username,
        name: acc.name,
        idTokenClaims: acc.idTokenClaims
      })));
    } else {
      console.log("No MSAL accounts found");
    }
  }, [accounts]);

  const handleMsalLogin = async () => {
    try {
      console.log("Attempting MSAL login...");
      const response = await loginWithMsal();
      console.log("MSAL login successful:", response);
      navigate(from, { replace: true });
    } catch (error) {
      console.error("MSAL login failed:", error);
    }
  };

  const handleCredentialLogin = async () => {
    try {
      await login(username, password);
      navigate(from, { replace: true });
    } catch (error) {
      console.error("Login failed:", error);
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.leftPanel}>
        <div className={styles.logo}>
          <img src={logo} alt="PowerOn Logo" />
        </div>
        <div className={styles.loginBox}>
          <h1 className={styles.title}>Sign In or Register Your Organisation</h1>
          
          <div className={styles.loginForm}>
            {(loginError || msalError) && (
              <div className={styles.error}>{loginError || msalError}</div>
            )}
            <input
              type="text"
              placeholder="Username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              className={styles.input}
            />
            <input
              type="password"
              placeholder="Password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className={styles.input}
            />
            <button 
              className={`${styles.button} ${styles.primaryButton}`}
              onClick={handleCredentialLogin}
              disabled={isLoginLoading}
            >
              {isLoginLoading ? "Signing in..." : "Sign In"}
            </button>

            <div className={styles.divider}>
              <span>or continue with</span>
            </div>

            <button 
              className={`${styles.button} ${styles.microsoftButton}`}
              onClick={handleMsalLogin}
              disabled={isMsalLoading || inProgress !== "none"}
            >
              {isMsalLoading ? "Signing in..." : "Sign in with Microsoft"}
            </button>

            <div className={styles.registerLink}>
              <span>Don't have an account?</span>
              <button 
                className={styles.textButton}
                onClick={() => navigate("/register")}
              >
                Register
              </button>
            </div>
          </div>
        </div>
      </div>
      <div className={styles.rightPanel}>
        <div className={styles.rightContent}>
          <img src={agentDiagram} alt="Agent Diagram" />
        </div>
      </div>
    </div>
  );
}

export default Login;