"use client";

import { useState } from "react";
import { highlightCode } from "@/lib/hljs";
import "highlight.js/styles/github-dark.css";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { Copy, Check } from "lucide-react";
import { copyToClipboard } from "@/lib/vulnerability-utils";
import { parseFencedCode } from "@/lib/fenced-code";
import { rehypeCodeMeta, mdComponents } from "./MdCodeBlock";

interface PocBlockProps {
  description?: string | null;
  scriptCode?: string | null;
  onCopy?: () => void;
}

export function PocBlock({ description, scriptCode, onCopy }: PocBlockProps) {
  const [copied, setCopied] = useState(false);

  if (!description && !scriptCode) return null;

  const { language, code } = parseFencedCode(scriptCode);
  const highlighted = highlightCode(code, language);

  const copy = () => {
    if (!code) return;
    copyToClipboard(code);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
    onCopy?.();
  };

  return (
    <section>
      <h2 className="text-xl font-semibold text-white mb-3">Proof of Concept</h2>
      <div className="space-y-4">
        {description && (
          <div className="prose-markdown">
            <ReactMarkdown
              remarkPlugins={[remarkGfm]}
              rehypePlugins={[rehypeCodeMeta]}
              components={mdComponents}
            >
              {description}
            </ReactMarkdown>
          </div>
        )}
        {code && (
          <div className="group/poc relative rounded-md border border-[#2a2a2a] overflow-hidden">
            <div className="flex items-stretch">
              <span className="relative flex items-center text-[13px] text-[#999] font-mono px-4 py-2 border-r border-[#2a2a2a]">PoC Script<span className="absolute top-0 inset-x-0 h-0.5 bg-white/60 rounded-full" /></span>
              <div className="flex-1 border-b border-[#2a2a2a]" />
              <button
                onClick={copy}
                className="px-3 py-2 text-[#555] hover:text-white transition-colors flex-shrink-0 border-b border-[#2a2a2a]"
                aria-label="Copy PoC code"
              >
                {copied ? (
                  <Check className="w-3.5 h-3.5 text-emerald-400" />
                ) : (
                  <Copy className="w-3.5 h-3.5" />
                )}
              </button>
            </div>
            <div className="overflow-auto max-h-[400px] px-4 py-3">
              <pre className="font-mono text-[12px] leading-[22px] whitespace-pre [font-variant-ligatures:none]">
                <code
                  dangerouslySetInnerHTML={{
                    __html: highlighted,
                  }}
                />
              </pre>
            </div>
          </div>
        )}
      </div>
    </section>
  );
}
