import { StatusBadge } from "@minmon/ui/components/status-badge";
import { useQuery } from "@tanstack/react-query";
import { Link, createFileRoute } from "@tanstack/react-router";

import {
  PageSection,
  QueryStateCard,
  ResourceListCard,
  SectionLinks,
  SummaryCard,
} from "@/components/dashboard-ui";
import { trpc } from "@/utils/trpc";

export const Route = createFileRoute("/dashboard/")({
  component: RouteComponent,
});

function RouteComponent() {
  const summary = useQuery(trpc.dashboard.summary.queryOptions());

  if (summary.isLoading) {
    return (
      <QueryStateCard
        title="Loading dashboard summary"
        description="Fetching current counts, DNS check results, and recent notes."
      />
    );
  }

  if (summary.isError || !summary.data) {
    return (
      <QueryStateCard
        title="Dashboard summary unavailable"
        description="The overview could not be loaded from the protected dashboard API."
      />
    );
  }

  const { totals, domainChecks, inactiveServices, recentNotes, recentServiceIssues } = summary.data;

  return (
    <div className="grid gap-6">
      <PageSection
        title="Dashboard"
        description="Summary of servers, services, domains, DNS results, and maintenance items."
      >
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
          <SummaryCard
            label="Total servers"
            value={String(totals.servers)}
            hint="All managed private servers currently recorded in the system."
          />
          <SummaryCard
            label="Total services"
            value={String(totals.services)}
            hint="Applications or services attached to managed servers."
            status={
              inactiveServices > 0
                ? { label: `${inactiveServices} inactive/down`, variant: "warning" }
                : { label: "All active", variant: "success" }
            }
          />
          <SummaryCard
            label="Total domains"
            value={String(totals.domains)}
            hint="Domains and subdomains attached to services."
          />
          <SummaryCard
            label="DNS match results"
            value={String(domainChecks.match)}
            hint={`${domainChecks.mismatch} mismatch · ${domainChecks.unresolved} unresolved/error`}
            status={
              domainChecks.mismatch || domainChecks.unresolved
                ? { label: "Needs review", variant: "warning" }
                : { label: "Healthy", variant: "success" }
            }
          />
        </div>
      </PageSection>

      <PageSection title="Areas" description="Open each section to manage data and review detail pages.">
        <SectionLinks
          items={[
            { label: "Servers", to: "/dashboard/servers", detail: "Create, edit, delete, and inspect server records." },
            { label: "Services", to: "/dashboard/services", detail: "Manage services running on each server." },
            { label: "Domains", to: "/dashboard/domains", detail: "Check DNS and compare resolved IPs against expected IPs." },
            { label: "Notes", to: "/dashboard/notes", detail: "Write documentation and operational notes per server." },
          ]}
        />
      </PageSection>

      <PageSection title="Recent service issues" description="Services currently marked down or under maintenance.">
        <ResourceListCard
          title="Inactive or down services"
          description="These services affect the dashboard summary and should be reviewed first."
          columns={[
            {
              key: "name",
              header: "Service",
              render: (item: (typeof recentServiceIssues)[number]) => (
                <Link
                  to="/dashboard/services/$serviceId"
                  params={{ serviceId: item.id }}
                  className="font-medium hover:underline"
                >
                  {item.name}
                </Link>
              ),
            },
            {
              key: "serverName",
              header: "Server",
              render: (item: (typeof recentServiceIssues)[number]) => item.serverName,
            },
            {
              key: "status",
              header: "Status",
              className: "w-40",
              render: (item: (typeof recentServiceIssues)[number]) => (
                <StatusBadge variant={item.status === "down" ? "destructive" : "warning"}>
                  {item.status}
                </StatusBadge>
              ),
            },
          ]}
          items={recentServiceIssues}
          emptyTitle="No inactive services"
          emptyDescription="All services are currently marked active."
        />
      </PageSection>

      <PageSection title="Recent notes" description="Latest documentation updates that may help during demos or maintenance.">
        <ResourceListCard
          title="Recently updated notes"
          description="Recent server notes and internal documentation entries."
          columns={[
            {
              key: "title",
              header: "Title",
              render: (item: (typeof recentNotes)[number]) => (
                <Link
                  to="/dashboard/notes/$noteId"
                  params={{ noteId: item.id }}
                  className="font-medium hover:underline"
                >
                  {item.title}
                </Link>
              ),
            },
            {
              key: "category",
              header: "Category",
              render: (item: (typeof recentNotes)[number]) => item.category || "-",
            },
            {
              key: "updatedAt",
              header: "Updated",
              render: (item: (typeof recentNotes)[number]) =>
                item.updatedAt ? new Date(item.updatedAt).toLocaleString() : "-",
            },
          ]}
          items={recentNotes}
          emptyTitle="No recent notes"
          emptyDescription="Create a note from the Notes section to start documenting servers."
        />
      </PageSection>
    </div>
  );
}
