import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { Card, DateText, Mono, PageHeader, PhoneText, Stat } from "@/components/pbps/page";
import {
  DetailSkeleton,
  EmptyState,
  ErrorState,
  KpiGridSkeleton,
  TableSkeleton,
} from "@/components/pbps/states";
import { StatusBadge } from "@/components/pbps/status-badge";
import { KpiCard, ProgressRing, TargetBar } from "@/components/pbps/kpi";
import { DataTable } from "@/components/pbps/data-table";
import { JobProgress } from "@/components/pbps/job-progress";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { fmtInt, fmtPct, relativeTime } from "@/lib/format";
import { useAccess, useCan } from "@/lib/access";
import { cn } from "@/lib/utils";

import { listNotifications, markAllRead, markRead } from "@/api/ops";
import { AlertTriangle, Bell, Info } from "lucide-react";
export const Route = createFileRoute("/p/$pid/notifications")({ component: Page });
function Page() {
  const qc = useQueryClient();
  const navigate = useNavigate();
  const [unread, setUnread] = useState(false);
  const q = useQuery({ queryKey: ["notifications"], queryFn: listNotifications });
  const inv = () => void qc.invalidateQueries({ queryKey: ["notifications"] });
  const toggle = useMutation({
    mutationFn: ({ id, read }: { id: string; read: boolean }) => markRead(id, read),
    onSettled: inv,
  });
  const all = useMutation({
    mutationFn: markAllRead,
    onSuccess: () => {
      toast.success("All marked as read");
      inv();
    },
  });
  const rows = (q.data ?? []).filter((n) => !unread || !n.readAt);
  return (
    <>
      <PageHeader
        title="Notifications"
        actions={
          <>
            <Button variant={unread ? "default" : "outline"} onClick={() => setUnread((u) => !u)}>
              Unread only
            </Button>
            <Button variant="outline" onClick={() => all.mutate()}>
              Mark all read
            </Button>
          </>
        }
      />
      {q.isPending ? (
        <TableSkeleton rows={6} cols={2} />
      ) : q.isError ? (
        <ErrorState error={q.error} />
      ) : rows.length === 0 ? (
        <EmptyState
          icon={Bell}
          title="You are up to date"
          text="We will let you know when something needs your attention."
        />
      ) : (
        <Card padded={false}>
          <ul>
            {rows.map((n) => {
              const I =
                n.severity === "critical"
                  ? AlertTriangle
                  : n.severity === "warning"
                    ? AlertTriangle
                    : Info;
              return (
                <li
                  key={n.id}
                  className={cn(
                    "flex items-start gap-3 border-b px-4 py-3 last:border-0",
                    !n.readAt && "bg-primary-soft/40",
                  )}
                >
                  <I
                    className={cn(
                      "mt-0.5 h-4 w-4 shrink-0",
                      n.severity === "critical"
                        ? "text-danger"
                        : n.severity === "warning"
                          ? "text-warning"
                          : "text-info",
                    )}
                  />
                  <div className="min-w-0 flex-1">
                    {n.link ? (
                      <a
                        href={n.link}
                        className="font-medium text-primary hover:underline"
                        onClick={(e) => {
                          e.preventDefault();
                          if (!n.readAt) toggle.mutate({ id: n.id, read: true });
                          void navigate({ href: n.link! });
                        }}
                      >
                        {n.title}
                      </a>
                    ) : (
                      <p className="font-medium">{n.title}</p>
                    )}
                    {n.body && <p className="text-muted-foreground">{n.body}</p>}
                    <p className="text-[11px] text-subtle">{relativeTime(n.createdAt)}</p>
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => toggle.mutate({ id: n.id, read: !n.readAt })}
                  >
                    {n.readAt ? "Mark unread" : "Mark read"}
                  </Button>
                </li>
              );
            })}
          </ul>
        </Card>
      )}
    </>
  );
}
