import * as ImagePicker from "expo-image-picker";
import { useState } from "react";
import { ActivityIndicator, Button, Image, StyleSheet, Text, TextInput, View } from "react-native";

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

export function ImagePage() {
  const [caption, setCaption] = useState("");
  const [uploading, setUploading] = useState(false);
  const [previewUri, setPreviewUri] = useState<string | null>(null);

  const handleTakePhoto = async () => {
    const { granted } = await ImagePicker.requestCameraPermissionsAsync();
    if (!granted) {
      alert("Camera permission is required to take photos.");
      return;
    }

    const result = await ImagePicker.launchCameraAsync({
      mediaTypes: "images",
      quality: 1,
      base64: true,
    });

    if (result.canceled) return;

    const asset = result.assets[0];
    setPreviewUri(asset.uri);
    setUploading(true);

    try {
      const res = await fetch(`${BASE_URL}/push_image`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ image_b64: asset.base64, caption }),
      });
      const data = await res.json();
      if (data.status !== "success") throw new Error(data.message ?? "Upload failed");
    } catch (error) {
      console.error("Upload error:", error);
      alert("Failed to upload image.");
    } finally {
      setUploading(false);
    }
  };

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

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Image Popup</Text>
      <Text style={styles.subtitle}>Show a photo on the TV with an optional caption.</Text>

      <View style={styles.field}>
        <Text style={styles.label}>Caption (optional)</Text>
        <TextInput
          style={styles.input}
          placeholder="Add a caption..."
          value={caption}
          onChangeText={setCaption}
        />
      </View>

      {previewUri && (
        <Image source={{ uri: previewUri }} style={styles.preview} />
      )}

      {uploading ? (
        <ActivityIndicator size="large" style={{ marginTop: 8 }} />
      ) : (
        <View style={styles.actions}>
          <View style={styles.actionBtn}>
            <Button title="Take Photo & Show" onPress={handleTakePhoto} />
          </View>
          <View style={styles.actionBtn}>
            <Button title="Dismiss" onPress={handleDismiss} color="#e55" />
          </View>
        </View>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 24,
    backgroundColor: "#f9f9f9",
    gap: 20,
  },
  title: {
    fontSize: 26,
    fontWeight: "700",
    color: "#111",
    marginTop: 8,
  },
  subtitle: {
    fontSize: 14,
    color: "#888",
    marginTop: -12,
  },
  field: {
    gap: 6,
  },
  label: {
    fontSize: 13,
    fontWeight: "600",
    color: "#555",
    textTransform: "uppercase",
    letterSpacing: 0.5,
  },
  input: {
    borderWidth: 1,
    borderColor: "#ddd",
    borderRadius: 10,
    padding: 12,
    fontSize: 16,
    backgroundColor: "#fff",
  },
  preview: {
    width: "100%",
    height: 200,
    borderRadius: 10,
    resizeMode: "cover",
  },
  actions: {
    flexDirection: "row",
    gap: 12,
    marginTop: 4,
  },
  actionBtn: {
    flex: 1,
  },
});
