"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { ArrowUpRight, CheckCircle2, Circle, ListChecks, RefreshCw } from "lucide-react";
import Panel from "./Panel";

interface SetupCheck {
  id: string;
  label: string;
  ok: boolean;
  optional: boolean;
  fix: string;
  guide: string | null;
}

interface SetupStatus {
  ok: boolean;
  checks: SetupCheck[];
}

type LoadState = "loading" | "ready" | "error";

// SetupChecklist — "Getting Started" on the Home dashboard. Mirrors the
// double-clickable Check My Setup.command, but live in the app: each missing
// power shows a one-line fix and deep-links its install guide.
export default function SetupChecklist() {
  const [state, setState] = useState<LoadState>("loading");
  const [checks, setChecks] = useState<SetupCheck[]>([]);
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    setRefreshing(true);
    try {
      const r = await fetch("/api/home/setup-status", { cache: "no-store" });
      const j: SetupStatus = await r.json();
      if (Array.isArray(j.checks) && j.checks.length > 0) {
        setChecks(j.checks);
        setState("ready");
      } else {
        setState("error");
      }
    } catch {
      setState("error");
    } finally {
      setRefreshing(false);
    }
  }, []);

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

  const done = checks.filter((c) => c.ok).length;
  const pct = checks.length > 0 ? Math.round((done / checks.length) * 100) : 0;

  return (
    <Panel
      title="Getting Started"
      accent="system"
      icon={<ListChecks size={14} />}
      actions={
        <div className="flex items-center gap-2">
          {state === "ready" && (
            <span className="pill pill-info">{done}/{checks.length} connected</span>
          )}
          <button
            onClick={load}
            title="Re-check my setup"
            aria-label="Re-check my setup"
            className="focus-ring grid place-items-center w-7 h-7 rounded-md transition-colors text-[var(--cream-mute)] hover:text-[var(--cream)]"
          >
            <RefreshCw size={13} className={refreshing ? "animate-spin" : ""} />
          </button>
        </div>
      }
    >
      {state === "loading" && (
        <div className="space-y-3" aria-label="Checking your setup">
          {[0, 1, 2, 3, 4].map((i) => <div key={i} className="skeleton h-9" />)}
        </div>
      )}

      {state === "error" && (
        <div className="py-6 text-center">
          <p className="text-[13px]" style={{ color: "var(--cream-dim)" }}>
            Could not run the setup check just now.
          </p>
          <button onClick={load} className="copy-btn focus-ring mt-4">Try again</button>
        </div>
      )}

      {state === "ready" && (
        <div>
          <div className="flex items-center gap-3 mb-4">
            <div className="pbar flex-1"><div className="fill" style={{ width: `${pct}%` }} /></div>
            <span className="pbar-value">{pct}%</span>
          </div>

          <ul className="space-y-1">
            {checks.map((c) => (
              <li
                key={c.id}
                className="rounded-md px-2.5 py-2 border border-transparent transition-colors"
                style={{ background: c.ok ? "transparent" : "color-mix(in srgb, var(--cream) 2%, transparent)" }}
              >
                <div className="flex items-center gap-2.5">
                  {c.ok ? (
                    <CheckCircle2 size={15} className="shrink-0" style={{ color: "var(--emerald)" }} aria-label="Connected" />
                  ) : (
                    <Circle size={15} className="shrink-0" style={{ color: "var(--cream-mute)" }} aria-label="Not connected yet" />
                  )}
                  <span className="text-[13.5px] flex-1 min-w-0 truncate" style={{ color: c.ok ? "var(--cream)" : "var(--cream-soft)" }}>
                    {c.label}
                  </span>
                  {!c.ok && c.optional && (
                    <span className="action-tag shrink-0" style={{ fontSize: "0.6rem" }}>optional</span>
                  )}
                </div>
                {!c.ok && (
                  <div className="mt-1 pl-[26px] text-[12px] leading-relaxed" style={{ color: "var(--cream-dim)" }}>
                    {c.fix}
                    {c.guide && (
                      <>
                        {" "}
                        <Link
                          href={`/setup-guide/${encodeURIComponent(c.guide)}`}
                          className="focus-ring inline-flex items-center gap-0.5 font-semibold hover:underline underline-offset-2"
                          style={{ color: "var(--gold)" }}
                        >
                          Open the guide <ArrowUpRight size={11} />
                        </Link>
                      </>
                    )}
                  </div>
                )}
              </li>
            ))}
          </ul>

          <p className="mt-4 text-[11px] leading-relaxed" style={{ color: "var(--cream-mute)" }}>
            Grey circles are optional powers, not problems. Add them whenever you are ready.
          </p>
        </div>
      )}
    </Panel>
  );
}
