import { useState, useEffect } from "react";
import { login, saveToken } from "../authApi";
import ForgotPassword from "./ForgotPassword";

function Login({ onSuccess, onSwitchToRegister }) {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [showForgotPassword, setShowForgotPassword] = useState(false);

  // Check for token in URL (from Google OAuth redirect)
  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const token = urlParams.get('token');
    if (token) {
      saveToken(token);
      // Clean URL
      window.history.replaceState({}, document.title, window.location.pathname);
      onSuccess();
    }
  }, [onSuccess]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");
    setLoading(true);

    try {
      const data = await login(username, password);
      saveToken(data.access_token);
      onSuccess();
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleGoogleLogin = () => {
    const apiBase = window.__ENV__?.API_BASE || "http://localhost:8000";
    window.location.href = `${apiBase}/auth/google/login`;
  };

  const handleAzureLogin = () => {
    const apiBase = window.__ENV__?.API_BASE || "http://localhost:8000";
    window.location.href = `${apiBase}/auth/azure/login`;
  };

  if (showForgotPassword) {
    return <ForgotPassword onBack={() => setShowForgotPassword(false)} />;
  }

  return (
    <div className="auth-container">
      <div className="auth-card">
        <h1 className="auth-title">התחברות</h1>
        <p className="auth-subtitle">ברוכים השבים למתכונים שלכם</p>

        <form onSubmit={handleSubmit} className="auth-form">
          {error && <div className="error-banner">{error}</div>}

          <div className="field">
            <label>שם משתמש</label>
            <input
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
              placeholder="הזן שם משתמש"
              autoComplete="username"
            />
          </div>

          <div className="field">
            <label>סיסמה</label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              placeholder="הזן סיסמה"
              autoComplete="current-password"
            />
          </div>

          <button type="submit" className="btn primary full-width" disabled={loading}>
            {loading ? "מתחבר..." : "התחבר"}
          </button>

          <div style={{ textAlign: "center", marginTop: "0.75rem" }}>
            <button 
              type="button"
              className="link-btn" 
              style={{ fontSize: "0.875rem", color: "var(--text-muted)" }}
              onClick={() => setShowForgotPassword(true)}
            >
              שכחת סיסמה?
            </button>
          </div>
        </form>

        <div style={{ 
          margin: "1rem 0", 
          textAlign: "center", 
          color: "var(--text-muted)",
          position: "relative"
        }}>
          <div style={{
            position: "absolute",
            top: "50%",
            left: 0,
            right: 0,
            borderTop: "1px solid var(--border-subtle)",
            zIndex: 0
          }}></div>
          <span style={{
            background: "var(--card)",
            padding: "0 1rem",
            position: "relative",
            zIndex: 1
          }}>או</span>
        </div>

        <button 
          type="button"
          onClick={handleGoogleLogin}
          className="btn ghost full-width"
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            gap: "0.5rem",
            border: "1px solid var(--border-subtle)"
          }}
        >
          <svg width="18" height="18" viewBox="0 0 18 18">
            <path fill="#4285F4" d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.874 2.684-6.615z"/>
            <path fill="#34A853" d="M9 18c2.43 0 4.467-.806 5.956-2.184l-2.908-2.258c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332C2.438 15.983 5.482 18 9 18z"/>
            <path fill="#FBBC05" d="M3.964 10.707c-.18-.54-.282-1.117-.282-1.707 0-.593.102-1.17.282-1.709V4.958H.957C.347 6.173 0 7.548 0 9c0 1.452.348 2.827.957 4.042l3.007-2.335z"/>
            <path fill="#EA4335" d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0 5.482 0 2.438 2.017.957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z"/>
          </svg>
          המשך עם Google
        </button>

        {/* <button 
          type="button"
          onClick={handleAzureLogin}
          className="btn ghost full-width"
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            gap: "0.5rem",
            border: "1px solid var(--border-subtle)",
            marginTop: "0.5rem"
          }}
        >
          <svg width="18" height="18" viewBox="0 0 23 23">
            <path fill="#f25022" d="M1 1h10v10H1z"/>
            <path fill="#00a4ef" d="M12 1h10v10H12z"/>
            <path fill="#7fba00" d="M1 12h10v10H1z"/>
            <path fill="#ffb900" d="M12 12h10v10H12z"/>
          </svg>
          המשך עם Microsoft
        </button> */}

        <div className="auth-footer">
          <p>
            עדיין אין לך חשבון?{" "}
            <button className="link-btn" onClick={onSwitchToRegister}>
              הירשם עכשיו
            </button>
          </p>
        </div>
      </div>
    </div>
  );
}

export default Login;
