'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;
    }
    onAuthenticated(user);
  };

  return (
    <div data-testid="identity-check-overlay" className="fixed inset-0 z-[100] flex items-center justify-center p-4 lg:p-5 xl:p-6 lg:p-8 xl:p-10 bg-background/90 animate-in fade-in duration-500">
      <div className="bg-surface border border-slate-800 rounded-[2.5rem] p-8 sm:p-10 max-w-sm w-full shadow-2xl space-y-8 animate-in zoom-in-95 duration-300 relative overflow-hidden">
        
        <div className="text-center space-y-3">
          <div className="w-20 h-20 bg-primary/10 text-primary rounded-[2rem] flex items-center justify-center mx-auto mb-6 border border-primary/20 shadow-xl shadow-primary/5">
            <Shield size={40} className="italic" />
          </div>
          <h2 className="text-3xl lg:text-4xl xl:text-5xl font-black text-white tracking-tight">Protocol Access</h2>
          <p className="text-muted text-xs lg:text-sm xl:text-base lg:text-lg xl:text-xl lg:text-2xl xl:text-3xl lg:text-4xl xl:text-5xl font-black">Select operator profile to initialize</p>
        </div>
        
        <div data-testid="user-list" className="grid gap-3.5">
          {!selectedUserForLogin && !isEnterprise ? (
            <>
              {users.map(user => (
                <button
                  key={user.id}
                  data-testid="user-list-item"
                  onClick={() => handleSelectUser(user)}
                  className="bg-slate-800/40 hover:bg-slate-800 border border-slate-800/50 hover:border-primary/40 p-5 lg:p-6 xl:p-8 rounded-[1.5rem] text-left transition-all group flex items-center justify-between shadow-sm active:scale-[0.98]"
                >
                  <div className="flex items-center gap-4">
                    <div className="w-10 h-10 rounded-2xl bg-surface border border-slate-800 flex items-center justify-center text-muted group-hover:text-primary transition-all group-hover:scale-110">
                      {user.role === 'admin' ? <Shield size={18} /> : <User size={18} />}
                    </div>
                    <div>
                      <p className="text-secondary font-black text-sm lg:text-base xl:text-lg lg:text-xl xl:text-2xl lg:text-3xl xl:text-4xl tracking-tight">{user.username}</p>
                      <p className="text-xs lg:text-sm xl:text-base lg:text-lg xl:text-xl lg:text-2xl xl:text-3xl lg:text-4xl xl:text-5xl text-secondary font-black mt-0.5">{user.role}</p>
                    </div>
                  </div>
                  <div className="p-1.5 rounded-full bg-surface/70 text-muted group-hover:text-primary group-hover:bg-primary/10 transition-all">
                    <ChevronRight size={14} />
                  </div>
                </button>
              ))}
              <div className="pt-4">
                <button
                  onClick={() => setIsEnterprise(true)}
                  className="w-full flex items-center justify-center gap-3 py-5 rounded-[1.5rem] border border-dashed border-slate-800 text-secondary hover:text-primary hover:border-primary/40 hover:bg-primary/5 transition-all font-black text-xs lg:text-sm xl:text-base lg:text-lg xl:text-xl lg:text-2xl xl:text-3xl lg:text-4xl xl:text-5xl"
                >
                  <Lock size={14} />
                  Enterprise Directory
                </button>
              </div>
            </>
          ) : isEnterprise ? (
            <div className="space-y-5 animate-in slide-in-from-bottom-5 duration-300">
               <div className="flex justify-between items-center px-1">
                 <p className="text-xs lg:text-sm xl:text-base lg:text-lg xl:text-xl lg:text-2xl xl:text-3xl lg:text-4xl xl:text-5xl font-black text-secondary italic">LDAP Authentication</p>
                 <button
                   data-testid="local-login-tab"
                   onClick={() => setIsEnterprise(false)}
                   className="text-xs lg:text-sm xl:text-base lg:text-lg xl:text-xl lg:text-2xl xl:text-3xl lg:text-4xl xl:text-5xl font-black text-primary hover:underline tracking-tighter"
                 >
                   Profile Swap
                 </button>
               </div>
               
               <div className="space-y-2">
                 <div className="relative group">
                   <User className="absolute left-5 top-1/2 -translate-y-1/2 text-secondary group-focus-within:text-primary transition-colors" size={18} />
                   <input
                     ref={enterpriseUserRef}
                     data-testid="username-input"
                     type="text"
                     autoFocus
                     className="w-full bg-background/50 border border-slate-800/80 focus:border-primary/50 focus:bg-background rounded-[1.25rem] py-4.5 pl-14 pr-5 text-sm lg:text-base xl:text-lg lg:text-xl xl:text-2xl lg:text-3xl xl:text-4xl text-secondary focus:outline-none transition-all placeholder:text-muted font-mono"
                     placeholder="DIRECTORY ID"
                   />
                 </div>
               </div>

               <div className="space-y-2">
                 <div className="relative group">
                   <Lock className="absolute left-5 top-1/2 -translate-y-1/2 text-secondary group-focus-within:text-primary transition-colors" size={18} />
                   <input
                     ref={enterprisePassRef}
                     data-testid="password-input"
                     type="password"
                     onKeyDown={(e) => e.key === 'Enter' && handleLogin()}
                     className="w-full bg-background/50 border border-slate-800/80 focus:border-primary/50 focus:bg-background rounded-[1.25rem] py-4.5 pl-14 pr-5 text-sm lg:text-base xl:text-lg lg:text-xl xl:text-2xl lg:text-3xl xl:text-4xl text-secondary focus:outline-none transition-all placeholder:text-muted font-mono"
                     placeholder="••••••••"
                   />
                 </div>
               </div>
               
               <button
                 data-testid="login-submit"
                 onClick={handleLogin}
                 className="w-full bg-primary text-white font-black py-5 rounded-[1.5rem] shadow-2xl shadow-primary/20 hover:shadow-primary/30 active:scale-95 transition-all text-xs lg:text-sm xl:text-base lg:text-lg xl:text-xl lg:text-2xl xl:text-3xl lg:text-4xl xl:text-5xl border border-primary/20"
               >
                 Initialize Session
               </button>
            </div>
          ) : (
            <div className="space-y-5 animate-in slide-in-from-bottom-5 duration-300">
               <div data-testid="user-display" className="bg-background/50 p-5 lg:p-6 xl:p-8 rounded-[1.5rem] border border-slate-800 flex items-center justify-between group">
                <div className="flex items-center gap-4">
                  <div className="w-10 h-10 rounded-2xl bg-primary/10 border border-primary/20 flex items-center justify-center text-primary shadow-lg">
                    <Shield size={20} />
                  </div>
                  <div>
                    <p className="text-xs lg:text-sm xl:text-base lg:text-lg xl:text-xl lg:text-2xl xl:text-3xl lg:text-4xl xl:text-5xl font-black text-secondary">Active Profile</p>
                    <p className="text-white font-black tracking-tight">{selectedUserForLogin.username}</p>
                  </div>
                </div>
                <button 
                  onClick={() => setSelectedUserForLogin(null)}
                  className="p-2 lg:p-3 xl:p-4 lg:p-5 xl:p-6 lg:p-8 xl:p-10 hover:bg-slate-800 rounded-xl transition-all text-secondary hover:text-rose-500"
                  title="Change User"
                >
                  <X size={18} />
                </button>
              </div>
              
              <div className="space-y-2">
                <div className="relative group">
                  <Lock className="absolute left-5 top-1/2 -translate-y-1/2 text-secondary group-focus-within:text-primary transition-colors" size={18} />
                   <input
                    ref={localPassRef}
                    data-testid="local-password-input"
                    type="password"
                    autoFocus
                    onKeyDown={(e) => e.key === 'Enter' && handleLogin()}
                    className="w-full bg-background/50 border border-slate-800/80 focus:border-primary/50 focus:bg-background rounded-[1.25rem] py-4.5 pl-14 pr-5 text-sm lg:text-base xl:text-lg lg:text-xl xl:text-2xl lg:text-3xl xl:text-4xl text-secondary focus:outline-none transition-all placeholder:text-muted font-mono"
                    placeholder="KEY-PHRASE"
                  />
                </div>
              </div>
              
              <button
                data-testid="local-login-submit"
                onClick={handleLogin}
                className="w-full bg-primary text-white font-black py-5 rounded-[1.5rem] shadow-2xl shadow-primary/20 hover:shadow-primary/30 active:scale-95 transition-all text-xs lg:text-sm xl:text-base lg:text-lg xl:text-xl lg:text-2xl xl:text-3xl lg:text-4xl xl:text-5xl border border-primary/20"
              >
                Unlock Account
              </button>
            </div>
          )}
        </div>
        
        {users.length === 0 && (
          <div className="text-center p-8 text-muted animate-pulse font-black text-xs lg:text-sm xl:text-base lg:text-lg xl:text-xl lg:text-2xl xl:text-3xl lg:text-4xl xl:text-5xl">
            Synchronizing User Tokens...
          </div>
        )}
      </div>
    </div>
  );
});

export default IdentityCheckOverlay;
