"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { apiPost } from "@/lib/client-api";

interface CrawlSummary {
  id: string;
  status: string;
  pagesCrawled: number;
  pagesFailed: number;
  pagesQueued: number;
  pageLimit: number;
  startedAt: string | null;
  finishedAt: string | null;
  createdAt: string;
  error: string | null;
}

interface IssueSummary {
  id: string;
  type: string;
  severity: string;
  url: string;
  explanation: string;
  recommendedFix: string | null;
}

const SEVERITY_STYLES: Record<string, string> = {
  CRITICAL: "bg-red-600 text-white",
  HIGH: "bg-red-100 text-red-800",
  MEDIUM: "bg-amber-100 text-amber-800",
  LOW: "bg-slate-100 text-slate-700",
  INFORMATIONAL: "bg-blue-50 text-blue-700",
};

export function CrawlPanel({
  websiteId,
  isVerified,
  initialCrawls,
  issueCounts,
  topIssues,
}: {
  websiteId: string;
  isVerified: boolean;
  initialCrawls: CrawlSummary[];
  issueCounts: Record<string, number>;
  topIssues: IssueSummary[];
}) {
  const router = useRouter();
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const latest = initialCrawls[0] ?? null;
  const active = latest && ["QUEUED", "RUNNING"].includes(latest.status);

  // Poll while a crawl is active so progress updates live.
  useEffect(() => {
    if (!active) return;
    const interval = setInterval(() => router.refresh(), 4000);
    return () => clearInterval(interval);
  }, [active, router]);

  async function startCrawl() {
    setBusy(true);
    setError(null);
    const result = await apiPost(`/api/websites/${websiteId}/crawls`, {});
    setBusy(false);
    if (result.ok) router.refresh();
    else setError(result.error);
  }

  async function cancelCrawl(crawlId: string) {
    setBusy(true);
    const result = await apiPost(`/api/crawls/${crawlId}/cancel`, {});
    setBusy(false);
    if (result.ok) router.refresh();
    else setError(result.error);
  }

  return (
    <section className="space-y-6">
      <div className="rounded-xl border border-slate-200 bg-white p-6">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <h2 className="font-semibold">Site crawl</h2>
            <p className="mt-1 text-sm text-slate-500">
              {isVerified
                ? "Crawl your site to find technical SEO issues."
                : "You can crawl before verifying, but verification unlocks publishing fixes later."}
            </p>
          </div>
          {active ? (
            <button
              type="button"
              disabled={busy}
              onClick={() => cancelCrawl(latest.id)}
              className="rounded-lg border border-red-300 px-4 py-2 text-sm font-medium text-red-700 hover:bg-red-50 disabled:opacity-50"
            >
              Cancel crawl
            </button>
          ) : (
            <button
              type="button"
              disabled={busy}
              onClick={startCrawl}
              className="rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-700 disabled:opacity-50"
            >
              {busy ? "Starting…" : "Start crawl"}
            </button>
          )}
        </div>
        {error && <p className="mt-3 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">{error}</p>}

        {latest && (
          <div className="mt-4 rounded-lg bg-slate-50 p-4 text-sm">
            <p>
              <span className="font-medium">Latest crawl:</span> {latest.status.toLowerCase()}
              {active && (
                <span className="ml-2 inline-block h-2 w-2 animate-pulse rounded-full bg-blue-500 align-middle" />
              )}
            </p>
            <p className="mt-1 text-slate-600">
              {latest.pagesCrawled} pages crawled · {latest.pagesFailed} failed ·{" "}
              {latest.pagesQueued} queued · limit {latest.pageLimit}
            </p>
            {latest.error && <p className="mt-1 text-red-700">{latest.error}</p>}
          </div>
        )}
      </div>

      {latest && latest.status === "COMPLETED" && (
        <div className="rounded-xl border border-slate-200 bg-white p-6">
          <h2 className="font-semibold">Issues found</h2>
          {Object.keys(issueCounts).length === 0 ? (
            <p className="mt-2 text-sm text-slate-500">
              No issues detected in the latest crawl. Nice work.
            </p>
          ) : (
            <>
              <div className="mt-3 flex flex-wrap gap-2">
                {Object.entries(issueCounts).map(([severity, count]) => (
                  <span
                    key={severity}
                    className={`rounded-full px-3 py-1 text-xs font-medium ${SEVERITY_STYLES[severity] ?? ""}`}
                  >
                    {severity.toLowerCase()}: {count}
                  </span>
                ))}
              </div>
              <ul className="mt-4 divide-y divide-slate-100">
                {topIssues.map((issue) => (
                  <li key={issue.id} className="py-3">
                    <div className="flex items-start gap-3">
                      <span
                        className={`mt-0.5 shrink-0 rounded-full px-2 py-0.5 text-[10px] font-medium ${SEVERITY_STYLES[issue.severity] ?? ""}`}
                      >
                        {issue.severity.toLowerCase()}
                      </span>
                      <div className="min-w-0">
                        <p className="text-sm font-medium">
                          {issue.type.toLowerCase().replace(/_/g, " ")}
                        </p>
                        <p className="truncate text-xs text-slate-500">{issue.url}</p>
                        <p className="mt-1 text-sm text-slate-600">{issue.explanation}</p>
                        {issue.recommendedFix && (
                          <p className="mt-1 text-sm text-slate-500">
                            <span className="font-medium">Fix:</span> {issue.recommendedFix}
                          </p>
                        )}
                      </div>
                    </div>
                  </li>
                ))}
              </ul>
            </>
          )}
        </div>
      )}
    </section>
  );
}
