import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import "./login.css";
import eflLogo from "../assets/EFL.png";
import efdLogo from "../assets/EFD.png";
import { useEffect } from "react";
import { buildApiUrl, API_ENDPOINTS } from "../utils/config";

const Login = () => {
  const [formData, setFormData] = useState({
    username: "",
    password: "",
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const navigate = useNavigate();

  // Check if user is already logged in
  useEffect(() => {
    const user = localStorage.getItem("user");
    if (user) {
      try {
        const userData = JSON.parse(user);
        if (userData && userData.user_id) {
          // User is already authenticated, redirect to dashboard
          navigate("/dashboard", { replace: true });
        }
      } catch (error) {
        console.error("Error parsing user data:", error);
        // Clear invalid user data
        localStorage.removeItem("user");
      }
    }

    // Clean up any stored route information when component mounts
    const keysToRemove = [];
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (
        key &&
        (key.startsWith("formData_") || key.startsWith("activeSection"))
      ) {
        keysToRemove.push(key);
      }
    }
    keysToRemove.forEach((key) => localStorage.removeItem(key));

    return () => {
      // Cleanup function - clear any form data that might have been set during this session
      const sessionKeysToRemove = [];
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (
          key &&
          (key.startsWith("formData_") || key.startsWith("activeSection"))
        ) {
          sessionKeysToRemove.push(key);
        }
      }
      sessionKeysToRemove.forEach((key) => localStorage.removeItem(key));
    };
  }, [navigate]);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
    // Clear error when user starts typing
    if (error) setError("");
  };

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

    try {
      const response = await fetch(buildApiUrl(API_ENDPOINTS.LOGIN), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(formData),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Login failed");
      }

      // Login successful
      setSuccess("Login successful!");
      console.log("Login successful:", data.user);

      // Store user data in localStorage
      localStorage.setItem("user", JSON.stringify(data.user));

      // Clear any previous route information to ensure user always starts at dashboard
      const keysToRemove = [];
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (
          key &&
          (key.startsWith("formData_") || key.startsWith("activeSection"))
        ) {
          keysToRemove.push(key);
        }
      }
      keysToRemove.forEach((key) => localStorage.removeItem(key));

      // Always redirect to dashboard with replace to prevent back navigation
      setTimeout(() => {
        navigate("/dashboard", { replace: true });
      }, 800); // short delay for user to see success
    } catch (err) {
      setError(err.message || "An error occurred during login");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen w-full bg-gray-900">
      {/* Left Container - Responsive Login Form */}
      <div className="left-container w-full lg:w-[30%] flex items-center justify-center px-4 py-8 sm:px-6 lg:px-8">
        <div className="w-full max-w-sm sm:max-w-md p-6 sm:p-8 rounded-lg shadow-lg bg-gray-100 dark:bg-slate-800">
          {/* Logo */}
          <div className="flex justify-center mb-4 sm:mb-6">
            {/* Light mode logo */}
            <img
              src={eflLogo}
              alt="Kartavya Logo Light"
              className="w-16 h-16 sm:w-20 sm:h-20 object-contain block dark:hidden"
            />
            {/* Dark mode logo */}
            <img
              src={efdLogo}
              alt="Kartavya Logo Dark"
              className="w-16 h-16 sm:w-20 sm:h-20 object-contain hidden dark:block"
            />
          </div>

          {/* Heading */}
          <div className="mb-6 text-center">
            <div className="text-xl sm:text-2xl lg:text-3xl font-bold text-gray-800 dark:text-white">
              User Login
            </div>
          </div>

          {/* Fixed height container for messages */}
          <div className="h-12 mb-4">
            {error && (
              <div className="p-2 sm:p-3 bg-red-100 border border-red-400 text-red-700 text-xs sm:text-sm rounded">
                {error}
              </div>
            )}
            {success && (
              <div className="p-2 sm:p-3 bg-green-100 border border-green-400 text-green-700 text-xs sm:text-sm rounded">
                {success}
              </div>
            )}
          </div>

          {/* Login Form */}
          <form className="space-y-6 sm:space-y-8" onSubmit={handleSubmit}>
            <div>
              <input
                type="text"
                name="username"
                placeholder="Email or Username"
                value={formData.username}
                onChange={handleInputChange}
                className="w-full border-b-2 border-gray-300 dark:border-gray-200 focus:border-orange-500 dark:focus:border-orange-400 focus:outline-none py-2 sm:py-3 bg-transparent text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 text-sm sm:text-base"
                required
                disabled={loading}
              />
            </div>
            <div>
              <input
                type="password"
                name="password"
                placeholder="Password"
                value={formData.password}
                onChange={handleInputChange}
                className="w-full border-b-2 border-gray-300 dark:border-gray-200 focus:border-orange-500 dark:focus:border-orange-400 focus:outline-none py-2 sm:py-3 bg-transparent text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 text-sm sm:text-base"
                required
                disabled={loading}
              />
            </div>
            <div className="pt-4">
              <button
                type="submit"
                disabled={loading}
                className={`w-full py-3 sm:py-4 rounded-lg transition-all duration-300 text-sm sm:text-base font-medium ${
                  loading
                    ? "bg-gray-400 cursor-not-allowed"
                    : "bg-orange-500 hover:bg-orange-600 dark:bg-orange-500 dark:hover:bg-transparent dark:hover:ring-2 dark:hover:ring-white active:scale-95"
                } text-white`}
              >
                {loading ? "Logging in..." : "Login"}
              </button>
            </div>
          </form>
        </div>
      </div>

      {/* Right Container - Hidden on mobile, visible on large screens */}
      <div className="right-container hidden lg:flex w-[70%] h-screen relative items-center justify-center">
        {/* Welcome text positioned at the center */}
        <div className="text-center z-10">
          <h1 className="text-3xl xl:text-4xl font-bold text-white mb-4">
            Welcome to Kartavya
          </h1>
          <p className="text-lg xl:text-xl text-gray-300">Management Portal</p>
        </div>
      </div>
    </div>
  );
};

export default Login;
