import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { api } from '@/lib/api';
import { Check, X, UserCheck, UserX, Shield, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { Loading } from '@/components/Loading';

interface User {
  id: string;
  email: string;
  name: string | null;
  role: string;
  isApproved: boolean;
  createdAt: string;
}

export function UserList() {
  const queryClient = useQueryClient();
  const [processingUser, setProcessingUser] = useState<string | null>(null);

  const { data: users, isLoading } = useQuery<User[]>({
    queryKey: ['users'],
    queryFn: async () => {
      const { data } = await api.get('/users');
      return data;
    },
  });

  const approveMutation = useMutation({
    mutationFn: async (userId: string) => {
      await api.patch(`/users/${userId}/approve`, { isApproved: true });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['users'] });
      setProcessingUser(null);
      toast.success('User approved successfully');
    },
    onError: (error: any) => {
      console.error('[USERS] Failed to approve user:', error);
      setProcessingUser(null);
      toast.error(error.response?.data?.message || 'Failed to approve user');
    },
  });

  const deleteUserMutation = useMutation({
    mutationFn: async (userId: string) => {
      await api.delete(`/users/${userId}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['users'] });
      setProcessingUser(null);
      toast.success('User deleted successfully');
    },
    onError: (error: any) => {
      console.error('[USERS] Failed to delete user:', error);
      setProcessingUser(null);
      toast.error(error.response?.data?.message || 'Failed to delete user');
    },
  });

  const changeRoleMutation = useMutation({
    mutationFn: async ({ userId, role }: { userId: string; role: string }) => {
      await api.patch(`/users/${userId}`, { role });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['users'] });
      toast.success('User role updated successfully');
    },
    onError: (error: any) => {
      console.error('[USERS] Failed to update user role:', error);
      toast.error(error.response?.data?.message || 'Failed to update user role');
    },
  });

  const handleRoleChange = (userId: string, newRole: string) => {
    if (confirm(`Change user role to ${newRole}?`)) {
      changeRoleMutation.mutate({ userId, role: newRole });
    }
  };

  const handleApprove = (userId: string) => {
    if (confirm('Approve this user?')) {
      setProcessingUser(userId);
      approveMutation.mutate(userId);
    }
  };

  const handleDeny = (userId: string) => {
    if (confirm('Delete this user? This action cannot be undone.')) {
      setProcessingUser(userId);
      deleteUserMutation.mutate(userId);
    }
  };

  if (isLoading) {
    return <Loading message="Loading users..." />;
  }

  const pendingUsers = users?.filter((u) => !u.isApproved) || [];
  const approvedUsers = users?.filter((u) => u.isApproved) || [];

  return (
    <div>
      <h1 className="text-3xl font-bold text-foreground mb-6">User Management</h1>

      {/* Pending Approval Section */}
      {pendingUsers.length > 0 && (
        <div className="mb-8">
          <div className="flex items-center mb-4">
            <UserX className="h-5 w-5 text-yellow-600 mr-2" />
            <h2 className="text-xl font-semibold text-foreground">
              Pending Approval ({pendingUsers.length})
            </h2>
          </div>

          <div className="bg-card border border-border shadow-soft rounded-lg overflow-hidden transition-colors">
            <table className="min-w-full divide-y divide-border">
              <thead className="bg-muted/30">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                    Name
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                    Email
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                    Role
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                    Requested
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="bg-card divide-y divide-border">
                {pendingUsers.map((user) => (
                  <tr key={user.id} className="bg-yellow-50 dark:bg-yellow-950/20">
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-foreground">
                      {user.name || 'Unknown User'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                      {user.email}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                      <span className="px-2 py-1 bg-muted rounded text-xs font-medium">
                        {user.role}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                      {new Date(user.createdAt).toLocaleDateString()}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm">
                      <div className="flex gap-2">
                        <button
                          onClick={() => handleApprove(user.id)}
                          disabled={processingUser === user.id}
                          className="inline-flex items-center px-3 py-1 bg-green-600 text-white rounded hover:bg-green-700 disabled:opacity-50 transition-colors"
                        >
                          <Check className="h-4 w-4 mr-1" />
                          Approve
                        </button>
                        <button
                          onClick={() => handleDeny(user.id)}
                          disabled={processingUser === user.id}
                          className="inline-flex items-center px-3 py-1 bg-red-600 text-white rounded hover:bg-red-700 disabled:opacity-50 transition-colors"
                        >
                          <X className="h-4 w-4 mr-1" />
                          Deny
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Approved Users Section */}
      <div>
        <div className="flex items-center mb-4">
          <UserCheck className="h-5 w-5 text-green-600 mr-2" />
          <h2 className="text-xl font-semibold text-foreground">
            Approved Users ({approvedUsers.length})
          </h2>
        </div>

        <div className="bg-card border border-border shadow-soft rounded-lg overflow-hidden transition-colors">
          <table className="min-w-full divide-y divide-border">
            <thead className="bg-muted/30">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                  Name
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                  Email
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                  Role
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                  Status
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-card divide-y divide-border">
              {approvedUsers.map((user) => (
                <tr key={user.id} className="hover:bg-accent transition-colors">
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-foreground">
                    {user.name || 'Unknown User'}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                    {user.email}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                    <span
                      className={`px-2 py-1 rounded text-xs font-medium ${
                        user.role === 'ADMINISTRATOR'
                          ? 'bg-purple-100 text-purple-800 dark:bg-purple-950 dark:text-purple-200'
                          : user.role === 'COORDINATOR'
                          ? 'bg-blue-100 text-blue-800 dark:bg-blue-950 dark:text-blue-200'
                          : 'bg-muted text-muted-foreground'
                      }`}
                    >
                      {user.role === 'ADMINISTRATOR' && <Shield className="h-3 w-3 inline mr-1" />}
                      {user.role}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-green-600 dark:text-green-400 font-medium">
                    <Check className="h-4 w-4 inline mr-1" />
                    Active
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm">
                    <div className="flex items-center gap-2">
                      <select
                        value={user.role}
                        onChange={(e) => handleRoleChange(user.id, e.target.value)}
                        className="text-sm border border-input bg-background rounded px-2 py-1 focus:ring-primary focus:border-primary transition-colors"
                      >
                        <option value="DRIVER">Driver</option>
                        <option value="COORDINATOR">Coordinator</option>
                        <option value="ADMINISTRATOR">Administrator</option>
                      </select>
                      <button
                        onClick={() => handleDeny(user.id)}
                        className="inline-flex items-center px-2 py-1 text-red-600 hover:text-red-800 hover:bg-red-50 dark:hover:bg-red-950/20 rounded transition-colors"
                        title="Delete user"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
