"use client";

import { useState, useEffect, useCallback } from "react";
import { useTheme } from "@/app/lib/theme";
import { Button } from "./button";
import { Copy, Check } from "lucide-react";
import { toast } from "sonner";

type Props = {
  code: string;
  language?: string;
  showCopy?: boolean;
  className?: string;
};

export default function CodeBlock({
  code,
  language = "sql",
  showCopy = true,
  className,
}: Props) {
  const { resolved } = useTheme();
  const [html, setHtml] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    let canceled = false;
    (async () => {
      try {
        const shiki = await import("shiki");
        const highlighter = await shiki.createHighlighter({
          themes: ["github-dark", "github-light"],
          langs: [language as never],
        });
        if (canceled) return;
        const result = highlighter.codeToHtml(code, {
          lang: language,
          theme: resolved === "dark" ? "github-dark" : "github-light",
        });
        setHtml(result);
      } catch {
        setHtml(null);
      }
    })();
    return () => {
      canceled = true;
    };
  }, [code, language, resolved]);

  const handleCopy = useCallback(() => {
    navigator.clipboard.writeText(code);
    setCopied(true);
    toast.success("Copied to clipboard", { duration: 1500 });
    setTimeout(() => setCopied(false), 2000);
  }, [code]);

  return (
    <div className={`relative group ${className ?? ""}`}>
      {html ? (
        <div
          className="rounded border border-border overflow-auto max-h-[300px] text-body-sm [&_pre]:p-3 [&_pre]:m-0 [&_pre]:bg-transparent [&_code]:text-body-sm [&_pre]:overflow-auto"
          dangerouslySetInnerHTML={{ __html: html }}
        />
      ) : (
        <pre className="rounded border border-border bg-muted p-3 font-mono text-body-sm text-foreground overflow-auto max-h-[300px] whitespace-pre-wrap break-words">
          {code}
        </pre>
      )}
      {showCopy && (
        <Button
          variant="ghost"
          size="icon"
          className="absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity"
          onClick={handleCopy}
        >
          {copied ? (
            <Check className="h-3 w-3 text-success" />
          ) : (
            <Copy className="h-3 w-3" />
          )}
        </Button>
      )}
    </div>
  );
}
