'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 className="min-h-screen bg-slate-950 flex items-center justify-center p-4">
      <Toaster position="top-center" />
      
      <div className="bg-slate-900 border border-slate-800 rounded-3xl p-8 max-w-sm w-full shadow-2xl space-y-8 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-black text-white tracking-tight">Identity Check</h2>
          <p className="text-slate-500 text-sm">Select operator profile or use enterprise login</p>
        </div>
        
        <div className="grid gap-3">
          {!selectedUserForLogin && !isEnterprise ? (
            <>
              {users.map(user => (
                <button
                  key={user.id}
                  onClick={() => handleSelectUser(user)}
                  className="bg-slate-800/50 hover:bg-slate-800 border border-slate-800 hover:border-primary/40 p-4 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-slate-900 border border-slate-700 flex items-center justify-center text-slate-500 group-hover:text-primary transition-colors">
                      {user.role === 'admin' ? <Shield size={14} /> : <User size={14} />}
                    </div>
                    <div>
                      <p className="text-white font-black text-sm">{user.username}</p>
                      <p className="text-xs text-slate-500 font-bold mt-1">{user.role}</p>
                    </div>
                  </div>
                  <ChevronRight size={16} className="text-slate-600 group-hover:text-primary transition-colors" />
                </button>
              ))}
              <div className="pt-2">
                <button
                  onClick={() => setIsEnterprise(true)}
                  className="w-full flex items-center justify-center gap-2 py-4 rounded-2xl border border-dashed border-slate-700 text-slate-500 hover:text-primary hover:border-primary/40 transition-all font-bold text-xs"
                >
                  <Shield size={14} />
                  Enterprise 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-black text-slate-500">Enterprise Account</p>
                 <button 
                   onClick={() => setIsEnterprise(false)}
                   className="text-xs font-black text-primary hover:underline"
                 >
                   Back to profiles
                 </button>
               </div>
               
               <div className="space-y-2">
                 <label className="text-xs font-black text-slate-500 px-1">Username</label>
                 <div className="relative">
                   <User className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500" size={16} />
                   <input 
                     ref={enterpriseUserRef}
                     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-black text-slate-500 px-1">Password</label>
                 <div className="relative">
                   <Lock className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500" size={16} />
                   <input 
                     ref={enterprisePassRef}
                     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 
                 onClick={handleLogin}
                 className="w-full bg-primary text-white font-black 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 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-slate-400" />
                </button>
                <div>
                  <p className="text-sm font-bold text-slate-500">Logging in as</p>
                  <p className="text-white font-black">{selectedUserForLogin.username}</p>
                </div>
              </div>
              
              <div className="space-y-2">
                <label className="text-xs font-black text-slate-500 px-1">Password</label>
                <div className="relative">
                  <Lock className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500" size={16} />
                   <input 
                    ref={localPassRef}
                    type="password"
                    autoFocus
                    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 
                onClick={handleLogin}
                className="w-full bg-primary text-white font-black py-4 rounded-2xl shadow-xl shadow-primary/20 active:scale-95 transition-all"
              >
                Verify Identity
              </button>
            </div>
          )}
        </div>
        
        {users.length === 0 && (
          <div className="text-center p-8 text-slate-500 animate-pulse">
            Initializing users...
          </div>
        )}
      </div>
    </div>
  );
}
