import { useState } from 'react';
import { Link } from 'react-router-dom';
import { Search } from 'lucide-react';
import { Card } from '@/components/ui/Card';
import { Input } from '@/components/ui/Input';
import { Avatar } from '@/components/ui/Avatar';
import { Badge } from '@/components/ui/Badge';
import { Button } from '@/components/ui/Button';
import { adminAPI } from '@/api/client';
import { formatNumber } from '@/lib/constants';

export default function UserLookup() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<any[]>([]);
  const [searching, setSearching] = useState(false);

  async function handleSearch() {
    if (!query.trim()) return;
    setSearching(true);
    try {
      const { data } = await adminAPI.getUsers({ search: query });
      setResults(data.users || []);
    } catch {} finally {
      setSearching(false);
    }
  }

  return (
    <div className="p-6">
      <h1 className="text-xl font-bold text-text-primary mb-6">User Lookup</h1>

      <div className="flex gap-3 mb-6">
        <div className="flex-1">
          <Input
            label="Search by username, email, or Steam ID"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            rightIcon={<Search className="w-4 h-4 text-text-muted" />}
          />
        </div>
        <Button onClick={handleSearch} loading={searching} className="self-start mt-1">
          Search
        </Button>
      </div>

      {results.length > 0 && (
        <div className="space-y-2">
          {results.map((u) => (
            <Link key={u.id} to={`/admin/users/${u.id}`}>
              <Card variant="interactive" className="flex items-center gap-4">
                <Avatar src={u.steam_avatar_url} username={u.username} size="md" />
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-text-primary">{u.username}</p>
                  <p className="text-xs text-text-muted">{u.email}</p>
                </div>
                <span className="text-sm font-mono text-amber-400">{formatNumber(u.mmr)}</span>
                <Badge>{u.role}</Badge>
              </Card>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
