"use client";

import { useState } from "react";
import type { SeoSection } from "@/lib/audit/types";

interface Props {
  prioritizedFindings: NonNullable<SeoSection["prioritizedFindings"]>;
  priorityActions: SeoSection["priorityActions"];
}

const PRIORITY_COLORS: Record<string, string> = {
  critical: "text-red-400 bg-red-900/30 border-red-500/40",
  high: "text-amber-400 bg-amber-900/30 border-amber-500/40",
  medium: "text-yellow-400 bg-yellow-900/30 border-yellow-500/40",
  low: "text-slate-400 bg-slate-700/30 border-slate-600/40",
};

const EFFORT_COLORS: Record<string, string> = {
  hour: "text-emerald-400",
  day: "text-amber-400",
  week: "text-orange-400",
};

function CodeBlock({ code }: { code: string }) {
  const [copied, setCopied] = useState(false);

  const handleCopy = async () => {
    await navigator.clipboard.writeText(code);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="relative mt-2 rounded-lg bg-slate-950 border border-white/10 overflow-hidden">
      <button
        onClick={handleCopy}
        className="absolute top-2 right-2 text-[10px] text-slate-400 hover:text-white bg-slate-800 hover:bg-slate-700 border border-white/10 px-2 py-0.5 rounded transition-colors"
      >
        {copied ? "Copied!" : "Copy"}
      </button>
      <pre className="text-[11px] text-slate-300 p-3 pr-16 overflow-x-auto leading-relaxed font-mono whitespace-pre-wrap">
        {code}
      </pre>
    </div>
  );
}

function extractCodeBlocks(text: string): Array<{ before: string; code: string }> {
  const results: Array<{ before: string; code: string }> = [];
  // Match ```...``` or indented JSON/HTML blocks
  const fenceRegex = /```(?:json|html|javascript|js)?\n([\s\S]*?)```/g;
  let match;
  while ((match = fenceRegex.exec(text)) !== null) {
    results.push({ before: text.slice(0, match.index).trim(), code: match[1].trim() });
  }
  return results;
}

export function ImplementationAppendixSection({ prioritizedFindings, priorityActions }: Props) {
  const [expandedIdx, setExpandedIdx] = useState<number | null>(null);

  // Only show findings with recommendedNextSteps that contain code artifacts
  const actionsWithCode = priorityActions.filter((a) =>
    /```|{\s*"@context"/i.test(a.rationale + " " + a.title),
  );

  return (
    <div className="rounded-2xl bg-slate-900/60 border border-white/10 overflow-hidden">
      <div className="px-6 py-5 border-b border-white/10">
        <h3 className="text-sm font-semibold text-slate-100">Implementation Appendix</h3>
        <p className="text-xs text-slate-400 mt-0.5">Step-by-step implementation guide with copy-paste artifacts</p>
      </div>

      <div className="divide-y divide-white/10">
        {prioritizedFindings.map((f, idx) => {
          const isOpen = expandedIdx === idx;
          const codeBlocks = f.recommendedNextSteps.flatMap(extractCodeBlocks);
          return (
            <div key={f.rank}>
              <button
                className="w-full px-6 py-4 flex items-center gap-3 text-left hover:bg-white/5 transition-colors"
                onClick={() => setExpandedIdx(isOpen ? null : idx)}
              >
                <span className={`text-[10px] font-semibold px-2 py-0.5 rounded-full border ${PRIORITY_COLORS[f.priority] ?? PRIORITY_COLORS.low}`}>
                  {f.priority.charAt(0).toUpperCase() + f.priority.slice(1)}
                </span>
                <span className="text-sm text-slate-200 flex-1">{f.title}</span>
                <svg
                  className={`w-4 h-4 text-slate-500 shrink-0 transition-transform ${isOpen ? "rotate-180" : ""}`}
                  fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}
                >
                  <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
                </svg>
              </button>

              {isOpen && (
                <div className="px-6 pb-5 space-y-4">
                  {f.affectedUrls && f.affectedUrls.length > 0 && (
                    <div>
                      <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">Affected pages</p>
                      <ul className="space-y-1">
                        {f.affectedUrls.map((url) => (
                          <li key={url} className="text-xs font-mono text-slate-400">{url}</li>
                        ))}
                      </ul>
                    </div>
                  )}

                  <div>
                    <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-2">Next steps</p>
                    <ol className="space-y-2.5 list-decimal list-inside">
                      {f.recommendedNextSteps.map((step, si) => {
                        const blocks = extractCodeBlocks(step);
                        const textPart = blocks.length > 0 ? step.slice(0, step.indexOf("```")).trim() : step;
                        return (
                          <li key={si} className="text-xs text-slate-300 leading-relaxed">
                            {textPart}
                            {blocks.map((b, bi) => <CodeBlock key={bi} code={b.code} />)}
                          </li>
                        );
                      })}
                    </ol>
                  </div>

                  {codeBlocks.length > 0 && (
                    <div>
                      <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">Code artifacts</p>
                      {codeBlocks.map((b, bi) => <CodeBlock key={bi} code={b.code} />)}
                    </div>
                  )}
                </div>
              )}
            </div>
          );
        })}

        {/* Priority actions with code */}
        {actionsWithCode.length > 0 && prioritizedFindings.length > 0 && (
          <div className="px-6 py-5">
            <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-3">Priority actions with implementation artifacts</p>
            <div className="space-y-4">
              {actionsWithCode.map((a, i) => {
                const blocks = extractCodeBlocks(a.rationale);
                return (
                  <div key={i}>
                    <div className="flex items-center gap-2 mb-1">
                      <span className={`text-xs font-semibold ${EFFORT_COLORS[a.effort] ?? ""}`}>
                        {a.effort.charAt(0).toUpperCase() + a.effort.slice(1)}
                      </span>
                      <span className="text-xs text-slate-300">{a.title}</span>
                    </div>
                    {blocks.map((b, bi) => <CodeBlock key={bi} code={b.code} />)}
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
