import * as ImagePicker from "expo-image-picker";
import { useState } from "react";
import { ActivityIndicator, Image, StyleSheet, 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 ImagePage() {
  const [caption, setCaption] = useState("");
  const [uploading, setUploading] = useState(false);
  const [dismissing, setDismissing] = useState(false);
  const [previewUri, setPreviewUri] = useState<string | null>(null);

  const uploadAsset = async (asset: ImagePicker.ImagePickerAsset) => {
    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 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;
    await uploadAsset(result.assets[0]);
  };

  const handlePickFromGallery = async () => {
    const { granted } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (!granted) {
      alert("Media library permission is required to pick photos.");
      return;
    }

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

    if (result.canceled) return;
    await uploadAsset(result.assets[0]);
  };

  const handleDismiss = () => {
    setDismissing(true);
    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.");
      })
      .finally(() => setDismissing(false));
  };

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

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

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

      {uploading ? (
        <ActivityIndicator size="large" color={colors.accent} style={{ marginTop: 8 }} />
      ) : (
        <>
          <View style={shared.actionsRow}>
            <TouchableOpacity
              style={[shared.btnPrimary, shared.actionFlex]}
              onPress={handleTakePhoto}
              activeOpacity={0.8}
            >
              <Text style={shared.btnPrimaryText}>Take Photo & Show</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={[shared.btnPrimary, shared.actionFlex]}
              onPress={handlePickFromGallery}
              activeOpacity={0.8}
            >
              <Text style={shared.btnPrimaryText}>Pick from Gallery</Text>
            </TouchableOpacity>
          </View>
          <View style={shared.actionsRow}>
            <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>
  );
}

const styles = StyleSheet.create({
  preview: {
    width: "100%",
    height: 200,
    borderRadius: 12,
    resizeMode: "cover",
  },
});
