import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Plus, Gamepad2 } from 'lucide-react';
import { api } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';

interface Game {
  id: string;
  slug: string;
  name: string;
  dockerImage: string;
  defaultPort: number;
  startupCommand: string;
}

interface PaginatedResponse<T> {
  data: T[];
  meta: { total: number };
}

export function AdminGamesPage() {
  const queryClient = useQueryClient();
  const [open, setOpen] = useState(false);
  const [name, setName] = useState('');
  const [slug, setSlug] = useState('');
  const [dockerImage, setDockerImage] = useState('');
  const [defaultPort, setDefaultPort] = useState(25565);
  const [startupCommand, setStartupCommand] = useState('');

  const { data } = useQuery({
    queryKey: ['admin-games'],
    queryFn: () => api.get<PaginatedResponse<Game>>('/admin/games'),
  });

  const createMutation = useMutation({
    mutationFn: (body: Record<string, unknown>) => api.post('/admin/games', body),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-games'] });
      setOpen(false);
      setName('');
      setSlug('');
      setDockerImage('');
      setStartupCommand('');
    },
  });

  const games = data?.data ?? [];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Games</h1>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="h-4 w-4" /> Add Game
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Add Game</DialogTitle>
            </DialogHeader>
            <form
              onSubmit={(e) => {
                e.preventDefault();
                createMutation.mutate({ name, slug, dockerImage, defaultPort, startupCommand });
              }}
              className="space-y-4"
            >
              <div className="space-y-2">
                <Label>Name</Label>
                <Input value={name} onChange={(e) => setName(e.target.value)} required />
              </div>
              <div className="space-y-2">
                <Label>Slug</Label>
                <Input
                  value={slug}
                  onChange={(e) =>
                    setSlug(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))
                  }
                  required
                />
              </div>
              <div className="space-y-2">
                <Label>Docker Image</Label>
                <Input
                  value={dockerImage}
                  onChange={(e) => setDockerImage(e.target.value)}
                  placeholder="itzg/minecraft-server:latest"
                  required
                />
              </div>
              <div className="space-y-2">
                <Label>Default Port</Label>
                <Input
                  type="number"
                  value={defaultPort}
                  onChange={(e) => setDefaultPort(Number(e.target.value))}
                />
              </div>
              <div className="space-y-2">
                <Label>Startup Command</Label>
                <Input
                  value={startupCommand}
                  onChange={(e) => setStartupCommand(e.target.value)}
                  required
                />
              </div>
              <DialogFooter>
                <Button type="submit" disabled={createMutation.isPending}>
                  {createMutation.isPending ? 'Creating...' : 'Create'}
                </Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>
      </div>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {games.map((game) => (
          <Card key={game.id}>
            <CardHeader className="flex flex-row items-center gap-3 pb-2">
              <Gamepad2 className="h-5 w-5 text-primary" />
              <CardTitle className="text-base">{game.name}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-1 text-sm text-muted-foreground">
                <p>
                  <Badge variant="outline">{game.slug}</Badge>
                </p>
                <p className="mt-2 font-mono text-xs">{game.dockerImage}</p>
                <p>Port: {game.defaultPort}</p>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}
