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

import React, { useState, useEffect, useRef, useCallback, useMemo } 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/UIX";
import { useUIXTheme } from "../../../components/UIX/themes/useUIXTheme";
import {
  EnvelopeIcon,
  LockClosedIcon,
  ArrowRightIcon,
  EyeIcon,
  EyeSlashIcon,
} from "@heroicons/react/24/outline";

// Static CSS - moved outside component to prevent recreation on every render
const STATIC_STYLES = `
  .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; } }
`;

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

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

  // UIX Theme support - defaults to blue theme
  const { getThemeClasses } = useUIXTheme();

  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 [hasInitialized, setHasInitialized] = useState(false);

  // Cleanup on unmount - prevents state updates after unmount
  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = 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]); // Removed unused authManager and navigate dependencies

  // 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]);

  // Memoized to prevent Input component re-renders
  const handleFieldChange = useCallback((field, value) => {
    setFormData((prev) => ({
      ...prev,
      [field]: value,
    }));

    // Clear errors when user types
    setErrors((prev) => {
      if (prev[field]) {
        return { ...prev, [field]: null };
      }
      return prev;
    });
  }, []); // No dependencies needed - uses functional setState

  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 = useCallback(async (e) => {
    e.preventDefault();

    // Prevent state updates if component is unmounted
    if (!isMountedRef.current) return;

    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 (!isMountedRef.current) return;

      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 (!isMountedRef.current) return;

      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 {
      if (isMountedRef.current) {
        setLoading(false);
      }
    }
  }, [formData, rememberMe, authManager, navigate, validateForm]);

  // Handle Enter key submission - memoized to prevent Input component re-renders
  const handleKeyDown = useCallback((e) => {
    if (e.key === "Enter" && !loading) {
      handleSubmit(e);
    }
  }, [loading, handleSubmit]); // Depends on loading state and handleSubmit

  // Memoized password toggle button - prevents Input re-renders
  const passwordSuffix = useMemo(() => (
    <button
      type="button"
      onClick={() => setShowPassword(!showPassword)}
      className="flex items-center touch-manipulation mobile-touch-target"
      tabIndex={-1}
    >
      {showPassword ? (
        <EyeSlashIcon className={`h-5 w-5 ${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-accent")}`} />
      ) : (
        <EyeIcon className={`h-5 w-5 ${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-accent")}`} />
      )}
    </button>
  ), [showPassword, getThemeClasses]); // Only recreate when showPassword or theme changes

  // Memoized theme classes - prevents re-calculation on every render
  const themeClasses = useMemo(() => ({
    backgroundGradient: getThemeClasses("bg-gradient-primary"),
    decorativeBlob1: getThemeClasses("decorative-blob-1"),
    decorativeBlob2: getThemeClasses("decorative-blob-2"),
    decorativeBlob3: getThemeClasses("decorative-blob-3"),
    linkPrimary: getThemeClasses("link-primary"),
    linkSecondary: getThemeClasses("link-secondary"),
  }), [getThemeClasses]);

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

      <div className={`min-h-screen relative overflow-hidden ${themeClasses.backgroundGradient} 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 ${themeClasses.decorativeBlob1} 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 ${themeClasses.decorativeBlob2} 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 ${themeClasses.decorativeBlob3} 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"
              >
                {/* Email Input - UIX Component */}
                <Input
                  ref={emailInputRef}
                  label="Email Address"
                  type="email"
                  name="email"
                  placeholder="you@example.com"
                  value={formData.email}
                  onChange={(value) => handleFieldChange("email", value)}
                  onKeyDown={handleKeyDown}
                  disabled={loading}
                  required
                  error={errors.email}
                  autoComplete="email"
                  autoCapitalize="none"
                  autoCorrect="off"
                  spellCheck="false"
                  inputMode="email"
                  icon={EnvelopeIcon}
                  className="mobile-input-fix"
                />

                {/* Password Input - UIX Component with custom toggle */}
                <div>
                  <Input
                    label="Password"
                    type={showPassword ? "text" : "password"}
                    name="password"
                    placeholder="Enter your password"
                    value={formData.password}
                    onChange={(value) => handleFieldChange("password", value)}
                    onKeyDown={handleKeyDown}
                    disabled={loading}
                    required
                    error={errors.password}
                    autoComplete="current-password"
                    autoCapitalize="none"
                    autoCorrect="off"
                    spellCheck="false"
                    icon={LockClosedIcon}
                    className="mobile-input-fix"
                    suffix={passwordSuffix}
                  />
                </div>

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

                  <Link
                    to="/forgot-password"
                    className={`text-sm ${themeClasses.linkPrimary} 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 ${getThemeClasses("border-muted")} text-center`}>
                <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                  Don't have an account?{" "}
                  <Link
                    to="/register"
                    className={`font-medium ${themeClasses.linkPrimary} 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 ${getThemeClasses("text-secondary")}`}>
                © 2025 Flashpoint Training All rights reserved.
              </p>
              <div className="mt-2 space-x-4">
                <Link
                  to="/privacy"
                  className={`text-xs ${themeClasses.linkSecondary} touch-manipulation mobile-touch-target`}
                >
                  Privacy Policy
                </Link>
                <Link
                  to="/terms"
                  className={`text-xs ${themeClasses.linkSecondary} touch-manipulation mobile-touch-target`}
                >
                  Terms of Service
                </Link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default LoginPageUIX;
