"use client";

import { useEffect, useState } from "react";
import type { ReadinessReport, ReadinessStatus } from "@/lib/production-readiness";

const statusLabels: Record<ReadinessStatus, string> = {
  ready: "Ready",
  warning: "Review",
  blocked: "Blocked",
};

const statusClass: Record<ReadinessStatus, string> = {
  ready: "bg-[#e7f4ec] text-[#1f6f43]",
  warning: "bg-[#fff4d6] text-[#8a6500]",
  blocked: "bg-[#f8e4e6] text-[#8a2730]",
};

export function AdminReadiness() {
  const [report, setReport] = useState<ReadinessReport | null>(null);
  const [loading, setLoading] = useState(true);

  async function loadReport() {
    setLoading(true);
    const response = await fetch("/api/admin/readiness", { cache: "no-store" });
    const data = (await response.json()) as ReadinessReport;
    setReport(data);
    setLoading(false);
  }

  useEffect(() => {
    let active = true;

    async function loadInitialReport() {
      const response = await fetch("/api/admin/readiness", { cache: "no-store" });
      const data = (await response.json()) as ReadinessReport;

      if (active) {
        setReport(data);
        setLoading(false);
      }
    }

    void loadInitialReport();

    return () => {
      active = false;
    };
  }, []);

  const groupedChecks =
    report?.checks.reduce<Record<string, typeof report.checks>>((groups, item) => {
      groups[item.group] ??= [];
      groups[item.group].push(item);
      return groups;
    }, {}) ?? {};

  return (
    <div className="mt-8 rounded-lg border border-[#d9d0bf] bg-white p-6 shadow-sm">
      <div className="flex flex-col justify-between gap-3 border-b border-[#d9d0bf] pb-5 sm:flex-row sm:items-center">
        <div>
          <h2 className="text-2xl font-semibold text-[#274739]">Production readiness</h2>
          <p className="mt-1 text-sm text-[#5e675f]">Provider, secret, payment, cron, database, and media checks.</p>
        </div>
        <button
          type="button"
          onClick={() => void loadReport()}
          className="rounded-full bg-[#274739] px-4 py-2 text-sm font-semibold text-white"
        >
          {loading ? "Checking..." : "Refresh"}
        </button>
      </div>

      {report ? (
        <>
          <div className="mt-5 grid gap-3 sm:grid-cols-4">
            <div className={`rounded-lg px-4 py-3 ${statusClass[report.status]}`}>
              <p className="text-xs font-bold uppercase tracking-[0.14em]">Overall</p>
              <p className="mt-1 text-2xl font-semibold">{statusLabels[report.status]}</p>
            </div>
            <div className="rounded-lg bg-[#e7f4ec] px-4 py-3 text-[#1f6f43]">
              <p className="text-xs font-bold uppercase tracking-[0.14em]">Ready</p>
              <p className="mt-1 text-2xl font-semibold">{report.readyCount}</p>
            </div>
            <div className="rounded-lg bg-[#fff4d6] px-4 py-3 text-[#8a6500]">
              <p className="text-xs font-bold uppercase tracking-[0.14em]">Review</p>
              <p className="mt-1 text-2xl font-semibold">{report.warningCount}</p>
            </div>
            <div className="rounded-lg bg-[#f8e4e6] px-4 py-3 text-[#8a2730]">
              <p className="text-xs font-bold uppercase tracking-[0.14em]">Blocked</p>
              <p className="mt-1 text-2xl font-semibold">{report.blockedCount}</p>
            </div>
          </div>

          <div className="mt-6 grid gap-4 lg:grid-cols-2">
            {Object.entries(groupedChecks).map(([group, checks]) => (
              <section key={group} className="rounded-lg border border-[#d9d0bf] bg-[#f7f3ea] p-5">
                <h3 className="text-lg font-semibold text-[#274739]">{group}</h3>
                <div className="mt-3 divide-y divide-[#d9d0bf]">
                  {checks.map((item) => (
                    <article key={item.id} className="py-4 first:pt-0 last:pb-0">
                      <div className="flex flex-wrap items-center justify-between gap-2">
                        <h4 className="font-semibold text-[#17211c]">{item.label}</h4>
                        <span className={`rounded-full px-3 py-1 text-xs font-bold uppercase tracking-[0.12em] ${statusClass[item.status]}`}>
                          {statusLabels[item.status]}
                        </span>
                      </div>
                      <p className="mt-2 text-sm text-[#5e675f]">{item.detail}</p>
                      {item.status !== "ready" ? <p className="mt-2 text-sm font-semibold text-[#274739]">{item.action}</p> : null}
                    </article>
                  ))}
                </div>
              </section>
            ))}
          </div>
        </>
      ) : (
        <p className="py-6 text-sm text-[#5e675f]">Checking production readiness...</p>
      )}
    </div>
  );
}
