"use client";

import React, { useState, useEffect } from "react";
import { useAuth } from "../../../contexts/AuthContext";
import Link from "next/link";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { FiEyeOff, FiEye } from "react-icons/fi";
import { getDefaultRouteForRoles } from "@/config/routePermissions";

export default function LoginPage() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const { user, isLoading: authLoading, login } = useAuth();
  const router = useRouter();

  // Redirect if already logged in
  useEffect(() => {
    if (user && !authLoading) {
      const userRoles = user.roles?.map((role) => role.key) || [];
      const defaultRoute = getDefaultRouteForRoles(userRoles);
      router.push(defaultRoute);
    }
  }, [user, authLoading, router]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setIsLoading(true);

    try {
      await login(email, password);
      // After successful login, the useEffect will handle redirection
      // based on the user's roles via getDefaultRouteForRoles
    } catch (err) {
      console.error("Login error:", err);
      setError("Invalid email or password. Please try again.");
    } finally {
      setIsLoading(false);
    }
  };

  // Show loading state when checking authentication
  if (authLoading) {
    return (
      <div className="flex justify-center items-center h-screen">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mr-3"></div>
        <span>Loading...</span>
      </div>
    );
  }

  // If already logged in, don't render the login form (handled by useEffect)
  if (user) {
    return null;
  }

  return (
    <div className="min-h-screen flex flex-col md:flex-row font-nunito">
      {/* Left Panel */}
      <div
        className="flex-1 relative flex flex-col justify-between items-center overflow-hidden 
                  bg-primary-dark bg-[url('/water-texture.jpg')] bg-cover bg-center bg-blend-multiply 
                  left-panel-with-radial-glows px-4 sm:px-8 pt-[10vh] pb-[10vh] md:pt-[120px] md:pb-[120px] lg:pt-[160px] lg:pb-[160px]"
      >
        {/* Logo Container */}
        <div className="relative z-[3] w-[30vw] sm:w-[25vw] md:w-[20vw] min-w-[150px] max-w-[438px]">
          <Image
            src="/sa-logo.png"
            alt="Spring Aqua Logo"
            width={0}
            height={0}
            sizes="(max-width: 768px) 30vw, (max-width: 1024px) 25vw, 20vw"
            className="w-full h-auto object-contain"
          />
        </div>

        {/* Tagline Container */}
        <div className="relative z-[3] text-center max-w-[600px]">
          <h2 className="text-xl sm:text-2xl md:text-[25px] font-bold text-white leading-normal">
            From Filtration to Fulfillment – <br></br>Smarter with ERP!
          </h2>
        </div>
      </div>

      {/* Right Panel */}
      <div className="flex-1 bg-gradient-to-l from-white to-secondary-light flex items-center justify-center p-4 sm:p-6 md:p-8">
        <div className="w-full max-w-xl bg-white rounded-lg shadow-[0px_4px_34px_rgba(0,59,113,0.16)] p-6 sm:p-8 lg:p-[50px]">
          <h1 className="text-xl sm:text-2xl md:text-[24px] font-bold mb-6 md:mb-[32px] text-center text-primary-dark">
            Welcome, Login to your account
          </h1>

          {error && (
            <div className="bg-red-100 text-red-700 p-3 rounded mb-4 w-full">
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="w-full">
            <div className="space-y-4 sm:space-y-6 mb-6 md:mb-[32px]">
              {/* Email Field Wrapper */}
              <div className="bg-[#F5F4FA] rounded-md px-3 sm:px-4 py-2">
                <label className="block text-xs font-normal text-gray-body">
                  Email
                </label>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="dallas123@gmail.com"
                  className="w-full bg-transparent focus:outline-none placeholder:text-gray-placeholder text-sm sm:text-base text-black"
                  required
                />
              </div>
              {/* Password Field Wrapper */}
              <div className="bg-[#F5F4FA] rounded-md px-3 sm:px-4 py-2 relative">
                <label className="block text-xs font-normal text-gray-body">
                  Password
                </label>
                <input
                  type={showPassword ? "text" : "password"}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="••••••••"
                  className="w-full bg-transparent focus:outline-none placeholder:text-gray text-sm sm:text-base pr-10 text-black"
                  required
                />
                <div className="absolute inset-y-0 right-0 flex items-center pr-3">
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="focus:outline-none text-black hover:text-gray-700 leading-[0]"
                  >
                    {showPassword ? (
                      <FiEyeOff size={20} />
                    ) : (
                      <FiEye size={20} />
                    )}
                  </button>
                </div>
              </div>
            </div>

            <div className="text-center">
              <button
                type="submit"
                className="w-full max-w-[260px] mx-auto bg-primary-blue text-white py-[8px] px-4 rounded-xl hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-150 text-sm font-normal"
                disabled={isLoading}
              >
                {isLoading ? "Signing in..." : "Login"}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}
