// File Path: src/pages/Anonymous/Login/LoginPageLegacy.jsx
// Enhanced Login Page with Modern UI/UX Features (No OAuth) - Desktop Fix
// Legacy version using UI components

import React, { useState, useEffect, useRef } from "react";
import { Link, useNavigate, useSearchParams } from "react-router";
import { useAuthManager } from "../../../services/Services";
import { getRoleRedirectPath } from "../../../constants/Roles";
import { Card, Input, Button, Alert, Checkbox } from "../../../components/UI";
import {
  EnvelopeIcon,
  LockClosedIcon,
  ArrowRightIcon,
  EyeIcon,
  EyeSlashIcon,
  ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";

function LoginPageLegacy() {
  const [searchParams] = useSearchParams();
  const isUnauthorized = searchParams.get("unauthorized");

  const authManager = useAuthManager();
  const navigate = useNavigate();
  const emailInputRef = useRef(null);

  const [formData, setFormData] = useState({
    email: "",
    password: "",
  });
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState({});
  const [rememberMe, setRememberMe] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [focusedField, setFocusedField] = useState(null);
  const [hasInitialized, setHasInitialized] = useState(false);

  // Split useEffect 1: Basic initialization
  useEffect(() => {
    if (hasInitialized) return;

    // Auto-focus email field on mount
    emailInputRef.current?.focus();

    // Smooth scroll to top
    window.scrollTo({ top: 0, behavior: "smooth" });

    // Note: We intentionally DON'T redirect already-authenticated users here
    // This prevents redirect loops when Safari auto-fills credentials
    // Users who are already logged in can navigate via browser back button

    // Check for remembered email
    const rememberedEmail = localStorage.getItem("rememberedEmail");
    if (rememberedEmail) {
      setFormData((prev) => ({ ...prev, email: rememberedEmail }));
      setRememberMe(true);
    }

    setHasInitialized(true);
  }, [hasInitialized, authManager, navigate]);

  // Split useEffect 2: Mobile optimizations (run once)
  useEffect(() => {
    if (!hasInitialized) return;

    // Simplified mobile optimizations - run only once
    const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
    const isAndroid = /Android/.test(navigator.userAgent);

    // Only set viewport if not already configured
    const viewport = document.querySelector('meta[name="viewport"]');
    if (!viewport) {
      const meta = document.createElement("meta");
      meta.name = "viewport";
      meta.content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no";
      document.head.appendChild(meta);
    }

    // Simplified iOS handling
    if (isIOS) {
      const handleResize = () => {
        document.documentElement.style.height = `${window.innerHeight}px`;
      };
      window.addEventListener("resize", handleResize);
      return () => window.removeEventListener("resize", handleResize);
    }

    // Simplified Android handling
    if (isAndroid && window.visualViewport) {
      const handleViewportChange = () => {
        document.documentElement.style.setProperty(
          "--android-vh",
          `${window.visualViewport.height * 0.01}px`,
        );
      };
      window.visualViewport.addEventListener("resize", handleViewportChange);
      handleViewportChange();
      return () => window.visualViewport.removeEventListener("resize", handleViewportChange);
    }
  }, [hasInitialized]);

  const handleFieldChange = (field, value) => {
    setFormData((prev) => ({
      ...prev,
      [field]: value,
    }));

    // Clear errors when user types
    if (errors[field]) {
      setErrors((prev) => ({
        ...prev,
        [field]: null,
      }));
    }
  };

  const validateForm = () => {
    const newErrors = {};

    if (!formData.email || !formData.email.trim()) {
      newErrors.email = "Email is required";
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = "Please enter a valid email address";
    }

    if (!formData.password || !formData.password.trim()) {
      newErrors.password = "Password is required";
    } else if (formData.password.length < 8) {
      newErrors.password = "Password must be at least 8 characters";
    }

    return newErrors;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    const validationErrors = validateForm();
    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
      // Focus on first error field
      const firstErrorField = Object.keys(validationErrors)[0];
      document.querySelector(`[name="${firstErrorField}"]`)?.focus();
      return;
    }

    setLoading(true);
    setErrors({});

    try {
      if (import.meta.env.DEV) {
        console.log("LoginPage: Attempting login");
      }

      // Handle remember me
      if (rememberMe) {
        localStorage.setItem("rememberedEmail", formData.email);
      } else {
        localStorage.removeItem("rememberedEmail");
      }

      const loginResponse = await authManager.login({
        email: formData.email.trim().toLowerCase(),
        password: formData.password,
      });

      if (import.meta.env.DEV) {
        console.log("LoginPage: Login successful");
      }

      // Clear form
      setFormData({ email: "", password: "" });

      // Handle redirect based on 2FA status
      if (loginResponse.user.otpEnabled === false) {
        const redirectUrl = getRoleRedirectPath(loginResponse.user.role);
        if (import.meta.env.DEV) {
          console.log(`LoginPage: Redirecting to ${redirectUrl}`);
        }
        navigate(redirectUrl);
      } else if (!loginResponse.user.otpVerified) {
        if (import.meta.env.DEV) {
          console.log("LoginPage: 2FA not verified, redirecting to setup");
        }
        navigate("/login/2fa/step-1");
      } else {
        if (import.meta.env.DEV) {
          console.log("LoginPage: 2FA enabled, redirecting to validation");
        }
        navigate("/login/2fa");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("LoginPage: Login failed", error);
      }
      setErrors({
        auth: error.message || "Invalid email or password. Please try again.",
      });

      // Shake animation on error
      const form = document.getElementById("login-form");
      form.classList.add("animate-shake");
      setTimeout(() => form.classList.remove("animate-shake"), 500);
    } finally {
      setLoading(false);
    }
  };

  // Handle Enter key submission
  const handleKeyDown = (e) => {
    if (e.key === "Enter" && !loading) {
      handleSubmit(e);
    }
  };

  // Simplified static CSS - removed massive dynamic injection
  const staticStyles = `
    .desktop-form-width { width: 100%; max-width: 24rem; }
    @media (min-width: 1920px) { .desktop-form-width { max-width: 28rem; } }
    .mobile-input-fix { font-size: 16px !important; -webkit-appearance: none; -webkit-tap-highlight-color: transparent; }
    .mobile-touch-target { min-height: 44px; min-width: 44px; }
    .android-viewport-fix { min-height: 100vh; min-height: calc(var(--android-vh, 1vh) * 100); }
    @media (prefers-reduced-motion: reduce) { .android-keyboard-adjust, .ios-keyboard-adjust { transition: none; } }
  `;

  return (
    <div>
      <style>{staticStyles}</style>

      <div className="min-h-screen relative overflow-hidden bg-gradient-to-br from-blue-50 via-white to-purple-50 android-viewport-fix">
        <div className="absolute inset-0 overflow-hidden pointer-events-none">
          <div className="absolute -top-20 -right-20 sm:-top-32 sm:-right-32 lg:-top-40 lg:-right-40 w-40 h-40 sm:w-60 sm:h-60 lg:w-80 lg:h-80 bg-purple-300 rounded-full filter blur-xl opacity-30 animate-blob"></div>
          <div className="absolute -bottom-20 -left-20 sm:-bottom-32 sm:-left-32 lg:-bottom-40 lg:-left-40 w-40 h-40 sm:w-60 sm:h-60 lg:w-80 lg:h-80 bg-blue-300 rounded-full filter blur-xl opacity-30 animate-blob animation-delay-2000"></div>
          <div className="absolute top-20 left-20 sm:top-32 sm:left-32 lg:top-40 lg:left-40 w-40 h-40 sm:w-60 sm:h-60 lg:w-80 lg:h-80 bg-pink-300 rounded-full filter blur-xl opacity-30 animate-blob animation-delay-4000"></div>
        </div>

        <div className="relative z-10 min-h-screen flex items-center justify-center p-4 sm:p-6 lg:p-8">
          <div className="w-full max-w-sm sm:max-w-md desktop-form-width">
            <div className="text-center mb-6 sm:mb-8 animate-fade-in">
              <div className="inline-flex items-center justify-center w-16 h-16 sm:w-20 sm:h-20 bg-white rounded-2xl shadow-lg">
                <img
                  src="/img/flashpointraining-logo.jpeg"
                  alt="Flashpoint Training"
                  className="w-12 h-12 sm:w-16 sm:h-16 object-contain"
                />
              </div>
            </div>

            <Card className="backdrop-blur-sm bg-white/95 shadow-2xl animate-slide-up p-6 sm:p-8">
              {isUnauthorized === "true" && (
                <Alert type="warning" dismissible className="mb-6">
                  <div>
                    <strong className="font-semibold">Session Expired</strong>
                    <p className="mt-1">Please sign in again to continue</p>
                  </div>
                </Alert>
              )}

              {errors.auth && (
                <Alert
                  type="error"
                  dismissible
                  onDismiss={() => setErrors({})}
                  className="mb-6"
                >
                  {errors.auth}
                </Alert>
              )}

              <form
                id="login-form"
                onSubmit={handleSubmit}
                className="space-y-5"
              >
                <div
                  className={`transition-all duration-200 ${focusedField === "email" ? "scale-[1.02]" : ""}`}
                >
                  <label htmlFor="email-input" className="block text-sm font-medium text-gray-700 mb-2">
                    Email Address
                    <span className="text-red-500 ml-1">*</span>
                  </label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <EnvelopeIcon
                        className={`h-5 w-5 transition-colors ${focusedField === "email" ? "text-blue-500" : "text-gray-400"}`}
                      />
                    </div>
                    <input
                      id="email-input"
                      ref={emailInputRef}
                      type="email"
                      name="email"
                      placeholder="you@example.com"
                      value={formData.email}
                      onChange={(e) =>
                        handleFieldChange("email", e.target.value)
                      }
                      onFocus={() => setFocusedField("email")}
                      onBlur={() => setFocusedField(null)}
                      onKeyDown={handleKeyDown}
                      disabled={loading}
                      required
                      autoComplete="email"
                      autoCapitalize="none"
                      autoCorrect="off"
                      spellCheck="false"
                      inputMode="email"
                      className={`
                        w-full pl-10 pr-4 py-3
                        text-base
                        border rounded-lg
                        transition-all duration-200
                        placeholder:text-gray-400
                        focus:outline-none focus:ring-2 focus:ring-offset-1
                        mobile-input-fix
                        ${
                          errors.email
                            ? "border-red-500 focus:border-red-500 focus:ring-red-500/20"
                            : "border-gray-300 focus:border-blue-500 focus:ring-blue-500/20"
                        }
                        ${loading ? "bg-gray-50 cursor-not-allowed opacity-60" : "bg-white"}
                      `}
                    />
                  </div>
                  {errors.email && (
                    <p className="mt-2 text-sm text-red-600 flex items-center animate-fade-in">
                      <ExclamationTriangleIcon className="h-4 w-4 mr-1 flex-shrink-0" />
                      {errors.email}
                    </p>
                  )}
                </div>

                <div
                  className={`transition-all duration-200 ${focusedField === "password" ? "scale-[1.02]" : ""}`}
                >
                  <label htmlFor="password-input" className="block text-sm font-medium text-gray-700 mb-2">
                    Password
                    <span className="text-red-500 ml-1">*</span>
                  </label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <LockClosedIcon
                        className={`h-5 w-5 transition-colors ${focusedField === "password" ? "text-blue-500" : "text-gray-400"}`}
                      />
                    </div>
                    <input
                      id="password-input"
                      type={showPassword ? "text" : "password"}
                      name="password"
                      placeholder="Enter your password"
                      value={formData.password}
                      onChange={(e) =>
                        handleFieldChange("password", e.target.value)
                      }
                      onFocus={() => setFocusedField("password")}
                      onBlur={() => setFocusedField(null)}
                      onKeyDown={handleKeyDown}
                      disabled={loading}
                      required
                      autoComplete="current-password"
                      autoCapitalize="none"
                      autoCorrect="off"
                      spellCheck="false"
                      className={`
                        w-full pl-10 pr-12 py-3
                        text-base
                        border rounded-lg
                        transition-all duration-200
                        placeholder:text-gray-400
                        focus:outline-none focus:ring-2 focus:ring-offset-1
                        mobile-input-fix
                        ${
                          errors.password
                            ? "border-red-500 focus:border-red-500 focus:ring-red-500/20"
                            : "border-gray-300 focus:border-blue-500 focus:ring-blue-500/20"
                        }
                        ${loading ? "bg-gray-50 cursor-not-allowed opacity-60" : "bg-white"}
                      `}
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute inset-y-0 right-0 pr-3 flex items-center touch-manipulation mobile-touch-target"
                      tabIndex={-1}
                    >
                      {showPassword ? (
                        <EyeSlashIcon className="h-5 w-5 text-gray-400 hover:text-gray-600" />
                      ) : (
                        <EyeIcon className="h-5 w-5 text-gray-400 hover:text-gray-600" />
                      )}
                    </button>
                  </div>
                  {errors.password && (
                    <p className="mt-2 text-sm text-red-600 flex items-center animate-fade-in">
                      <ExclamationTriangleIcon className="h-4 w-4 mr-1 flex-shrink-0" />
                      {errors.password}
                    </p>
                  )}
                </div>

                <div className="flex items-center justify-between">
                  <Checkbox
                    label="Remember me"
                    checked={rememberMe}
                    onChange={(e) => setRememberMe(e.target.checked)}
                    disabled={loading}
                    className="text-sm"
                  />

                  <Link
                    to="/forgot-password"
                    className="text-sm text-blue-600 hover:text-blue-700 hover:underline transition-colors touch-manipulation mobile-touch-target"
                  >
                    Forgot password?
                  </Link>
                </div>

                <Button
                  type="submit"
                  variant="primary"
                  fullWidth
                  disabled={loading}
                  loading={loading}
                  className="group py-3 text-base touch-manipulation mobile-touch-target desktop-button-fix"
                >
                  {!loading && (
                    <span className="inline-flex items-center justify-center gap-2">
                      <span>Sign In</span>
                      <ArrowRightIcon className="h-5 w-5 transition-transform group-hover:translate-x-1" />
                    </span>
                  )}
                  {loading && "Signing in..."}
                </Button>
              </form>

              <div className="mt-6 pt-6 border-t border-gray-200 text-center">
                <p className="text-sm text-gray-600">
                  Don't have an account?{" "}
                  <Link
                    to="/register"
                    className="font-medium text-blue-600 hover:text-blue-700 hover:underline transition-colors touch-manipulation mobile-touch-target"
                  >
                    Sign up for free
                  </Link>
                </p>
              </div>
            </Card>

            <div className="text-center mt-8 px-4">
              <p className="text-xs text-gray-500">
                © 2025 Flashpoint Training All rights reserved.
              </p>
              <div className="mt-2 space-x-4">
                <Link
                  to="/privacy"
                  className="text-xs text-gray-400 hover:text-gray-600 touch-manipulation mobile-touch-target"
                >
                  Privacy Policy
                </Link>
                <Link
                  to="/terms"
                  className="text-xs text-gray-400 hover:text-gray-600 touch-manipulation mobile-touch-target"
                >
                  Terms of Service
                </Link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default LoginPageLegacy;
