"use client";

import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { api, Monitor, MonitorStatus } from "@/lib/api";
import { Badge, Button, Card, Table, Thead, Tbody, Tr, Th, Td } from "@/components/ui";

function statusVariant(status: MonitorStatus) {
  switch (status) {
    case "up":
      return "success";
    case "down":
      return "danger";
    default:
      return "warning";
  }
}

function targetSummary(m: Monitor): string {
  if (m.type === "http") return m.target.url ?? "";
  if (m.type === "tls") return `${m.target.host ?? ""}:${m.target.port || 443}`;
  if (m.type === "icmp") return m.target.host ?? "";
  return `${m.target.host ?? ""}:${m.target.port ?? ""}`;
}

export default function MonitorsPage() {
  const { data: monitors, isLoading } = useQuery({
    queryKey: ["monitors"],
    queryFn: () => api.listMonitors(),
    refetchInterval: 30_000,
  });

  return (
    <div className="p-8">
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-text-primary">Monitors</h1>
          <p className="mt-1 text-sm text-text-secondary">Service uptime and latency checks.</p>
        </div>
        <div className="flex gap-2">
          <Link href="/settings/notifications">
            <Button variant="secondary">Notifications</Button>
          </Link>
          <Link href="/monitors/new">
            <Button variant="primary">New Monitor</Button>
          </Link>
        </div>
      </div>

      <Card padding={false}>
        {isLoading ? (
          <div className="flex justify-center py-16">
            <div className="h-8 w-8 animate-spin rounded-full border-2 border-border border-t-accent" />
          </div>
        ) : !monitors || monitors.length === 0 ? (
          <div className="py-16 text-center">
            <p className="text-sm text-text-secondary">No monitors yet.</p>
            <Link href="/monitors/new">
              <Button variant="secondary" size="sm" className="mt-3">
                Create your first monitor
              </Button>
            </Link>
          </div>
        ) : (
          <Table>
            <Thead>
              <Tr>
                <Th>Name</Th>
                <Th>Type</Th>
                <Th>Target</Th>
                <Th>Status</Th>
                <Th>Latency</Th>
                <Th>Last check</Th>
              </Tr>
            </Thead>
            <Tbody>
              {monitors.map((m) => (
                <Tr key={m.monitor_id}>
                  <Td>
                    <Link href={`/monitors/${m.monitor_id}`} className="font-medium text-text-primary hover:text-accent">
                      {m.name}
                    </Link>
                  </Td>
                  <Td>
                    <Badge variant="neutral">{m.type}</Badge>
                  </Td>
                  <Td>
                    <span className="font-mono text-xs text-text-secondary">{targetSummary(m)}</span>
                  </Td>
                  <Td>
                    <Badge variant={statusVariant(m.state.status)}>{m.state.status}</Badge>
                  </Td>
                  <Td>
                    <span className="text-sm text-text-secondary">{m.state.latency_ms}ms</span>
                  </Td>
                  <Td>
                    <span className="text-xs text-text-secondary">
                      {m.state.last_check_at ? new Date(m.state.last_check_at).toLocaleTimeString() : "n/a"}
                    </span>
                  </Td>
                </Tr>
              ))}
            </Tbody>
          </Table>
        )}
      </Card>
    </div>
  );
}
