import { useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Plus, Gamepad2 } from 'lucide-react';
import { toast } from 'sonner';
import { api, ApiError } 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;
  automationRules: unknown[];
}

interface GamesResponse {
  data: Game[];
}

function extractApiMessage(error: unknown, fallback: string): string {
  if (error instanceof ApiError && error.data && typeof error.data === 'object') {
    const maybeMessage = (error.data as { message?: unknown }).message;
    if (typeof maybeMessage === 'string' && maybeMessage.trim()) {
      return maybeMessage;
    }
  }
  return fallback;
}

function formatAutomationRules(value: unknown): string {
  if (!Array.isArray(value)) {
    return '[]';
  }

  try {
    return JSON.stringify(value, null, 2);
  } catch {
    return '[]';
  }
}

function parseAutomationRules(raw: string): { rules: unknown[]; error: string | null } {
  try {
    const parsed = JSON.parse(raw) as unknown;
    if (!Array.isArray(parsed)) {
      return { rules: [], error: 'Automation JSON must be an array.' };
    }
    return { rules: parsed, error: null };
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Invalid JSON';
    return { rules: [], error: message };
  }
}

export function AdminGamesPage() {
  const queryClient = useQueryClient();
  const [open, setOpen] = useState(false);
  const [automationOpen, setAutomationOpen] = useState(false);
  const [selectedGame, setSelectedGame] = useState<Game | null>(null);
  const [automationJson, setAutomationJson] = useState('[]');
  const [automationError, setAutomationError] = useState<string | null>(null);
  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<GamesResponse>('/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('');
      toast.success('Game created');
    },
    onError: (error) => {
      toast.error(extractApiMessage(error, 'Failed to create game'));
    },
  });

  const updateAutomationMutation = useMutation({
    mutationFn: ({ gameId, rules }: { gameId: string; rules: unknown[] }) =>
      api.patch(`/admin/games/${gameId}`, { automationRules: rules }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-games'] });
      setAutomationOpen(false);
      setSelectedGame(null);
      setAutomationError(null);
      toast.success('Automation rules updated');
    },
    onError: (error) => {
      toast.error(extractApiMessage(error, 'Failed to save automation rules'));
    },
  });

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

  const openAutomationDialog = (game: Game) => {
    setSelectedGame(game);
    setAutomationJson(formatAutomationRules(game.automationRules));
    setAutomationError(null);
    setAutomationOpen(true);
  };

  const saveAutomationRules = () => {
    if (!selectedGame) return;

    const parsed = parseAutomationRules(automationJson);
    if (parsed.error) {
      setAutomationError(parsed.error);
      return;
    }

    setAutomationError(null);
    updateAutomationMutation.mutate({
      gameId: selectedGame.id,
      rules: parsed.rules,
    });
  };

  const handleAutomationTabKey = (event: ReactKeyboardEvent<HTMLTextAreaElement>) => {
    if (event.key !== 'Tab') return;

    event.preventDefault();
    const textarea = event.currentTarget;
    const selectionStart = textarea.selectionStart;
    const selectionEnd = textarea.selectionEnd;
    const nextValue = `${automationJson.slice(0, selectionStart)}  ${automationJson.slice(selectionEnd)}`;
    const nextCursor = selectionStart + 2;

    setAutomationJson(nextValue);
    requestAnimationFrame(() => {
      textarea.focus();
      textarea.setSelectionRange(nextCursor, nextCursor);
    });
  };

  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>
                <p>
                  Automation:{' '}
                  {Array.isArray(game.automationRules) ? game.automationRules.length : 0} workflow
                </p>
              </div>
              <Button
                variant="outline"
                size="sm"
                className="mt-4"
                onClick={() => openAutomationDialog(game)}
              >
                Manage Automation
              </Button>
            </CardContent>
          </Card>
        ))}
      </div>

      <Dialog
        open={automationOpen}
        onOpenChange={(nextOpen) => {
          setAutomationOpen(nextOpen);
          if (!nextOpen) {
            setSelectedGame(null);
            setAutomationError(null);
          }
        }}
      >
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>
              Automation Rules
              {selectedGame ? ` - ${selectedGame.name}` : ''}
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-2">
            <Label>JSON</Label>
            <p className="text-xs text-muted-foreground">
              Supported events: server.created, server.install.completed, server.power.started,
              server.power.stopped
            </p>
            <textarea
              value={automationJson}
              onChange={(event) => setAutomationJson(event.target.value)}
              onKeyDown={handleAutomationTabKey}
              spellCheck={false}
              className="min-h-[320px] w-full rounded-md border bg-background px-3 py-2 font-mono text-xs outline-none ring-offset-background placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring"
            />
            {automationError && <p className="text-sm text-destructive">{automationError}</p>}
          </div>

          <DialogFooter>
            <Button
              type="button"
              onClick={saveAutomationRules}
              disabled={updateAutomationMutation.isPending || !selectedGame}
            >
              {updateAutomationMutation.isPending ? 'Saving...' : 'Save Automation'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
