import React, { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { UserTableRow } from './UserTableRow';
import { BanUserModal } from './modals/BanUserModal';
import { User } from '../../types';
import { Search, Shield, Activity, Users, Download, UserPlus, Loader2 } from 'lucide-react';
import { useToast } from '../../components/feedback/ToastProvider';
import { userService } from '../../services/userService';
import { logger } from '@/utils/logger';

export const AdminUsersView: React.FC = () => {
  const { addToast } = useToast();
  const [search, setSearch] = useState('');
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);

  useEffect(() => {
    const loadUsers = async () => {
      setLoading(true);
      try {
        const res = await userService.list();
        setUsers(res.users);
      } catch (e) {
        logger.error('Failed to load users', { error: e });
        addToast('Failed to load neural identities', 'error');
      } finally {
        setLoading(false);
      }
    };
    loadUsers();
  }, []);

  const handleBan = (duration: string) => {
    if (!selectedUser) return;
    addToast(`Node ${selectedUser.username} quarantined for ${duration}.`, 'success');
    setUsers(users.filter((u) => u.id !== selectedUser.id));
    setSelectedUser(null);
  };

  const handleDelete = (user: User) => {
    if (confirm(`INITIATE PERMANENT DELETION: ${user.username}?`)) {
      setUsers(users.filter((u) => u.id !== user.id));
      addToast(`Identity purged: ${user.username}`, 'info');
    }
  };

  const filteredUsers = users.filter(
    (u) =>
      u.username.toLowerCase().includes(search.toLowerCase()) ||
      u.email.toLowerCase().includes(search.toLowerCase()),
  );

  return (
    <div className="space-y-6 animate-fadeIn pb-24 container py-8">
      <div className="flex flex-col md:flex-row justify-between items-end gap-6 border-b border-white/5 pb-8">
        <div>
          <h2 className="text-4xl font-display font-bold text-white mb-2 flex items-center gap-3">
            <Users className="text-primary w-8 h-8" /> IDENTITY GRID
          </h2>
          <p className="text-muted-foreground font-mono text-xs tracking-[0.2em]">USER DIRECTORY • ACCESS PERMISSIONS</p>
        </div>
        <div className="flex gap-3">
          <Button variant="outline" onClick={() => addToast('Generating CSV matrix...', 'info')} className="border-white/10 hover:bg-white/5 font-mono text-[10px] tracking-widest uppercase">
            <Download className="w-4 h-4 mr-2" /> Export
          </Button>
          <Button variant="primary" onClick={() => addToast('Opening Registration Terminal...', 'info')} className="shadow-glow-cyan font-mono text-[10px] tracking-widest uppercase">
            <UserPlus className="w-4 h-4 mr-2" /> New Entity
          </Button>
        </div>
      </div>

      <Card variant="glass" className="p-0 overflow-hidden bg-black/40 border-white/5">
        <div className="p-6 border-b border-white/5 bg-white/2 flex flex-col md:flex-row gap-6 justify-between items-center">
          <div className="w-full md:w-96 relative group">
            <Input
              icon={<Search className="w-4 h-4" />}
              placeholder="Search by ID or frequency..."
              value={search}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearch(e.target.value)}
              className="bg-black/40 border-white/10"
            />
          </div>
          <div className="flex gap-3">
            <Button variant="outline" size="sm" className="bg-white/2 border-white/5 hover:bg-white/10 font-mono text-[10px] tracking-widest uppercase h-10">
              <Shield className="w-3 h-3 mr-2 text-primary" /> Filter Role
            </Button>
            <Button variant="outline" size="sm" className="bg-white/2 border-white/5 hover:bg-white/10 font-mono text-[10px] tracking-widest uppercase h-10">
              <Activity className="w-3 h-3 mr-2 text-primary" /> Filter Status
            </Button>
          </div>
        </div>

        {loading ? (
          <div className="flex justify-center py-20 opacity-40">
            <Loader2 className="w-12 h-12 text-primary animate-spin" />
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-left">
              <thead>
                <tr className="text-[10px] text-muted-foreground uppercase tracking-[0.2em] border-b border-white/5 bg-black/20">
                  <th className="py-4 pl-8">Identity</th>
                  <th className="py-4">Access Origin</th>
                  <th className="py-4">Assigned Roles</th>
                  <th className="py-4">Network Plan</th>
                  <th className="py-4">Registered</th>
                  <th className="py-4">Last Sync</th>
                  <th className="py-4 text-right pr-8">Management</th>
                </tr>
              </thead>
              <tbody className="text-sm divide-y divide-white/5 font-sans">
                {filteredUsers.map((user) => (
                  <UserTableRow
                    key={user.id}
                    user={user}
                    onBan={() => setSelectedUser(user)}
                    onDelete={() => handleDelete(user)}
                    onEditRole={() => addToast(`Modifying access roles for ${user.username}`, 'info')}
                  />
                ))}
                {filteredUsers.length === 0 && (
                  <tr>
                    <td colSpan={7} className="p-20 text-center text-muted-foreground font-mono uppercase tracking-widest opacity-30">
                      No entities found.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        )}

        <div className="p-6 border-t border-white/5 bg-black/20 flex justify-between items-center">
          <span className="text-[10px] font-mono text-muted-foreground uppercase tracking-widest">
            Displaying {filteredUsers.length} / {users.length} active nodes
          </span>
          <div className="flex gap-3">
            <Button variant="outline" size="sm" disabled className="border-white/5 opacity-50 font-mono text-[10px] h-9">
              PREV
            </Button>
            <Button variant="outline" size="sm" className="border-white/5 hover:bg-white/5 font-mono text-[10px] h-9">
              NEXT
            </Button>
          </div>
        </div>
      </Card>

      {selectedUser && (
        <BanUserModal
          username={selectedUser.username}
          onClose={() => setSelectedUser(null)}
          onConfirm={(reason, details, duration) => handleBan(duration)}
        />
      )}
    </div>
  );
};
