'use client';

import { useState, useEffect, useRef } from 'react';
import { User, Shield, X, Lock, ChevronRight } from 'lucide-react';
import { inventoryApi } from '@/lib/api';
import { saveToken } from '@/lib/auth';
import { toast, Toaster } from 'react-hot-toast';
import { useRouter } from 'next/navigation';

export default function LoginPage() {
  const [mounted, setMounted] = useState(false);
  const [users, setUsers] = useState<any[]>([]);
  const [selectedUserForLogin, setSelectedUserForLogin] = useState<any | null>(null);
  const [isEnterprise, setIsEnterprise] = useState(false);
  const router = useRouter();
  
  const enterpriseUserRef = useRef<HTMLInputElement>(null);
  const enterprisePassRef = useRef<HTMLInputElement>(null);
  const localPassRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    setMounted(true);
    inventoryApi.getUsers()
      .then(setUsers)
      .catch((err) => {
        console.error("Failed to load users:", err);
      });

    // If already logged in, go home
    if (localStorage.getItem('inventory_token')) {
      router.push('/');
    }
  }, [router]);

  const handleLogin = async () => {
    let username = "";
    let password = "";

    if (isEnterprise) {
      username = enterpriseUserRef.current?.value || "";
      password = enterprisePassRef.current?.value || "";
    } else if (selectedUserForLogin) {
      username = selectedUserForLogin.username;
      password = localPassRef.current?.value || "";
    }

    if (!username) {
      toast.error("Username is required");
      return;
    }

    try {
      // [C-01] Login returns JWT token
      const tokenResponse = await inventoryApi.login({
        username,
        password
      });

      // Save JWT token and user info
      saveToken(tokenResponse);
      toast.success(`Welcome back, ${tokenResponse.username}`);

      // Delay slightly to show toast then redirect
      setTimeout(() => {
        router.push('/');
      }, 500);

    } catch (error: any) {
      const detail = error.response?.data?.detail || (isEnterprise ? "Login failed. Check credentials or group membership." : "Invalid password");
      toast.error(detail);
    }
  };

  const handleSelectUser = async (user: any) => {
    // [C-01] All users require password for JWT
    setSelectedUserForLogin(user);
  };

  if (!mounted) return null;

  return (
    <div data-testid="identity-check-overlay" className="bg-background flex items-center justify-center p-4 md:min-h-screen">
      <Toaster position="top-center" />

      <div className="bg-surface border border-slate-800 rounded-3xl p-4 md:p-6 max-w-sm w-full shadow-2xl space-y-3 md:space-y-4 animate-in fade-in zoom-in duration-500">
        <div className="text-center space-y-2">
          <div className="w-16 h-16 bg-primary/10 text-primary rounded-2xl flex items-center justify-center mx-auto mb-4 border border-primary/20">
            <User size={32} />
          </div>
          <h2 className="text-2xl font-normal text-white tracking-tight">Identity Check</h2>
          <p className="text-muted text-sm">Select operator profile or use direct login</p>
        </div>
        
        <div data-testid="user-list" className="grid gap-2 md:gap-3">
          {!selectedUserForLogin && !isEnterprise ? (
            <>
              {users.length > 0 ? (
                <>
                  {users.map(user => (
                    <button
                      key={user.id}
                      data-testid="user-list-item"
                      onClick={() => handleSelectUser(user)}
                      className="bg-slate-800/50 hover:bg-slate-800 border border-slate-800 hover:border-primary/40 p-4 lg:p-5 xl:p-6 lg:p-8 xl:p-10 rounded-2xl text-left transition-all group flex items-center justify-between"
                    >
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded-full bg-surface border border-slate-700 flex items-center justify-center text-muted group-hover:text-primary transition-colors">
                          {user.role === 'admin' ? <Shield size={14} /> : <User size={14} />}
                        </div>
                        <div>
                          <p className="text-white font-normal text-sm">{user.username}</p>
                          <p className="text-xs text-muted font-normal mt-1">{user.role}</p>
                        </div>
                      </div>
                      <ChevronRight size={16} className="text-secondary group-hover:text-primary transition-colors" />
                    </button>
                  ))}
                </>
              ) : (
                <div className="text-center p-4 text-muted text-xs font-normal animate-pulse">
                   Connectivity issues? Use manual login below.
                </div>
              )}
              
              <div className="pt-2 grid grid-cols-2 gap-3">
                <button
                  data-testid="ldap-login-tab"
                  onClick={() => setIsEnterprise(true)}
                  className="flex items-center justify-center gap-2 py-4 rounded-2xl border border-dashed border-slate-700 text-muted hover:text-white hover:border-slate-500 transition-all font-normal text-xs"
                >
                  <Lock size={12} />
                  Enterprise
                </button>
                <button
                  data-testid="local-login-tab"
                  onClick={() => {
                    setSelectedUserForLogin({ username: '' });
                    // We use an empty username object to trigger the manual input view
                  }}
                  className="flex items-center justify-center gap-2 py-4 rounded-2xl border border-primary/20 bg-primary/5 text-primary hover:bg-primary/10 transition-all font-normal text-xs"
                >
                  <User size={12} />
                  Manual Login
                </button>
              </div>
            </>
          ) : isEnterprise ? (
            <div className="space-y-4 animate-in slide-in-from-right-4 duration-300">
               <div className="flex justify-between items-center px-1">
                 <p className="text-xs font-normal text-muted">Enterprise Account</p>
                 <button 
                   onClick={() => setIsEnterprise(false)}
                   className="text-xs font-normal text-primary hover:underline"
                 >
                   Back to profiles
                 </button>
               </div>
               
               <div className="space-y-2">
                 <label className="text-xs font-normal text-muted px-1">Username</label>
                 <div className="relative">
                   <User className="absolute left-4 top-1/2 -translate-y-1/2 text-muted" size={16} />
                   <input
                     ref={enterpriseUserRef}
                     data-testid="username-input"
                     type="text"
                     autoFocus
                     className="w-full bg-slate-800/50 border border-slate-800 focus:border-primary rounded-2xl py-4 pl-12 pr-4 text-white focus:outline-none transition-all placeholder:text-slate-700 font-mono"
                     placeholder="e.g. jsmith"
                   />
                 </div>
               </div>

               <div className="space-y-2">
                 <label className="text-xs font-normal text-muted px-1">Password</label>
                 <div className="relative">
                   <Lock className="absolute left-4 top-1/2 -translate-y-1/2 text-muted" size={16} />
                   <input
                     ref={enterprisePassRef}
                     data-testid="password-input"
                     type="password"
                     onKeyDown={(e) => e.key === 'Enter' && handleLogin()}
                     className="w-full bg-slate-800/50 border border-slate-800 focus:border-primary rounded-2xl py-4 pl-12 pr-4 text-white/50 focus:text-white focus:outline-none transition-all placeholder:text-slate-700 font-mono"
                     placeholder="Enter password"
                   />
                 </div>
               </div>
               
               <button
                 data-testid="login-submit"
                 onClick={handleLogin}
                 className="w-full bg-primary text-white font-normal py-4 rounded-2xl shadow-xl shadow-primary/20 active:scale-95 transition-all"
               >
                 Sign In
               </button>
            </div>
          ) : (
            <div className="space-y-4 animate-in slide-in-from-right-4 duration-300">
               <div className="bg-slate-800/30 p-4 lg:p-5 xl:p-6 lg:p-8 xl:p-10 rounded-2xl border border-slate-800 flex items-center gap-3">
                <button 
                  onClick={() => setSelectedUserForLogin(null)}
                  className="p-1 hover:bg-slate-700 rounded-lg transition-colors"
                >
                  <X size={16} className="text-secondary" />
                </button>
                <div>
                  <p className="text-sm font-normal text-muted">Logging in as</p>
                  <p className="text-white font-normal">{selectedUserForLogin.username || "Manual Input"}</p>
                </div>
              </div>
              
              <div className="space-y-2">
                <label className="text-xs font-normal text-muted px-1">Username</label>
                <div className="relative">
                  <User className="absolute left-4 top-1/2 -translate-y-1/2 text-muted" size={16} />
                  <input
                    type="text"
                    autoFocus
                    value={selectedUserForLogin.username || ""}
                    onChange={(e) => setSelectedUserForLogin({...selectedUserForLogin, username: e.target.value})}
                    className="w-full bg-slate-800/50 border border-slate-800 focus:border-primary rounded-2xl py-4 pl-12 pr-4 text-white focus:outline-none transition-all placeholder:text-slate-700 font-mono"
                    placeholder="Admin"
                  />
                </div>
              </div>
              
              <div className="space-y-2">
                <label className="text-xs font-normal text-muted px-1">Password</label>
                <div className="relative">
                  <Lock className="absolute left-4 top-1/2 -translate-y-1/2 text-muted" size={16} />
                   <input
                    ref={localPassRef}
                    data-testid="local-password-input"
                    type="password"
                    autoFocus={!!selectedUserForLogin.username}
                    onKeyDown={(e) => e.key === 'Enter' && handleLogin()}
                    className="w-full bg-slate-800/50 border border-slate-800 focus:border-primary rounded-2xl py-4 pl-12 pr-4 text-white/50 focus:text-white focus:outline-none transition-all placeholder:text-slate-700 font-mono"
                    placeholder="Enter password"
                  />
                </div>
              </div>
              
              <button
                data-testid="local-login-submit"
                onClick={handleLogin}
                className="w-full bg-primary text-white font-normal py-4 rounded-2xl shadow-xl shadow-primary/20 active:scale-95 transition-all"
              >
                Verify Identity
              </button>
            </div>
          )}
        </div>
        
        {/* Progress bar hint */}
        {users.length === 0 && !selectedUserForLogin && !isEnterprise && (
          <div className="w-full bg-slate-800 h-1 rounded-full overflow-hidden">
            <div className="bg-primary h-full animate-progress-fast shadow-[0_0_8px_rgba(var(--primary-rgb),0.5)]"></div>
          </div>
        )}
      </div>
    </div>
  );
}
