"use client";

import { useEffect, useRef } from "react";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism";
import { cn } from "@/lib/utils";
import type { AlgorithmCode } from "@/lib/visualizations/types";

interface CodePanelProps {
  code: AlgorithmCode;
  currentLine?: number;
  highlightLines?: number[];
  className?: string;
}

const LANGUAGE_MAP: Record<AlgorithmCode["language"], string> = {
  typescript: "typescript",
  javascript: "javascript",
  python: "python",
};

export function CodePanel({
  code,
  currentLine,
  highlightLines = [],
  className,
}: CodePanelProps) {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (currentLine && containerRef.current) {
      const container = containerRef.current;
      const lineHeight = 24;
      const lineTop = (currentLine - 1) * lineHeight;
      const containerHeight = container.clientHeight;
      const scrollTarget = lineTop - containerHeight / 2 + lineHeight / 2;

      container.scrollTo({
        top: Math.max(0, scrollTarget),
        behavior: "smooth",
      });
    }
  }, [currentLine]);

  const codeLines = code.code.trim().split("\n");

  return (
    <div
      ref={containerRef}
      className={cn(
        "overflow-auto rounded-lg border border-[var(--border)] bg-[#282c34]",
        className
      )}
    >
      <div className="relative min-w-max">
        {codeLines.map((line, i) => {
          const lineNumber = i + 1;
          const isCurrentLine = lineNumber === currentLine;
          const isHighlighted = highlightLines.includes(lineNumber);

          return (
            <div
              key={i}
              className={cn(
                "flex transition-colors duration-200",
                isCurrentLine && "bg-[var(--primary)]/20",
                isHighlighted && !isCurrentLine && "bg-[var(--primary)]/10"
              )}
            >
              <span className="inline-block w-10 flex-shrink-0 select-none py-0.5 pr-3 text-right font-mono text-xs text-[var(--muted-foreground)]/60">
                {lineNumber}
              </span>
              {isCurrentLine && (
                <span
                  className="inline-block w-4 flex-shrink-0 py-0.5 font-mono text-xs text-[var(--primary)]"
                  aria-hidden="true"
                >
                  →
                </span>
              )}
              {!isCurrentLine && (
                <span
                  className="inline-block w-4 flex-shrink-0"
                  aria-hidden="true"
                />
              )}
              <SyntaxHighlighter
                language={LANGUAGE_MAP[code.language]}
                style={oneDark}
                customStyle={{
                  margin: 0,
                  padding: "2px 8px 2px 0",
                  background: "transparent",
                  fontSize: "0.875rem",
                  lineHeight: "1.5",
                }}
                codeTagProps={{
                  style: {
                    fontFamily: "var(--font-mono, monospace)",
                  },
                }}
              >
                {line || " "}
              </SyntaxHighlighter>
            </div>
          );
        })}
      </div>
    </div>
  );
}
