import React, { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { SearchInput } from '../ui/input';
import { UserTableRow } from './UserTableRow';
import { BanUserModal } from './modals/BanUserModal';
import { User } from '../../types';
import { Filter, Download, UserPlus, Loader2 } from 'lucide-react';
import { useToast } from '../../context/ToastContext';
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 instanceof Error ? e.message : String(e),
          stack: e instanceof Error ? e.stack : undefined,
        });
        addToast('Failed to load users', 'error');
      } finally {
        setLoading(false);
      }
    };
    loadUsers();
  }, []);

  const handleBan = (reason: string, _details: string, duration: string) => {
    if (!selectedUser) return;
    addToast(
      `Banned ${selectedUser.username} for ${duration}. Reason: ${reason}`,
      'success',
    );
    setUsers(users.filter((u) => u.id !== selectedUser.id)); // Mock remove
    setSelectedUser(null);
  };

  const handleDelete = (user: User) => {
    if (
      confirm(
        `Are you sure you want to delete ${user.username}? This cannot be undone.`,
      )
    ) {
      setUsers(users.filter((u) => u.id !== user.id));
      addToast(`Deleted user ${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-20">
      <div className="flex flex-col md:flex-row justify-between items-end gap-4">
        <div>
          <h2 className="text-2xl font-display font-bold text-white mb-2">
            USER MANAGEMENT
          </h2>
          <p className="text-gray-400 font-mono text-sm">
            Manage accounts, roles, and permissions.
          </p>
        </div>
        <div className="flex gap-3">
          <Button
            variant="ghost"
            icon={<Download className="w-4 h-4" />}
            onClick={() => addToast('Exporting CSV...')}
          >
            Export
          </Button>
          <Button
            variant="primary"
            icon={<UserPlus className="w-4 h-4" />}
            onClick={() => addToast('Create User Modal')}
          >
            Create User
          </Button>
        </div>
      </div>

      <Card variant="default" className="p-0 overflow-hidden">
        <div className="p-4 border-b border-kodo-steel bg-kodo-ink/50 flex flex-col md:flex-row gap-4 justify-between items-center">
          <div className="w-full md:w-96">
            <SearchInput
              placeholder="Search users by name or email..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
          </div>
          <div className="flex gap-2">
            <Button
              variant="ghost"
              size="sm"
              icon={<Filter className="w-3 h-3" />}
            >
              Filter Role
            </Button>
            <Button
              variant="ghost"
              size="sm"
              icon={<Filter className="w-3 h-3" />}
            >
              Filter Status
            </Button>
          </div>
        </div>

        {loading ? (
          <div className="flex justify-center py-20">
            <Loader2 className="w-8 h-8 text-kodo-cyan animate-spin" />
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="border-b border-kodo-steel bg-kodo-graphite text-xs font-bold text-gray-500 uppercase tracking-wider">
                  <th className="p-4">User</th>
                  <th className="p-4">Email</th>
                  <th className="p-4">Roles</th>
                  <th className="p-4">Plan</th>
                  <th className="p-4">Joined</th>
                  <th className="p-4">Last Login</th>
                  <th className="p-4 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-kodo-steel/30">
                {filteredUsers.map((user) => (
                  <UserTableRow
                    key={user.id}
                    user={user}
                    onBan={() => setSelectedUser(user)}
                    onDelete={() => handleDelete(user)}
                    onEditRole={() =>
                      addToast(`Editing role for ${user.username}`)
                    }
                  />
                ))}
                {filteredUsers.length === 0 && (
                  <tr>
                    <td colSpan={7} className="p-8 text-center text-gray-500">
                      No users found.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        )}

        <div className="p-4 border-t border-kodo-steel bg-kodo-ink/30 text-xs text-gray-500 flex justify-between items-center">
          <span>
            Showing {filteredUsers.length} of {users.length} users
          </span>
          <div className="flex gap-2">
            <button className="hover:text-white disabled:opacity-50" disabled>
              Previous
            </button>
            <button className="hover:text-white">Next</button>
          </div>
        </div>
      </Card>

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