import { useCallback, useEffect, useState } from "react";
import { Link, createFileRoute } from "@tanstack/react-router";
import { Cloud, Loader2, RefreshCw, ShieldAlert } from "lucide-react";
import { Button } from "@/components/ui/button";
import { EmptyState, KpiCard, PageHeader, SectionCard } from "@/components/ledger/Primitives";
import { Pill } from "@/components/ledger/StatusBadge";
import { useAuthSession } from "@/hooks/useAuthSession";
import {
  fetchSnelStartConnectionsApi,
  type SnelStartConnectionsResponse,
} from "@/lib/api";
import { snelstartStatusLabel, snelstartStatusTone } from "@/lib/snelstart";

export const Route = createFileRoute("/settings/snelstart")({
  head: () => ({
    meta: [{ title: "SnelStart connection — Amanah" }],
  }),
  component: SnelStartConnectionPage,
});

function SnelStartConnectionPage() {
  const session = useAuthSession("firm");
  const [data, setData] = useState<SnelStartConnectionsResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    if (!session?.email) return;
    setLoading(true);
    setError(null);
    try {
      const next = await fetchSnelStartConnectionsApi({
        platform: "firm",
        email: session.email,
      });
      setData(next);
    } catch (err) {
      setData(null);
      setError(err instanceof Error ? err.message : "Unable to load SnelStart connection status.");
    } finally {
      setLoading(false);
    }
  }, [session?.email]);

  useEffect(() => {
    void load();
  }, [load]);

  const enabled = Boolean(data?.integrationEnabled);
  const reachable = data?.probe.reachable === true;
  const bannerTone = enabled
    ? reachable
      ? "border-success/25 bg-success-soft"
      : "border-attention/30 bg-attention-soft"
    : "border-border bg-surface";

  return (
    <div className="space-y-6">
      <PageHeader
        eyebrow="Configuration"
        title="SnelStart connection"
        subtitle="Live connection status from PostgreSQL and the configured SnelStart API."
        actions={
          <Button variant="outline" onClick={() => void load()} disabled={loading}>
            {loading ? <Loader2 size={16} className="animate-spin" /> : <RefreshCw size={16} />}
            Refresh
          </Button>
        }
      />

      {loading && !data ? (
        <div className="flex items-center gap-3 px-1 py-8 text-[13px] text-muted-foreground">
          <Loader2 size={16} className="animate-spin text-brand" aria-hidden="true" />
          Checking SnelStart connection...
        </div>
      ) : error ? (
        <SectionCard>
          <EmptyState
            icon={ShieldAlert}
            title="Unable to load SnelStart status"
            description={error}
            action={
              <Button variant="outline" onClick={() => void load()}>
                Try again
              </Button>
            }
          />
        </SectionCard>
      ) : data ? (
        <>
          <div className={`flex items-start gap-3 rounded-xl border px-4 py-3 ${bannerTone}`}>
            <Cloud size={18} className="mt-0.5 text-primary" aria-hidden="true" />
            <div className="min-w-0 flex-1">
              <p className="text-[13.5px] font-medium text-foreground">
                {enabled
                  ? reachable
                    ? "SnelStart API host is reachable"
                    : "SnelStart is configured, but the API host could not be reached"
                  : "SnelStart is not connected"}
              </p>
              <p className="mt-0.5 text-[13px] leading-6 text-muted-foreground">{data.probe.message}</p>
              <p className="mt-1 text-[12px] text-muted-foreground">
                {data.apiHost ? `Host: ${data.apiHost}` : "No API host configured"}
                {data.checkedAt ? ` · Checked ${data.checkedAt.replace("T", " ").replace("Z", " UTC")}` : ""}
              </p>
            </div>
            <Pill tone={enabled ? (reachable ? "green" : "amber") : "neutral"}>
              {enabled ? (reachable ? "Live" : "Unreachable") : "Not configured"}
            </Pill>
          </div>

          <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
            <KpiCard label="Administrations" value={data.counts.clients} hint="Clients in this workspace" icon={Cloud} />
            <KpiCard
              label="Connected"
              value={data.counts.connected}
              hint="Live SnelStart connection"
              icon={Cloud}
              tone={data.counts.connected > 0 ? "green" : "neutral"}
            />
            <KpiCard
              label="Pending"
              value={data.counts.pending}
              hint="Waiting to connect"
              icon={Cloud}
              tone={data.counts.pending > 0 ? "amber" : "neutral"}
            />
            <KpiCard
              label="Errors"
              value={data.counts.error}
              hint="Connection errors"
              icon={Cloud}
              tone={data.counts.error > 0 ? "danger" : "neutral"}
            />
          </div>

          <SectionCard title="Configuration" description="Which credentials are present (secrets are never shown)">
            <ul className="divide-y divide-border text-[13.5px]">
              <ConfigRow label="API base URL" ok={data.configured.apiBaseUrl} />
              <ConfigRow label="Client ID" ok={data.configured.clientId} />
              <ConfigRow label="Client secret" ok={data.configured.clientSecret} />
              <ConfigRow label="Redirect URI" ok={data.configured.redirectUri} />
            </ul>
          </SectionCard>

          <SectionCard title="Client connections" description="Live status per administration from PostgreSQL">
            {data.items.length === 0 ? (
              <EmptyState
                icon={Cloud}
                title="No clients yet"
                description="Add a client to see SnelStart connection status here."
              />
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full min-w-[720px] text-[13.5px]">
                  <thead className="border-b border-border bg-muted/50 text-[11.5px] tracking-wide text-muted-foreground uppercase">
                    <tr>
                      <th className="px-5 py-3 text-left font-semibold">Client</th>
                      <th className="px-4 py-3 text-left font-semibold">Status</th>
                      <th className="px-4 py-3 text-left font-semibold">Administration</th>
                      <th className="px-4 py-3 text-left font-semibold">Last sync</th>
                      <th className="px-5 py-3 text-left font-semibold">Last error</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {data.items.map((item) => (
                      <tr key={item.clientId} className="hover:bg-muted/50">
                        <td className="px-5 py-3">
                          <Link
                            to="/clients/$id"
                            params={{ id: item.clientId }}
                            className="font-medium hover:text-primary"
                          >
                            {item.clientName || item.clientId}
                          </Link>
                        </td>
                        <td className="px-4 py-3">
                          <Pill tone={snelstartStatusTone(item.isConnected ? "connected" : item.status)}>
                            {item.isConnected ? "Connected" : snelstartStatusLabel(item.status)}
                          </Pill>
                        </td>
                        <td className="px-4 py-3 text-muted-foreground">
                          {item.externalAdministrationId || "—"}
                        </td>
                        <td className="px-4 py-3 text-muted-foreground">
                          {item.lastSyncAt ? item.lastSyncAt.replace("T", " ").slice(0, 19) : "Never"}
                        </td>
                        <td className="max-w-[280px] truncate px-5 py-3 text-muted-foreground">
                          {item.lastSyncError || "—"}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </SectionCard>

          <p className="text-[12.5px] leading-6 text-muted-foreground">
            Invoice push and bank import stay disabled until a real SnelStart connection exists.
            This page does not invent a connected state.
          </p>
        </>
      ) : null}
    </div>
  );
}

function ConfigRow({ label, ok }: { label: string; ok: boolean }) {
  return (
    <li className="flex items-center justify-between gap-3 px-5 py-3">
      <span className="text-muted-foreground">{label}</span>
      <Pill tone={ok ? "green" : "neutral"}>{ok ? "Set" : "Not set"}</Pill>
    </li>
  );
}
