import { useEffect, useRef, useState } from "react";
import {
  KeyboardAvoidingView,
  Modal,
  Platform,
  Pressable,
  Text,
  TextInput,
  View,
} from "react-native";
import {
  initialWindowMetrics,
  SafeAreaProvider,
  SafeAreaView,
} from "react-native-safe-area-context";
import { toast } from "sonner-native";
import { cn } from "@/lib/utils";
import { toUserMessage } from "@/lib/errors";

const IMMERSIVE_CHAR_LIMIT = 120;

function getImmersiveStyle(length: number) {
  if (length === 0)
    return { className: "text-3xl font-semibold leading-snug" };
  if (length < 30)
    return { className: "text-5xl font-semibold leading-tight" };
  if (length < 70)
    return { className: "text-3xl font-semibold leading-snug" };
  return { className: "text-2xl font-normal leading-snug" };
}

interface TextComposeModalProps {
  open: boolean;
  onClose: () => void;
  /**
   * Submit handler — must throw if the upload fails so the modal can re-show
   * the editor and the user doesn't lose their text.
   */
  onSubmit: (content: string) => Promise<void>;
}

/**
 * Immersive full-screen text editor. Mirrors desktop's `text-editor.tsx`:
 * dynamic font ramp at 30/70/130 chars, no markdown preview, no gradient.
 * Long messages scroll inside the multiline TextInput. Pauses upstream
 * playback (the host wraps render in a useSuspendPlayback while open).
 */
export function TextComposeModal({
  open,
  onClose,
  onSubmit,
}: TextComposeModalProps) {
  const [content, setContent] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const inputRef = useRef<TextInput>(null);

  // Reset whenever the modal opens fresh.
  useEffect(() => {
    if (open) {
      setContent("");
      setSubmitting(false);
      // Re-focus on next tick; iOS occasionally drops the autoFocus call when
      // the modal animation is mid-flight.
      const t = setTimeout(() => inputRef.current?.focus(), 60);
      return () => clearTimeout(t);
    }
  }, [open]);

  const trimmed = content.trim();
  const canSend = trimmed.length > 0 && !submitting;

  const handleSend = async () => {
    if (!canSend) return;
    setSubmitting(true);
    try {
      await onSubmit(trimmed);
      onClose();
    } catch (err) {
      toast.error(toUserMessage(err));
      setSubmitting(false);
    }
  };

  const style = getImmersiveStyle(trimmed.length);
  const isImmersive = trimmed.length < IMMERSIVE_CHAR_LIMIT;

  return (
    <Modal
      visible={open}
      animationType="fade"
      transparent={false}
      onRequestClose={onClose}
    >
      <SafeAreaProvider initialMetrics={initialWindowMetrics}>
      <SafeAreaView className="flex-1 bg-black" edges={["top", "bottom"]}>
        <KeyboardAvoidingView
          behavior={Platform.OS === "ios" ? "padding" : undefined}
          className="flex-1"
        >
          <View className="flex-row items-center justify-between px-4 py-3">
            <Pressable
              onPress={onClose}
              accessibilityLabel="Cancel"
              hitSlop={12}
            >
              <Text className="text-white/70 text-base">Cancel</Text>
            </Pressable>
            <Pressable
              onPress={handleSend}
              disabled={!canSend}
              hitSlop={12}
              accessibilityLabel="Send"
            >
              <Text
                className={cn(
                  "text-base font-semibold",
                  canSend ? "text-white" : "text-white/30",
                )}
              >
                {submitting ? "Sending..." : "Send"}
              </Text>
            </Pressable>
          </View>

          <View className="flex-1 justify-center px-6 pb-6">
            <TextInput
              ref={inputRef}
              value={content}
              onChangeText={setContent}
              placeholder="Type a message"
              placeholderTextColor="rgba(255,255,255,0.4)"
              multiline
              autoFocus
              autoCorrect
              autoCapitalize="sentences"
              editable={!submitting}
              scrollEnabled={!isImmersive}
              textAlignVertical={isImmersive ? "center" : "top"}
              style={{
                color: "white",
                textAlign: isImmersive ? "center" : "left",
                maxHeight: isImmersive ? undefined : 540,
              }}
              className={cn("text-white", style.className)}
            />
          </View>
        </KeyboardAvoidingView>
      </SafeAreaView>
      </SafeAreaProvider>
    </Modal>
  );
}
