/**
 * User management page
 */

import { useQuery } from '@tanstack/react-query';
import { usersApi, guildsApi } from '../services/api';
import { useState } from 'react';
import { format } from 'date-fns';

export function Users() {
  const [selectedGuildId, setSelectedGuildId] = useState<number | undefined>();
  const [searchTerm, setSearchTerm] = useState('');

  const { data: guilds } = useQuery({
    queryKey: ['guilds'],
    queryFn: guildsApi.list,
  });

  const { data: users, isLoading } = useQuery({
    queryKey: ['users', selectedGuildId, searchTerm],
    queryFn: () => usersApi.search(selectedGuildId!, searchTerm || undefined),
    enabled: !!selectedGuildId,
  });

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">User Management</h1>
          <p className="text-gray-600 mt-1">Search and manage users across your servers</p>
        </div>
        <select
          value={selectedGuildId || ''}
          onChange={(e) => setSelectedGuildId(e.target.value ? Number(e.target.value) : undefined)}
          className="input max-w-xs"
        >
          <option value="">Select a Guild</option>
          {guilds?.map((guild) => (
            <option key={guild.id} value={guild.id}>
              {guild.name}
            </option>
          ))}
        </select>
      </div>

      {!selectedGuildId ? (
        <div className="card text-center py-12">
          <p className="text-gray-600">Please select a guild to search users</p>
        </div>
      ) : (
        <>
          {/* Search */}
          <div className="card">
            <label className="label">Search Users</label>
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Enter username..."
              className="input"
            />
          </div>

          {/* Results */}
          <div className="card">
            {isLoading ? (
              <div className="text-center py-12">Loading...</div>
            ) : users && users.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b border-gray-200">
                      <th className="text-left py-3 px-4 font-semibold text-gray-700">Username</th>
                      <th className="text-left py-3 px-4 font-semibold text-gray-700">Strikes</th>
                      <th className="text-left py-3 px-4 font-semibold text-gray-700">Warnings</th>
                      <th className="text-left py-3 px-4 font-semibold text-gray-700">Kicks</th>
                      <th className="text-left py-3 px-4 font-semibold text-gray-700">Bans</th>
                      <th className="text-left py-3 px-4 font-semibold text-gray-700">Timeouts</th>
                      <th className="text-left py-3 px-4 font-semibold text-gray-700">First Seen</th>
                    </tr>
                  </thead>
                  <tbody>
                    {users.map((user) => (
                      <tr key={user.user_id} className="border-b border-gray-100 hover:bg-gray-50">
                        <td className="py-3 px-4 font-medium">{user.username}</td>
                        <td className="py-3 px-4">
                          <span
                            className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
                              user.strike_count > 5
                                ? 'bg-red-100 text-red-800'
                                : user.strike_count > 2
                                ? 'bg-yellow-100 text-yellow-800'
                                : 'bg-gray-100 text-gray-800'
                            }`}
                          >
                            {user.strike_count}
                          </span>
                        </td>
                        <td className="py-3 px-4 text-center">{user.total_warnings}</td>
                        <td className="py-3 px-4 text-center">{user.total_kicks}</td>
                        <td className="py-3 px-4 text-center">{user.total_bans}</td>
                        <td className="py-3 px-4 text-center">{user.total_timeouts}</td>
                        <td className="py-3 px-4 text-sm text-gray-600">
                          {format(new Date(user.first_seen), 'MMM d, yyyy')}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <div className="text-center py-12 text-gray-600">
                {searchTerm ? 'No users found matching your search' : 'Enter a username to search'}
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}
