'use client';

import { useState, memo, useRef } from 'react';
import { User, Shield, ChevronRight, X, Lock } from 'lucide-react';
import { inventoryApi } from '@/lib/api';
import { toast } from 'react-hot-toast';

interface IdentityCheckOverlayProps {
  show: boolean;
  users: any[];
  onAuthenticated: (user: any) => void;
}

const IdentityCheckOverlay = memo(({ show, users, onAuthenticated }: IdentityCheckOverlayProps) => {
  const [selectedUserForLogin, setSelectedUserForLogin] = useState<any | null>(null);
  const [isEnterprise, setIsEnterprise] = useState(false);
  
  const enterpriseUserRef = useRef<HTMLInputElement>(null);
  const enterprisePassRef = useRef<HTMLInputElement>(null);
  const localPassRef = useRef<HTMLInputElement>(null);

  if (!show) return null;

  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 {
      const user = await inventoryApi.login({
        username,
        password
      });
      onAuthenticated(user);
      setSelectedUserForLogin(null);
      setIsEnterprise(false);
    } catch (error) {
      toast.error(isEnterprise ? "Login failed. Check credentials or group membership." : "Invalid password");
    }
  };

  const handleSelectUser = async (user: any) => {
    if (user.username === 'Admin' || user.id > 1) {
      setSelectedUserForLogin(user);
      return;
    }
    
    // Auto-login for passwordless users (if any exist beyond Admin)
    onAuthenticated(user);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/90 backdrop-blur-xl animate-in fade-in zoom-in duration-300">
      <div className="bg-slate-900 border border-slate-800 rounded-3xl p-8 max-w-sm w-full shadow-2xl space-y-8">
        <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 uppercase tracking-tight">Identity Check</h2>
          <p className="text-slate-500 text-sm">Select operator profile to continue</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 tracking-widest">{user.username}</p>
                      <p className="text-[10px] text-slate-500 font-bold mt-1 tracking-widest">{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 uppercase tracking-widest"
                >
                  <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-[10px] font-black text-slate-500 uppercase tracking-widest">Enterprise Account</p>
                 <button 
                   onClick={() => setIsEnterprise(false)}
                   className="text-[10px] font-black text-primary uppercase tracking-widest hover:underline"
                 >
                   Back to profiles
                 </button>
               </div>
               
               <div className="space-y-2">
                 <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest 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-[10px] font-black text-slate-500 uppercase tracking-widest 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 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 uppercase tracking-widest 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-xs font-bold text-slate-500 uppercase tracking-widest">Logging in as</p>
                  <p className="text-white font-black tracking-tight">{selectedUserForLogin.username}</p>
                </div>
              </div>
              
              <div className="space-y-2">
                <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest 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 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 uppercase tracking-widest 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>
  );
});

export default IdentityCheckOverlay;
