import { useParams, Link } from 'react-router';
import { useQuery } from '@tanstack/react-query';
import { Server, Network, Activity, Plus } from 'lucide-react';
import { api } from '@/lib/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { statusBadgeVariant } from '@/lib/utils';

interface ServerSummary {
  id: string;
  uuid: string;
  name: string;
  status: string;
  gameName: string;
  nodeName: string;
  port: number;
}

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

export function DashboardPage() {
  const { orgId } = useParams();

  const { data: serversData } = useQuery({
    queryKey: ['servers', orgId],
    queryFn: () => api.get<PaginatedResponse<ServerSummary>>(`/organizations/${orgId}/servers`),
  });

  const { data: nodesData } = useQuery({
    queryKey: ['nodes', orgId],
    queryFn: () => api.get<PaginatedResponse<{ id: string }>>(`/organizations/${orgId}/nodes`),
  });

  const servers = serversData?.data ?? [];
  const running = servers.filter((s) => s.status === 'running').length;
  const totalNodes = nodesData?.meta?.total ?? nodesData?.data?.length ?? 0;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Dashboard</h1>
        <Link to={`/org/${orgId}/servers/new`}>
          <Button>
            <Plus className="h-4 w-4" />
            New Server
          </Button>
        </Link>
      </div>

      <div className="grid gap-4 sm:grid-cols-3">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Total Servers</CardTitle>
            <Server className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{servers.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Running</CardTitle>
            <Activity className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-500">{running}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Nodes</CardTitle>
            <Network className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalNodes}</div>
          </CardContent>
        </Card>
      </div>

      <div>
        <h2 className="mb-4 text-lg font-semibold">Servers</h2>
        {servers.length === 0 ? (
          <Card>
            <CardContent className="flex flex-col items-center justify-center py-12">
              <Server className="mb-4 h-12 w-12 text-muted-foreground/50" />
              <p className="text-muted-foreground">No servers yet</p>
              <Link to={`/org/${orgId}/servers/new`}>
                <Button variant="outline" className="mt-4">
                  Create your first server
                </Button>
              </Link>
            </CardContent>
          </Card>
        ) : (
          <div className="grid gap-3">
            {servers.map((server) => (
              <Link key={server.id} to={`/org/${orgId}/servers/${server.id}/console`}>
                <Card className="transition-colors hover:border-primary/50">
                  <CardContent className="flex items-center justify-between p-4">
                    <div className="flex items-center gap-4">
                      <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
                        <Server className="h-5 w-5 text-primary" />
                      </div>
                      <div>
                        <p className="font-medium">{server.name}</p>
                        <p className="text-sm text-muted-foreground">
                          {server.gameName} &middot; {server.nodeName} &middot; :{server.port}
                        </p>
                      </div>
                    </div>
                    <Badge variant={statusBadgeVariant(server.status)}>{server.status}</Badge>
                  </CardContent>
                </Card>
              </Link>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
