'use client';

import { useState, useEffect } from 'react';
import { inventoryApi } from '@/lib/api';
import { User, LogIn, Shield, X, Loader2 } from 'lucide-react';
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 [isEnterprise, setIsEnterprise] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedUserForLogin, setSelectedUserForLogin] = useState<any | null>(null);
  const [password, setPassword] = useState('');
  const router = useRouter();

  useEffect(() => {
    setMounted(true);
    checkMode();
  }, []);

  const checkMode = async () => {
    try {
      setIsLoading(true);
      // TODO: getNetworkConfig() method not implemented in API
      // const config = await inventoryApi.getNetworkConfig();
      // setIsEnterprise(config.mode === 'enterprise');
      setIsEnterprise(false); // Default to non-enterprise mode

      const userList = await inventoryApi.getUsers();
      setUsers(userList);
    } catch (error) {
      console.error("Failed to load users", error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleLogin = async (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    
    const username = isEnterprise ? (document.getElementById('username') as HTMLInputElement)?.value : selectedUserForLogin?.username;
    
    if (!username) {
      toast.error("Please select or enter a username");
      return;
    }

    try {
      const response = await inventoryApi.login({ username, password });
      localStorage.setItem('inventory_token', response.access_token);
      localStorage.setItem('inventory_user', JSON.stringify(response.user));
      
      toast.success(`Access Granted: ${response.user.username}`);
      router.push('/');
    } catch (error: any) {
      const detail = error.response?.data?.detail || (isEnterprise ? "Identity Verification Failed" : "Invalid Protocol Password");
      toast.error(detail);
    }
  };

  if (!mounted) return null;

  return (
    <div className="bg-background flex items-center justify-center min-h-screen p-4">
      <Toaster position="top-center" />

      <div className="level-2 p-6 md:p-8 max-w-sm w-full space-y-6 animate-in fade-in zoom-in duration-500">
        <div className="text-center space-y-4">
          <div className="w-20 h-20 bg-primary/10 text-primary flex items-center justify-center mx-auto mb-6 border border-primary/20">
            <User size={40} />
          </div>
          <h1 className="text-3xl font-normal text-white tracking-tight">Identity Check</h1>
          <p className="text-secondary text-sm font-normal">Secure Access Protocol Required</p>
        </div>

        {isLoading ? (
          <div className="flex justify-center py-10">
            <Loader2 className="animate-spin text-primary" size={32} />
          </div>
        ) : (
          <div className="grid gap-3">
            {!selectedUserForLogin && !isEnterprise ? (
              <>
                {users.length > 0 ? (
                  users.map((user) => (
                    <button
                      key={user.id}
                      onClick={() => setSelectedUserForLogin(user)}
                      className="w-full flex items-center gap-4 p-4 bg-surface-container border border-border hover:border-primary/50 transition-all text-left group"
                    >
                      <div className="w-10 h-10 bg-black flex items-center justify-center text-secondary group-hover:text-primary transition-colors border border-border">
                        {user.role === 'admin' ? <Shield size={18} /> : <User size={18} />}
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-base font-normal text-white truncate">{user.username}</p>
                        <p className="text-[10px] text-secondary font-normal uppercase tracking-widest">{user.role}</p>
                      </div>
                    </button>
                  ))
                ) : (
                  <p className="text-center text-xs text-rose-500 bg-rose-500/10 p-4 border border-rose-500/20">No local operators detected.</p>
                )}
              </>
            ) : (
              <form onSubmit={handleLogin} className="space-y-4">
                {isEnterprise && (
                  <div className="space-y-1">
                    <label className="text-[10px] text-secondary font-normal ml-1">Enterprise ID</label>
                    <input
                      id="username"
                      type="text"
                      placeholder="Operator Name"
                      className="input-field w-full py-3"
                      autoFocus
                    />
                  </div>
                )}
                
                {!isEnterprise && (
                  <div className="flex items-center gap-3 p-3 bg-surface-container border border-border mb-4">
                     <div className="w-8 h-8 bg-black flex items-center justify-center text-primary border border-primary/20">
                        {selectedUserForLogin.role === 'admin' ? <Shield size={16} /> : <User size={16} />}
                     </div>
                     <span className="text-white font-normal flex-1">{selectedUserForLogin.username}</span>
                     <button type="button" onClick={() => setSelectedUserForLogin(null)} className="text-secondary hover:text-white">
                        <X size={16} />
                     </button>
                  </div>
                )}

                <div className="space-y-1">
                  <label className="text-[10px] text-secondary font-normal ml-1">Security Key</label>
                  <input
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="••••••••"
                    className="input-field w-full py-3 tracking-widest"
                    autoFocus={!isEnterprise}
                  />
                </div>

                <button
                  type="submit"
                  className="btn-primary w-full py-4 text-lg mt-2"
                >
                  Authorize Access
                </button>
                
                {!isEnterprise && (
                  <button
                    type="button"
                    onClick={() => setSelectedUserForLogin(null)}
                    className="w-full text-center text-xs text-secondary hover:text-white transition-colors py-2"
                  >
                    Switch Identity
                  </button>
                )}
              </form>
            )}
          </div>
        )}

        <div className="pt-6 border-t border-border flex flex-col items-center gap-2 opacity-40">
           <img src="/logo.png" alt="TFM" className="h-6 grayscale" />
           <p className="text-[10px] font-mono text-secondary">TFM Group Industrial Automation</p>
        </div>
      </div>
    </div>
  );
}
