'use client';

import { useState } from 'react';
import { X, Shield, UserPlus, User, Trash2, Tag, Plus, AlertTriangle, LogOut, Layers } from 'lucide-react';
import { inventoryApi } from '@/lib/api';
import { toast } from 'react-hot-toast';
import CreateUserModal from './CreateUserModal';
import ConfirmationModal from './ConfirmationModal';
import CategoryCreationModal from './CategoryCreationModal';

interface AdminOverlayProps {
  show: boolean;
  onClose: () => void;
  users: any[];
  categories: any[];
  onUpdateUsers: (users: any[]) => void;
  onUpdateCategories: (categories: any[]) => void;
}

export default function AdminOverlay({
  show,
  onClose,
  users,
  categories,
  onUpdateUsers,
  onUpdateCategories
}: AdminOverlayProps) {
  const [showCreateUserModal, setShowCreateUserModal] = useState(false);
  const [showCreateCategoryModal, setShowCreateCategoryModal] = useState(false);
  const [confirmState, setConfirmState] = useState<{
    show: boolean;
    type: 'user' | 'category' | null;
    itemId?: number;
    itemName?: string;
    affectedCount?: number;
    loading?: boolean;
  }>({
    show: false,
    type: null,
    loading: false,
  });

  if (!show) return null;

  const handleUserCreated = () => {
    inventoryApi.getUsers().then(onUpdateUsers);
  };

  const handleCategoryCreated = () => {
    inventoryApi.getCategories().then(onUpdateCategories);
  };

  const handleDeleteUser = async () => {
    if (!confirmState.itemId) return;
    setConfirmState(prev => ({ ...prev, loading: true }));
    try {
      await inventoryApi.deleteUser(confirmState.itemId);
      toast.success("User removed");
      await inventoryApi.getUsers().then(onUpdateUsers);
      setConfirmState({ show: false, type: null, loading: false });
    } catch (error) {
      toast.error("Delete failed");
      setConfirmState(prev => ({ ...prev, loading: false }));
    }
  };

  const handleDeleteCategory = async () => {
    if (!confirmState.itemId) return;
    setConfirmState(prev => ({ ...prev, loading: true }));
    try {
      await inventoryApi.deleteCategory(confirmState.itemId);
      toast.success("Category removed");
      await inventoryApi.getCategories().then(onUpdateCategories);
      setConfirmState({ show: false, type: null, loading: false });
    } catch (error: any) {
      toast.error(error?.response?.data?.detail || "Delete failed");
      setConfirmState(prev => ({ ...prev, loading: false }));
    }
  };

  return (
    <>
      <CreateUserModal
        show={showCreateUserModal}
        onClose={() => setShowCreateUserModal(false)}
        onUserCreated={handleUserCreated}
      />
      <CategoryCreationModal
        show={showCreateCategoryModal}
        onClose={() => setShowCreateCategoryModal(false)}
        onCategoryCreated={handleCategoryCreated}
      />
      <ConfirmationModal
        show={confirmState.show && confirmState.type === 'user'}
        title={`Delete User: ${confirmState.itemName}?`}
        description="This will remove the user from the system. The audit log will remain."
        itemName={confirmState.itemName}
        consequence="This cannot be undone."
        onConfirm={handleDeleteUser}
        onCancel={() => setConfirmState({ show: false, type: null, loading: false })}
        loading={confirmState.loading}
        dangerLevel="medium"
      />
      <ConfirmationModal
        show={confirmState.show && confirmState.type === 'category'}
        title={`Delete Category: ${confirmState.itemName}?`}
        description="This will remove the category from the system."
        itemName={confirmState.itemName}
        affectedCount={confirmState.affectedCount}
        consequence="This cannot be undone. Audit logs will remain."
        onConfirm={handleDeleteCategory}
        onCancel={() => setConfirmState({ show: false, type: null, loading: false })}
        loading={confirmState.loading}
        dangerLevel={confirmState.affectedCount && confirmState.affectedCount > 10 ? 'high' : 'medium'}
      />
      <div data-testid="admin-overlay" className="fixed inset-0 z-50 bg-background/60 animate-in fade-in duration-300">
      <div className="absolute inset-y-0 right-0 w-full max-w-md sm:max-w-lg md:max-w-md bg-surface border-l border-slate-800 shadow-2xl flex flex-col animate-in slide-in-from-right duration-500">
        <div className="p-3 md:p-6 border-b border-slate-800 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2 lg:p-3 xl:p-4 lg:p-5 xl:p-6 lg:p-8 xl:p-10 bg-slate-800 rounded-xl text-primary">
              <Shield size={20} />
            </div>
            <h2 className="text-xl font-normal text-white">System Admin</h2>
          </div>
          <button
            data-testid="close-admin-overlay"
            onClick={onClose}
            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-full transition-colors text-muted focus-visible:ring-2 focus-visible:ring-primary focus-visible:outline-none"
            aria-label="Close"
          >
            <X size={20} />
          </button>
        </div>
        
        <div className="flex-1 overflow-y-auto p-3 md:p-6 space-y-3 md:space-y-4">
          <section className="space-y-2 md:space-y-3">
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-sm font-normal text-secondary">User Management</h3>
                <p className="text-xs text-muted mt-0.5">Create accounts and control access</p>
              </div>
              <button
                onClick={() => setShowCreateUserModal(true)}
                className="flex items-center gap-1 text-xs font-normal text-primary hover:text-blue-400 focus-visible:ring-2 focus-visible:ring-primary focus-visible:outline-none rounded px-1"
              >
                <UserPlus size={12} /> Add User
              </button>
            </div>
            
            <div className="grid gap-1.5 md:gap-2">
              {users.map(u => (
                <div key={u.id} className="bg-slate-800/40 border border-slate-800 p-3 md:p-4 rounded-2xl flex items-center justify-between">
                  <div className="flex items-center gap-2 md:gap-3">
                    <div className={`p-2 rounded-lg ${u.role === 'admin' ? "bg-primary/20 text-primary" : "bg-slate-700 text-secondary"}`}>
                      <User size={16} />
                    </div>
                    <div>
                      <p className="text-sm font-normal text-white">{u.username}</p>
                      <p className="text-xs font-normal text-muted">{u.role}</p>
                    </div>
                  </div>
                  
                  {u.username !== 'Admin' && (
                    <button
                      onClick={() => {
                        setConfirmState({
                          show: true,
                          type: 'user',
                          itemId: u.id,
                          itemName: u.username,
                          loading: false,
                        });
                      }}
                      className="p-2 lg:p-3 xl:p-4 lg:p-5 xl:p-6 lg:p-8 xl:p-10 text-rose-500 hover:bg-rose-500/10 rounded-lg transition-all focus-visible:ring-2 focus-visible:ring-rose-500 focus-visible:outline-none"
                      aria-label={`Delete user ${u.username}`}
                    >
                      <Trash2 size={16} />
                    </button>
                  )}
                </div>
              ))}
            </div>
          </section>

          <section className="space-y-2 md:space-y-3">
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-sm font-normal text-secondary">Category Groups</h3>
                <p className="text-xs text-muted mt-0.5">Organize items by type or location</p>
              </div>
              <button
                onClick={() => setShowCreateCategoryModal(true)}
                className="flex items-center gap-1 text-xs font-normal text-primary hover:text-blue-400 focus-visible:ring-2 focus-visible:ring-primary focus-visible:outline-none rounded px-1"
              >
                <Plus size={12} /> Add Category
              </button>
            </div>

            <div className="grid gap-1.5 md:gap-2">
              {categories.map(cat => (
                <div key={cat.id} className="bg-slate-800/40 border border-slate-800 p-3 md:p-4 rounded-2xl flex items-center justify-between">
                  <div className="flex items-center gap-2 md:gap-3">
                    <div className="p-2 bg-primary/10 rounded-lg text-primary">
                      <Layers size={16} />
                    </div>
                    <div>
                      <p className="text-sm font-normal text-white">{cat.name}</p>
                      <p className="text-xs text-muted font-mono">{cat.description || 'No description'}</p>
                    </div>
                  </div>
                  
                  <button
                     onClick={() => {
                       setConfirmState({
                         show: true,
                         type: 'category',
                         itemId: cat.id,
                         itemName: cat.name,
                         affectedCount: 0, // TODO: fetch actual count from backend
                         loading: false,
                       });
                     }}
                     className="p-2 lg:p-3 xl:p-4 lg:p-5 xl:p-6 lg:p-8 xl:p-10 text-rose-500 hover:bg-rose-500/10 rounded-lg transition-all focus-visible:ring-2 focus-visible:ring-rose-500 focus-visible:outline-none"
                     aria-label={`Delete category ${cat.name}`}
                  >
                     <Trash2 size={16} />
                  </button>
                </div>
              ))}
            </div>
          </section>

          <section className="p-4 md:p-6 bg-slate-800/30 rounded-3xl border border-slate-800 space-y-2 md:space-y-3">
            <div className="flex items-center gap-2 text-rose-500">
              <AlertTriangle size={16} />
              <p className="text-sm font-normal">Sign Out</p>
            </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 text-muted">End your session and return to the login screen.</p>
            <button
              onClick={() => {
                import('@/lib/auth').then(m => m.clearAuth());
                window.location.href = '/login';
              }}
              className="w-full bg-rose-500/10 hover:bg-rose-500/20 text-rose-500 border border-rose-500/20 font-normal py-3 rounded-xl transition-all flex items-center justify-center gap-2 focus-visible:ring-2 focus-visible:ring-rose-500 focus-visible:outline-none"
            >
              <LogOut size={16} /> Sign Out
            </button>
          </section>
        </div>
      </div>
      </div>
    </>
  );
}
