"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import { api, Monitor, MonitorStatus, Rollup } from "@/lib/api";
import { Badge, Button, Card, CardHeader, CardTitle, 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 uptimePct(rollups: Rollup[]): number {
    const checks = rollups.reduce((a, r) => a + r.checks, 0);
    const up = rollups.reduce((a, r) => a + r.up_count, 0);
    return checks > 0 ? (up / checks) * 100 : 0;
}

function Heartbeat({ rollups }: { rollups: Rollup[] }) {
    const recent = rollups.slice(-48);
    return (
        <div className="flex items-end gap-0.5">
            {recent.map((r) => {
                const pct = r.checks > 0 ? (r.up_count / r.checks) * 100 : 0;
                const color = r.checks === 0 ? "bg-surface-2" : pct >= 99 ? "bg-success" : pct >= 80 ? "bg-warning" : "bg-danger";
                return <div key={r.period_start} className={`h-8 w-1.5 rounded-sm ${color}`} title={`${new Date(r.period_start).toLocaleString()} ${pct.toFixed(0)}% up`} />;
            })}
            {recent.length === 0 && <span className="text-xs text-text-secondary">No history yet.</span>}
        </div>
    );
}

export default function MonitorDetailPage() {
    const params = useParams();
    const router = useRouter();
    const queryClient = useQueryClient();
    const monitorId = params.id as string;
    const [confirmDelete, setConfirmDelete] = useState(false);

    const { data: monitor, isLoading } = useQuery({
        queryKey: ["monitors", monitorId],
        queryFn: () => api.getMonitor(monitorId),
        refetchInterval: 30_000,
    });

    const { data: rollups } = useQuery({
        queryKey: ["monitors", monitorId, "uptime"],
        queryFn: () => api.getMonitorUptime(monitorId),
        refetchInterval: 60_000,
    });

    const { data: incidents } = useQuery({
        queryKey: ["monitors", monitorId, "incidents"],
        queryFn: () => api.getMonitorIncidents(monitorId),
        refetchInterval: 60_000,
    });

    const { mutate: deleteMonitor, isPending: isDeleting } = useMutation({
        mutationFn: () => api.deleteMonitor(monitorId),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["monitors"] });
            router.push("/monitors");
        },
    });

    const { mutate: toggleEnabled } = useMutation({
        mutationFn: (enabled: boolean) => api.updateMonitor(monitorId, { enabled }),
        onSuccess: () => queryClient.invalidateQueries({ queryKey: ["monitors", monitorId] }),
    });

    if (isLoading) {
        return (
            <div className="flex h-full items-center justify-center">
                <div className="h-8 w-8 animate-spin rounded-full border-2 border-border border-t-accent" />
            </div>
        );
    }

    if (!monitor) {
        return (
            <div className="p-8">
                <div className="rounded-lg border border-danger/30 bg-danger/10 p-4 text-danger">Monitor not found.</div>
            </div>
        );
    }

    const all = rollups ?? [];
    const last24 = all.slice(-24);

    return (
        <div className="p-8">
            <div className="mb-6 flex items-start justify-between">
                <div>
                    <Link href="/monitors" className="text-sm text-text-secondary hover:text-text-primary">
                        ← Monitors
                    </Link>
                    <div className="mt-2 flex items-center gap-3">
                        <h1 className="text-2xl font-bold text-text-primary">{monitor.name}</h1>
                        <Badge variant={statusVariant(monitor.state.status)}>{monitor.state.status}</Badge>
                        <Badge variant="neutral">{monitor.type}</Badge>
                        {!monitor.enabled && <Badge variant="warning">disabled</Badge>}
                    </div>
                    {monitor.state.message && <p className="mt-1 text-sm text-text-secondary">{monitor.state.message}</p>}
                </div>
                <div className="flex gap-2">
                    <Link href={`/monitors/${monitorId}/edit`}>
                        <Button variant="secondary">Edit</Button>
                    </Link>
                    <Button variant="secondary" onClick={() => toggleEnabled(!monitor.enabled)}>
                        {monitor.enabled ? "Disable" : "Enable"}
                    </Button>
                    {!confirmDelete ? (
                        <Button variant="danger" onClick={() => setConfirmDelete(true)}>
                            Delete
                        </Button>
                    ) : (
                        <div className="flex items-center gap-2">
                            <span className="text-sm text-danger">Are you sure?</span>
                            <Button variant="danger" loading={isDeleting} onClick={() => deleteMonitor()}>
                                Confirm
                            </Button>
                            <Button variant="ghost" onClick={() => setConfirmDelete(false)}>
                                Cancel
                            </Button>
                        </div>
                    )}
                </div>
            </div>

            <div className="mb-6 grid grid-cols-2 gap-4 sm:grid-cols-4">
                <Card>
                    <p className="text-xs text-text-secondary">Uptime (24h)</p>
                    <p className="mt-1 text-2xl font-bold text-text-primary">{uptimePct(last24).toFixed(1)}%</p>
                </Card>
                <Card>
                    <p className="text-xs text-text-secondary">Uptime (30d)</p>
                    <p className="mt-1 text-2xl font-bold text-text-primary">{uptimePct(all).toFixed(1)}%</p>
                </Card>
                <Card>
                    <p className="text-xs text-text-secondary">Latency</p>
                    <p className="mt-1 text-2xl font-bold text-text-primary">{monitor.state.latency_ms}ms</p>
                </Card>
                <Card>
                    <p className="text-xs text-text-secondary">Cert expiry</p>
                    <p className="mt-1 text-sm font-medium text-text-primary">{monitor.state.cert_expiry_at ? new Date(monitor.state.cert_expiry_at).toLocaleDateString() : "n/a"}</p>
                </Card>
            </div>

            <Card className="mb-6">
                <CardHeader>
                    <CardTitle>Heartbeat (last 48h)</CardTitle>
                </CardHeader>
                <Heartbeat rollups={all} />
            </Card>

            <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
                <Card padding={false}>
                    <div className="border-b border-border px-6 py-4">
                        <h2 className="text-lg font-semibold text-text-primary">Incidents</h2>
                    </div>
                    {!incidents || incidents.length === 0 ? (
                        <div className="py-12 text-center text-sm text-text-secondary">No incidents recorded.</div>
                    ) : (
                        <Table>
                            <Thead>
                                <Tr>
                                    <Th>Started</Th>
                                    <Th>Resolved</Th>
                                    <Th>Cause</Th>
                                </Tr>
                            </Thead>
                            <Tbody>
                                {incidents.map((inc) => (
                                    <Tr key={inc.incident_id}>
                                        <Td>
                                            <span className="text-xs text-text-secondary">{new Date(inc.started_at).toLocaleString()}</span>
                                        </Td>
                                        <Td>
                                            {inc.resolved_at ? (
                                                <span className="text-xs text-text-secondary">{new Date(inc.resolved_at).toLocaleString()}</span>
                                            ) : (
                                                <Badge variant="danger">ongoing</Badge>
                                            )}
                                        </Td>
                                        <Td>
                                            <span className="text-xs text-text-primary">{inc.cause || "n/a"}</span>
                                        </Td>
                                    </Tr>
                                ))}
                            </Tbody>
                        </Table>
                    )}
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle>Configuration</CardTitle>
                    </CardHeader>
                    <dl className="space-y-3 text-sm">
                        <div>
                            <dt className="text-text-secondary">Runner</dt>
                            <dd className="mt-0.5 font-mono text-text-primary">{monitor.runner}</dd>
                        </div>
                        <div className="border-t border-border pt-3">
                            <dt className="text-text-secondary">Interval</dt>
                            <dd className="mt-0.5 text-text-primary">{monitor.interval_sec}s</dd>
                        </div>
                        <div className="border-t border-border pt-3">
                            <dt className="text-text-secondary">Retries before down</dt>
                            <dd className="mt-0.5 text-text-primary">{monitor.retries}</dd>
                        </div>
                        <div className="border-t border-border pt-3">
                            <dt className="text-text-secondary">Target</dt>
                            <dd className="mt-0.5 font-mono text-xs text-text-primary break-all">
                                {monitor.target.url || `${monitor.target.host ?? ""}${monitor.target.port ? `:${monitor.target.port}` : ""}`}
                            </dd>
                        </div>
                    </dl>
                </Card>
            </div>
        </div>
    );
}
