import { useState } from "react";
import { ActivityIndicator, Text, TextInput, TouchableOpacity, View } from "react-native";
import { colors, shared } from "../styles";

const BASE_URL =
  "https://shsf-api.reversed.dev/api/exec/15/1c44d8b5-4065-4a54-b259-748561021329";

export function TextPage() {
  const [title, setTitle] = useState("");
  const [sending, setSending] = useState(false);
  const [dismissing, setDismissing] = useState(false);

  const handleShow = () => {
    if (title.trim() === "") {
      alert("Please enter some text before sending.");
      return;
    }
    setSending(true);
    fetch(`${BASE_URL}/push_text`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ title }),
    })
      .then((r) => r.json())
      .then((data) => {
        if (data.status !== "success") alert("Failed to send text.");
      })
      .catch((error) => {
        console.error("Error sending text:", error);
        alert("Error sending text.");
      })
      .finally(() => setSending(false));
  };

  const handleDismiss = () => {
    setDismissing(true);
    fetch(`${BASE_URL}/push_dismiss_text`, { method: "POST" })
      .then((r) => r.json())
      .then((data) => {
        if (data.status !== "success") alert("Failed to dismiss text.");
      })
      .catch((error) => {
        console.error("Error dismissing text:", error);
        alert("Error dismissing text.");
      })
      .finally(() => setDismissing(false));
  };

  return (
    <View style={shared.screenPadded}>
      <Text style={shared.pageTitle}>Text Popup</Text>
      <Text style={shared.subtitle}>Display a text message on the TV.</Text>

      <View style={shared.field}>
        <Text style={shared.label}>Message</Text>
        <TextInput
          style={[shared.input, shared.inputMultiline]}
          placeholder="Type something..."
          placeholderTextColor={colors.placeholderColor}
          value={title}
          onChangeText={setTitle}
          multiline
        />
      </View>

      <View style={shared.actionsRow}>
        <TouchableOpacity
          style={[shared.btnPrimary, shared.actionFlex, sending && shared.btnDisabled]}
          onPress={handleShow}
          activeOpacity={0.8}
          disabled={sending}
        >
          {sending ? (
            <ActivityIndicator color="#fff" />
          ) : (
            <Text style={shared.btnPrimaryText}>Show on TV</Text>
          )}
        </TouchableOpacity>
        <TouchableOpacity
          style={[shared.btnDanger, shared.actionFlex, dismissing && shared.btnDisabled]}
          onPress={handleDismiss}
          activeOpacity={0.8}
          disabled={dismissing}
        >
          {dismissing ? (
            <ActivityIndicator color="#fff" />
          ) : (
            <Text style={shared.btnDangerText}>Dismiss</Text>
          )}
        </TouchableOpacity>
      </View>
    </View>
  );
}
