import React, { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { Loader2, AlertCircle } from "lucide-react";
import loginHero from "../../assets/login-hero.png";
import logo from "../../assets/logo.png";
import { Label } from "@radix-ui/react-label";
import { Input } from "../../common/components/ui/input";
import { Button } from "../../common/components/ui/button";
import { loginUser } from "../auth/authSlice";
import { getDashboardPath } from "../../services/firestoreService";
import type { RootState, AppDispatch } from "../../store/store";

/**
 * Login Page Component.
 * Features a modern split-screen layout with an inspirational hero image.
 * Handles user authentication via email/password with client-side validation.
 * Uses Redux for state management and handles role-based redirection.
 */

type LocationState = {
  from?: {
    pathname: string;
  };
  message?: string;
};

const Login: React.FC = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [emailError, setEmailError] = useState("");
  const [passwordError, setPasswordError] = useState("");
  const [sessionMessage, setSessionMessage] = useState<string | null>(null);
  const navigate = useNavigate();
  const location = useLocation();
  const dispatch = useDispatch<AppDispatch>();
  const { status, error: reduxError, user, isAuthenticated } = useSelector((state: RootState) => state.auth);

  // Validate email format
  const validateEmail = (value: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(value);
  };

  // Validate password length
  const validatePassword = (value: string): boolean => {
    return value.length >= 8;
  };

  // Validate entire form
  const validateForm = (emailValue: string, passwordValue: string): boolean => {
    return validateEmail(emailValue) && validatePassword(passwordValue);
  };

  const isFormValid = validateForm(email, password);

  // Handle email input change
  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setEmail(value);

    if (value.trim() && !validateEmail(value)) {
      setEmailError("Please enter a valid email address");
    } else {
      setEmailError("");
    }
  };

  // Handle password input change
  const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setPassword(value);

    if (value && !validatePassword(value)) {
      setPasswordError("Password must be at least 8 characters");
    } else {
      setPasswordError("");
    }
  };

  // Navigate user after successful login
  useEffect(() => {
    if (!isAuthenticated || !user?.userRole) return;

    const state = location.state as LocationState | null;
    const from = state?.from?.pathname;
    const dashboardPath = getDashboardPath(user.userRole);

    navigate(from ?? dashboardPath, { replace: true });
  }, [isAuthenticated, user?.userRole, navigate, location.state]);

  // Check for session expiration message from redirect
  useEffect(() => {
    const state = location.state as LocationState | null;
    if (state?.message) {
      // Auto-clear session message after 5 seconds
      const timer = setTimeout(() => setSessionMessage(null), 5000);
      // Use a microtask to avoid cascading renders
      Promise.resolve().then(() => setSessionMessage(state.message || null));
      return () => clearTimeout(timer);
    }
  }, [location.state]);

  // Clear error message when component unmounts
  useEffect(() => {
    return () => {
      // Error will be cleared from Redux state when user navigates away
    };
  }, []);

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

    // Validate before submission
    if (!isFormValid) {
      if (!validateEmail(email)) {
        setEmailError("Please enter a valid email address");
      }
      if (!validatePassword(password)) {
        setPasswordError("Password must be at least 8 characters");
      }
      return;
    }

    // Dispatch Redux action to handle login
    dispatch(loginUser({ email, password }));
  };
  return (
    <div className="flex min-h-screen bg-slate-50/50">
      {/* Left Side: Hero Image (Hidden on Mobile) */}
      <div className="hidden lg:flex lg:w-3/5 xl:w-[65%] relative overflow-hidden">
        <img
          src={loginHero}
          alt="Modern workspace"
          className="absolute inset-0 w-full h-full object-cover transform scale-105 hover:scale-100 transition-transform duration-10000 ease-in-out"
        />
        {/* Cinematic Overlay */}
        <div className="absolute inset-0 bg-linear-to-r from-black/60 via-black/20 to-transparent z-10" />
        <div className="absolute inset-0 bg-primary/10 backdrop-blur-[2px] z-0" />

        {/* Top Left Logo */}
        <div className="absolute top-12 left-12 z-20">
          <img
            src={logo}
            alt="Krow Logo"
            className="h-10 w-auto brightness-0 invert"
          />
        </div>

        <div className="absolute bottom-12 left-12 right-12 text-white z-10">
          <h1 className="text-5xl font-bold mb-4 tracking-tight leading-tight">
            Streamline your workforce <br /> with{" "}
            <span className="text-secondary underline decoration-4 underline-offset-8">
              KROW
            </span>
          </h1>
          <p className="text-lg text-slate-100/90 max-w-lg leading-relaxed">
            The all-in-one platform for managing staff, orders, and professional
            relationships with precision and ease.
          </p>
        </div>
      </div>

      {/* Right Side: Login Form */}
      <div className="w-full lg:w-2/5 xl:w-[35%] flex flex-col justify-center items-center p-8 sm:p-12 md:p-16 lg:p-20 bg-white border-l border-slate-200 z-10">
        <div className="w-full max-w-md space-y-8">
          {/* Logo / Branding */}
          <div className="flex flex-col items-center lg:items-start space-y-4">
            <img
              src={logo}
              alt="Krow Logo"
              className="h-10 w-auto lg:hidden mb-2"
            />
            <div className="space-y-1">
              <h2 className="text-3xl font-bold tracking-tight text-primary-text">
                Welcome Back
              </h2>
              <p className="text-secondary-text font-medium">
                Please enter your details to sign in
              </p>
            </div>
          </div>

          <form onSubmit={handleSubmit} className="space-y-6">
            {sessionMessage && (
              <div className="flex items-center p-4 text-sm text-blue-700 bg-blue-50 border border-blue-200 rounded-xl transition-all animate-in fade-in slide-in-from-top-2">
                <AlertCircle className="w-4 h-4 mr-2 shrink-0" />
                <span>{sessionMessage}</span>
              </div>
            )}

            {reduxError && (
              <div className="flex items-center p-4 text-sm text-destructive-foreground bg-destructive/70 border border-destructive/20 rounded-xl transition-all animate-in fade-in slide-in-from-top-2">
                <AlertCircle className="w-4 h-4 mr-2 shrink-0" />
                <span>{reduxError}</span>
              </div>
            )}

            <div className="space-y-2">
              <Label htmlFor="email" className="text-sm font-semibold">
                Work Email
              </Label>
              <Input
                id="email"
                type="email"
                placeholder="name@company.com"
                value={email}
                onChange={handleEmailChange}
                disabled={status === "loading"}
                required
                aria-describedby={emailError ? "email-error" : undefined}
                className={
                  emailError
                    ? "border-destructive focus-visible:ring-destructive"
                    : ""
                }
              />
              {emailError && (
                <p
                  id="email-error"
                  className="text-xs text-destructive font-medium"
                >
                  {emailError}
                </p>
              )}
            </div>

            <div className="space-y-2">
              <div className="flex items-center justify-between mb-1">
                <Label htmlFor="password" className="text-sm font-semibold">
                  Password
                </Label>
                <button
                  type="button"
                  onClick={() => navigate("/forgot-password")}
                  className="text-xs font-semibold text-primary hover:underline underline-offset-2"
                >
                  Forgot password?
                </button>
              </div>
              <Input
                id="password"
                type="password"
                placeholder="••••••••"
                value={password}
                onChange={handlePasswordChange}
                disabled={status === "loading"}
                required
                aria-describedby={passwordError ? "password-error" : undefined}
                className={
                  passwordError
                    ? "border-destructive focus-visible:ring-destructive"
                    : ""
                }
              />
              {passwordError && (
                <p
                  id="password-error"
                  className="text-xs text-destructive font-medium"
                >
                  {passwordError}
                </p>
              )}
            </div>

            <Button
              type="submit"
              className="w-full"
              disabled={status === "loading" || !isFormValid}
              size="default"
            >
              {status === "loading" ? (
                <>
                  <Loader2 className="w-5 h-5 mr-3 animate-spin" />
                  Authenticating...
                </>
              ) : (
                "Sign In to Workspace"
              )}
            </Button>
          </form>
        </div>
      </div>
    </div>
  );
};

export default Login;
