"use client";

import { AlertTriangle, CheckCircle2 } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { cn } from "@/lib/utils";

interface ScheduleCheck {
  ok: boolean;
  label: string;
  detail: string;
}

interface ScheduleReadinessBannerProps {
  projectId: string | undefined;
  className?: string;
}

const INFO_LABELS = new Set(["Content queued for schedule", "Current time slot"]);

export function ScheduleReadinessBanner({ projectId, className }: ScheduleReadinessBannerProps) {
  const [checks, setChecks] = useState<ScheduleCheck[]>([]);
  const [ready, setReady] = useState<boolean | null>(null);
  const [plannedSlots, setPlannedSlots] = useState<string[]>([]);
  const [queuedCount, setQueuedCount] = useState(0);

  useEffect(() => {
    if (!projectId) return;

    void fetch(`/api/scheduling/diagnostics?projectId=${encodeURIComponent(projectId)}`)
      .then((res) => (res.ok ? res.json() : null))
      .then(
        (data: {
          projects?: Array<{
            ready: boolean;
            checks: ScheduleCheck[];
            plannedSlots: string[];
            queuedCount?: number;
          }>;
        }) => {
          const project = data?.projects?.[0];
          if (!project) return;
          setReady(project.ready);
          setChecks(project.checks);
          setPlannedSlots(project.plannedSlots ?? []);
          setQueuedCount(project.queuedCount ?? 0);
        },
      )
      .catch(() => {
        // ignore
      });
  }, [projectId]);

  if (ready === null) return null;

  const blocking = checks.filter((c) => !c.ok && !INFO_LABELS.has(c.label));
  const loopCheck = checks.find((c) => c.label === "Loop sequence");
  const loopOn = loopCheck?.ok !== false;
  const infoChecks = checks.filter((c) => INFO_LABELS.has(c.label));

  if (ready && blocking.length === 0) {
    return (
      <div
        className={cn(
          "mb-4 rounded-lg border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-900",
          className,
        )}
      >
        <div className="flex items-start gap-2">
          <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0" />
          <div>
            <p className="font-semibold">
              {queuedCount > 0 ? "Post queued for auto-publish" : "Auto-publish is armed"}
            </p>
            <p className="mt-1 text-green-800">
              {queuedCount > 0 ? (
                <>
                  <strong>{queuedCount}</strong> post(s) waiting — cron publishes at the next slot (
                  {plannedSlots.join(" · ") || "see Smart Schedule"}). No approve step.
                </>
              ) : loopOn ? (
                <>
                  <strong>Loop Post Sequence is ON.</strong> At{" "}
                  {plannedSlots.join(" · ") || "your morning/evening slots"}, cron will
                  auto-generate and publish directly. Optional:{" "}
                  <Link href="/live-generation" className="font-medium underline">
                    Generate Now
                  </Link>{" "}
                  to queue a draft early.
                </>
              ) : (
                <>
                  Turn ON{" "}
                  <Link href="/automation" className="font-medium underline">
                    Loop Post Sequence
                  </Link>{" "}
                  in Automation so cron can generate + publish at slot time.
                </>
              )}
            </p>
            {infoChecks.length > 0 && (
              <ul className="mt-2 space-y-1 text-xs text-green-800">
                {infoChecks.map((c) => (
                  <li key={c.label}>
                    <strong>{c.label}:</strong> {c.detail}
                  </li>
                ))}
              </ul>
            )}
          </div>
        </div>
      </div>
    );
  }

  const failed = checks.filter((c) => !c.ok);

  return (
    <div
      className={cn(
        "mb-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-950",
        className,
      )}
    >
      <div className="flex items-start gap-2">
        <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
        <div>
          <p className="font-semibold">Complete setup for auto-publish</p>
          <p className="mt-1 text-amber-900">
            Fix the items below. To enable auto-generate + direct publish: open{" "}
            <Link href="/automation" className="font-semibold underline">
              Automation
            </Link>{" "}
            → turn <strong>Loop Post Sequence</strong> ON (toggle switches on automatically).
          </p>
          <ul className="mt-3 space-y-1.5 text-xs text-amber-900">
            {failed.map((c) => (
              <li key={c.label}>
                <strong>{c.label}:</strong> {c.detail}
                {c.label === "Loop sequence" && (
                  <>
                    {" "}
                    →{" "}
                    <Link href="/automation" className="font-medium underline">
                      Open Automation
                    </Link>
                  </>
                )}
                {c.label === "Posting context" && (
                  <>
                    {" "}
                    →{" "}
                    <Link href="/posting-context" className="font-medium underline">
                      Posting Context
                    </Link>
                  </>
                )}
                {c.label === "Schedule saved" && (
                  <>
                    {" "}
                    →{" "}
                    <Link href="/smart-schedule" className="font-medium underline">
                      Smart Schedule
                    </Link>
                  </>
                )}
                {c.label === "Connected accounts" && (
                  <>
                    {" "}
                    →{" "}
                    <Link href="/connected-accounts" className="font-medium underline">
                      Connected Accounts
                    </Link>
                  </>
                )}
              </li>
            ))}
          </ul>
          <p className="mt-2 text-xs text-amber-800">
            After setup: wait for the next slot, or{" "}
            <Link href="/live-generation" className="font-medium underline">
              Generate Now
            </Link>{" "}
            — drafts publish with no approve step.
          </p>
        </div>
      </div>
    </div>
  );
}
