import { useState, useRef, useEffect, useCallback } from "react";
import { cn } from "@/lib/utils";
import { apiClient } from "@/api/client";
import { useAppStore } from "@/stores/app-store";

interface TextComposeOverlayProps {
  streamId: string;
  onClose: () => 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 TextComposeOverlay({
  streamId,
  onClose,
}: TextComposeOverlayProps) {
  const [content, setContent] = useState("");
  const [sending, setSending] = useState(false);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const addParticleToStream = useAppStore((s) => s.addParticleToStream);

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

  const handleSend = useCallback(async () => {
    const trimmed = content.trim();
    if (!trimmed || sending) return;

    setSending(true);
    try {
      const particle = await apiClient.createStreamParticle(streamId, {
        type: "text",
        data: { content: trimmed },
      });
      addParticleToStream(streamId, particle);
      onClose();
    } catch {
      setSending(false);
    }
  }, [content, sending, streamId, addParticleToStream, onClose]);

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

  const style = getTextStyle(content.length);

  return (
    <div className="absolute inset-0 z-50 flex items-center justify-center bg-black/90">
      <textarea
        ref={textareaRef}
        value={content}
        onChange={(e) => setContent(e.target.value)}
        onKeyDown={handleKeyDown}
        placeholder="Type a message..."
        disabled={sending}
        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">
            Cmd+Enter
          </kbd>{" "}
          send
        </span>
      </div>
    </div>
  );
}
