import { useEffect, useRef, useCallback } from "react";
import { cn } from "@/lib/utils";

interface TextComposeStepProps {
  textContent: string;
  onTextChange: (text: string) => void;
  onAdvance: () => void;
  onCancel: () => void;
}

function getTextStyle(length: number) {
  if (length < 50) return { size: "text-5xl", weight: "font-semibold" };
  if (length < 150) return { size: "text-3xl", weight: "font-semibold" };
  if (length < 300) return { size: "text-2xl", weight: "font-normal" };
  return { size: "text-lg", weight: "font-normal" };
}

export function TextComposeStep({
  textContent,
  onTextChange,
  onAdvance,
  onCancel,
}: TextComposeStepProps) {
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    textareaRef.current?.focus();
  }, []);

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onCancel();
      } else if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
        e.preventDefault();
        if (textContent.trim()) onAdvance();
      }
    },
    [onCancel, onAdvance, textContent],
  );

  const style = getTextStyle(textContent.length);

  return (
    <div className="absolute inset-0 z-50 flex items-center justify-center bg-black/90">
      <textarea
        ref={textareaRef}
        value={textContent}
        onChange={(e) => onTextChange(e.target.value)}
        onKeyDown={handleKeyDown}
        placeholder="Type a message..."
        className={cn(
          "w-full max-w-2xl resize-none border-none bg-transparent p-8 text-center text-white placeholder-white/40 outline-none",
          style.size,
          style.weight,
        )}
        rows={4}
      />
      <div className="absolute bottom-8 flex items-center gap-4 text-sm text-white/50">
        <span>
          <kbd className="rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs">
            Esc
          </kbd>{" "}
          cancel
        </span>
        <span>
          <kbd className="rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs">
            ⌘+Enter
          </kbd>{" "}
          next
        </span>
      </div>
    </div>
  );
}
