/**
 * Virtual staging — upload photos, select style, submit to Collov AI.
 * $0.23/image. Room detection, style selection.
 */

import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Image,
  ScrollView,
  Alert,
} from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { useTheme } from '../../themes/ThemeProvider';
import { requestVirtualStaging } from '../../services/api';

const ROOM_TYPES = ['Living Room', 'Bedroom', 'Kitchen', 'Dining Room', 'Bathroom', 'Office', 'Outdoor'];
const STYLES = ['Modern', 'Contemporary', 'Transitional', 'Traditional', 'Coastal', 'Farmhouse', 'Mid-Century'];

export default function Staging() {
  const { theme } = useTheme();
  const [image, setImage] = useState<string | null>(null);
  const [roomType, setRoomType] = useState('Living Room');
  const [style, setStyle] = useState('Modern');
  const [submitting, setSubmitting] = useState(false);
  const [result, setResult] = useState<string | null>(null);

  const pickImage = async () => {
    const permResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (!permResult.granted) {
      Alert.alert('Permission needed', 'Please allow access to your photo library.');
      return;
    }
    const pickerResult = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images'],
      quality: 0.9,
      allowsEditing: true,
    });
    if (!pickerResult.canceled && pickerResult.assets[0]) {
      setImage(pickerResult.assets[0].uri);
      setResult(null);
    }
  };

  const takePhoto = async () => {
    const permResult = await ImagePicker.requestCameraPermissionsAsync();
    if (!permResult.granted) {
      Alert.alert('Permission needed', 'Please allow camera access.');
      return;
    }
    const pickerResult = await ImagePicker.launchCameraAsync({
      quality: 0.9,
      allowsEditing: true,
    });
    if (!pickerResult.canceled && pickerResult.assets[0]) {
      setImage(pickerResult.assets[0].uri);
      setResult(null);
    }
  };

  const handleSubmit = async () => {
    if (!image) {
      Alert.alert('No Image', 'Please select or take a photo first.');
      return;
    }
    setSubmitting(true);
    const res = await requestVirtualStaging({
      image_uri: image,
      room_type: roomType,
      style,
    });
    setSubmitting(false);
    if (res.success && res.data) {
      const data = res.data as { staged_url: string };
      setResult(data.staged_url);
    } else {
      Alert.alert('Error', res.error ?? 'Staging failed');
    }
  };

  return (
    <ScrollView style={[styles.container, { backgroundColor: theme.colors.background }]}>
      {/* Image Selection */}
      <View style={[styles.imageSection, { backgroundColor: theme.colors.card }]}>
        {image ? (
          <Image source={{ uri: image }} style={styles.previewImage} />
        ) : (
          <View style={[styles.placeholder, { backgroundColor: theme.colors.inputBg }]}>
            <Text style={[styles.placeholderText, { color: theme.colors.textSecondary }]}>
              Select an empty room photo
            </Text>
          </View>
        )}
        <View style={styles.imageButtons}>
          <TouchableOpacity
            style={[styles.imgBtn, { backgroundColor: theme.colors.primary }]}
            onPress={pickImage}
          >
            <Text style={styles.imgBtnText}>Choose Photo</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.imgBtn, { backgroundColor: theme.colors.accent }]}
            onPress={takePhoto}
          >
            <Text style={styles.imgBtnText}>Take Photo</Text>
          </TouchableOpacity>
        </View>
      </View>

      {/* Room Type */}
      <View style={[styles.section, { backgroundColor: theme.colors.card }]}>
        <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>Room Type</Text>
        <View style={styles.chipRow}>
          {ROOM_TYPES.map((r) => (
            <TouchableOpacity
              key={r}
              style={[styles.chip, {
                backgroundColor: roomType === r ? theme.colors.primary : theme.colors.surface,
                borderColor: roomType === r ? theme.colors.primary : theme.colors.border,
              }]}
              onPress={() => setRoomType(r)}
            >
              <Text style={[styles.chipText, { color: roomType === r ? '#FFF' : theme.colors.textSecondary }]}>
                {r}
              </Text>
            </TouchableOpacity>
          ))}
        </View>
      </View>

      {/* Style */}
      <View style={[styles.section, { backgroundColor: theme.colors.card }]}>
        <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>Staging Style</Text>
        <View style={styles.chipRow}>
          {STYLES.map((s) => (
            <TouchableOpacity
              key={s}
              style={[styles.chip, {
                backgroundColor: style === s ? theme.colors.accent : theme.colors.surface,
                borderColor: style === s ? theme.colors.accent : theme.colors.border,
              }]}
              onPress={() => setStyle(s)}
            >
              <Text style={[styles.chipText, { color: style === s ? '#FFF' : theme.colors.textSecondary }]}>
                {s}
              </Text>
            </TouchableOpacity>
          ))}
        </View>
      </View>

      {/* Submit */}
      <View style={styles.submitSection}>
        <Text style={[styles.costNote, { color: theme.colors.textSecondary }]}>
          Cost: ~$0.23 per image via Collov AI
        </Text>
        <TouchableOpacity
          style={[styles.submitBtn, { backgroundColor: theme.colors.success, opacity: submitting ? 0.6 : 1 }]}
          onPress={handleSubmit}
          disabled={submitting}
        >
          <Text style={styles.submitBtnText}>{submitting ? 'Staging...' : 'Generate Staged Image'}</Text>
        </TouchableOpacity>
      </View>

      {/* Result */}
      {result && (
        <View style={[styles.resultSection, { backgroundColor: theme.colors.card }]}>
          <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>Staged Result</Text>
          <Image source={{ uri: result }} style={styles.resultImage} />
        </View>
      )}

      <View style={styles.bottomPad} />
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  imageSection: { padding: 16 },
  previewImage: { width: '100%', height: 220, borderRadius: 10 },
  placeholder: { width: '100%', height: 220, borderRadius: 10, justifyContent: 'center', alignItems: 'center' },
  placeholderText: { fontSize: 15 },
  imageButtons: { flexDirection: 'row', gap: 10, marginTop: 12 },
  imgBtn: { flex: 1, paddingVertical: 12, borderRadius: 10, alignItems: 'center' },
  imgBtnText: { color: '#FFF', fontWeight: '700', fontSize: 14 },
  section: { marginTop: 8, padding: 16 },
  sectionTitle: { fontSize: 16, fontWeight: '700', marginBottom: 12 },
  chipRow: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
  chip: { paddingHorizontal: 14, paddingVertical: 8, borderRadius: 20, borderWidth: 1 },
  chipText: { fontSize: 13, fontWeight: '500' },
  submitSection: { padding: 16 },
  costNote: { fontSize: 12, textAlign: 'center', marginBottom: 10 },
  submitBtn: { height: 50, borderRadius: 12, justifyContent: 'center', alignItems: 'center' },
  submitBtnText: { color: '#FFF', fontSize: 17, fontWeight: '700' },
  resultSection: { margin: 16, padding: 16, borderRadius: 12 },
  resultImage: { width: '100%', height: 220, borderRadius: 10 },
  bottomPad: { height: 40 },
});
