import { useRef, useEffect, useState, useCallback } from "react";
import type { TranscriptEntry } from "../../types/messages";

interface TranscriptPanelProps {
  transcripts: TranscriptEntry[];
}

export function TranscriptPanel({ transcripts }: TranscriptPanelProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [autoScroll, setAutoScroll] = useState(true);

  // Auto-scroll when new transcripts arrive
  useEffect(() => {
    if (autoScroll && containerRef.current) {
      containerRef.current.scrollTop = containerRef.current.scrollHeight;
    }
  }, [transcripts, autoScroll]);

  // Detect manual scroll
  const handleScroll = useCallback(() => {
    if (!containerRef.current) return;

    const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
    const isAtBottom = scrollHeight - scrollTop - clientHeight < 50;

    setAutoScroll(isAtBottom);
  }, []);

  const scrollToBottom = useCallback(() => {
    if (containerRef.current) {
      containerRef.current.scrollTop = containerRef.current.scrollHeight;
      setAutoScroll(true);
    }
  }, []);

  return (
    <div className="panel h-full flex flex-col">
      <div className="font-mono text-xs text-[#9bc3ff] tracking-wide uppercase p-4 pb-2 border-b border-dashed border-[rgba(117,170,252,0.35)] flex justify-between items-center">
        <span>TRANSCRIPT//</span>
        {!autoScroll && (
          <button
            onClick={scrollToBottom}
            className="px-2 py-1 text-[10px] bg-[#0f1c2f] border border-[#3f6fb3] hover:bg-[#153667] transition-colors"
          >
            Scroll to bottom
          </button>
        )}
      </div>

      <div
        ref={containerRef}
        onScroll={handleScroll}
        className="flex-1 overflow-y-auto p-4 space-y-3"
      >
        {transcripts.length === 0 ? (
          <div className="text-center text-[#9bc3ff] text-sm font-mono opacity-60 py-8">
            Transcriptions will appear here...
          </div>
        ) : (
          transcripts.map((entry) => (
            <div
              key={entry.id}
              className={`font-mono text-sm ${
                entry.isFinal ? "opacity-100" : "opacity-70"
              }`}
            >
              <div className="flex items-baseline gap-2 mb-1">
                <span className="text-[#75aafc] text-xs">
                  [{entry.start.toFixed(2)}s - {entry.end.toFixed(2)}s]
                </span>
                <span className="text-[#9bc3ff] text-xs font-bold">
                  {entry.speaker}
                </span>
                {entry.isFinal && (
                  <span className="text-[#3f6fb3] text-[10px]">[FINAL]</span>
                )}
              </div>
              <p className="m-0 text-[#dbe7ff] leading-relaxed">{entry.text}</p>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
