import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useMutation } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { useState } from "react";
import { CheckCircle2, XCircle, RefreshCw, Server, Copy } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { Badge } from "@/components/ui/badge";
import { systemInfo, systemHealthCheck } from "@/lib/install.functions";
import { siteUrl } from "@/lib/site";

export const Route = createFileRoute("/admin/system")({
  head: () => ({
    meta: [
      { title: "System Configuration — Billsline Admin" },
      { name: "description", content: "Check the health of the Billsline deployment: database, storage, providers and webhooks." },
      { property: "og:title", content: "System Configuration — Billsline Admin" },
      { property: "og:description", content: "Check the health of the Billsline deployment: database, storage, providers and webhooks." },
    ],
  }),
  component: SystemPage,
});

type Check = { ok: boolean; label: string; detail?: string };

function SystemPage() {
  const info = useServerFn(systemInfo);
  const health = useServerFn(systemHealthCheck);
  const [results, setResults] = useState<Check[] | null>(null);

  const { data, isPending } = useQuery({ queryKey: ["system-info"], queryFn: () => info() });

  const run = useMutation({
    mutationFn: () => health(),
    onSuccess: (r) => {
      setResults(r.results as Check[]);
      toast[r.ok ? "success" : "error"](r.ok ? "All systems healthy" : "Some checks failed");
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const base = siteUrl();
  const webhooks = [
    ["Paystack", `${base}/api/public/paystack-webhook`],
    ["Flutterwave", `${base}/api/public/flutterwave-webhook`],
  ];

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Server className="h-5 w-5 text-primary" />
          <h2 className="text-lg font-bold">System Configuration</h2>
        </div>
        <Button onClick={() => run.mutate()} disabled={run.isPending}>
          <RefreshCw className={run.isPending ? "mr-2 h-4 w-4 animate-spin" : "mr-2 h-4 w-4"} />
          Run health check
        </Button>
      </div>

      <Card>
        <CardHeader className="pb-2"><CardTitle className="text-sm">Deployment</CardTitle></CardHeader>
        <CardContent className="space-y-2 text-sm">
          {isPending ? (
            <Skeleton className="h-24 w-full" />
          ) : (
            <>
              <Row label="Site address" value={data?.siteUrl || base || "not set"} />
              <Row label="Database URL" value={data?.supabaseUrl || "not set"} />
              <Row label="Project reference" value={data?.projectRef || "not set"} />
              <Row label="Service role key" value={data?.hasServiceRole ? "present" : "missing"} ok={data?.hasServiceRole} />
              <Row label="Publishable key" value={data?.hasPublishableKey ? "present" : "missing"} ok={data?.hasPublishableKey} />
              <Row
                label="Installation"
                value={data?.installation?.installed ? `installed ${String(data.installation.installed_at ?? "")}` : "not recorded"}
                ok={!!data?.installation?.installed}
              />
              <div className="flex flex-wrap gap-2 pt-1">
                {Object.entries(data?.env ?? {}).map(([k, v]) => (
                  <Badge key={k} variant={v ? "default" : "outline"}>{k}: {v ? "env key set" : "from database"}</Badge>
                ))}
              </div>
            </>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="pb-2"><CardTitle className="text-sm">Webhook addresses</CardTitle></CardHeader>
        <CardContent className="space-y-2 text-sm">
          {webhooks.map(([name, url]) => (
            <div key={name} className="flex items-center justify-between gap-2 rounded-lg border p-2">
              <div className="min-w-0">
                <p className="text-xs text-muted-foreground">{name}</p>
                <p className="truncate font-mono text-xs">{url}</p>
              </div>
              <Button size="icon" variant="ghost" onClick={() => { void navigator.clipboard.writeText(url); toast.success("Copied"); }}>
                <Copy className="h-4 w-4" />
              </Button>
            </div>
          ))}
        </CardContent>
      </Card>

      {results && (
        <Card>
          <CardHeader className="pb-2"><CardTitle className="text-sm">Health check</CardTitle></CardHeader>
          <CardContent className="space-y-1">
            {results.map((r, i) => (
              <div key={`${r.label}-${i}`} className="flex items-start gap-2 rounded-md px-2 py-1.5 text-sm">
                {r.ok ? <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0 text-emerald-500" /> : <XCircle className="mt-0.5 h-4 w-4 shrink-0 text-destructive" />}
                <div className="min-w-0">
                  <p className="font-medium">{r.label}</p>
                  {r.detail && <p className="truncate text-xs text-muted-foreground">{r.detail}</p>}
                </div>
              </div>
            ))}
          </CardContent>
        </Card>
      )}
    </div>
  );
}

function Row({ label, value, ok }: { label: string; value: string; ok?: boolean }) {
  return (
    <div className="flex items-center justify-between gap-3 border-b py-1.5 last:border-0">
      <span className="text-muted-foreground">{label}</span>
      <span className={ok === false ? "truncate font-mono text-xs text-destructive" : "truncate font-mono text-xs"}>{value}</span>
    </div>
  );
}
