import { Chantier } from '@/class/class';
import { ThemedView } from '@/components/theme/themed-view';
import React, { use, useEffect, useState } from 'react';
import { TouchableOpacity, StyleProp, StyleSheet, View, Image, ViewStyle,Text, TextInput, ScrollView } from 'react-native';
import { ThemedText } from './theme/themed-text';
import { deleteAnomalie, addAnomalie, getChantiers } from '@/services/ressourcesService';
import { useChantier } from '@/app/ContextChantier';
import * as ImagePicker from 'expo-image-picker';

type Props = {
    data: {
        chantier:Chantier|null;
    }
    style?: StyleProp<ViewStyle>;
};

export default function Anomaly({data,style}: Props) {

  const{syncChantier }= useChantier();
  const [imageUri, setImageUri] = useState<string | null>(null);

  const handleDelete = async (anomaly: string) => {
    await deleteAnomalie(data.chantier!.id, anomaly);
    data.chantier!.anomalies = data.chantier!.anomalies.filter(a => a !== anomaly);
    await syncChantier();
  };

  const handleAdd = async () => {
    if (newAnomaly.trim().length === 0) return;
    await addAnomalie(data.chantier!.id, newAnomaly.trim());
    data.chantier!.anomalies.push(newAnomaly.trim());
    setNewAnomaly("");
    await syncChantier();
  };

  //DEBUG
  useEffect(() => {
    console.log("imageUri changed", imageUri);
  }, [imageUri]);


  // Image picker function (not used currently)
  const selectImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images'],
      allowsEditing: true,
      quality: 1,
    });

    if (!result.canceled) {
      console.log(result);
      setImageUri(result.assets[0].uri.replace('file://', ''));
    } else {
      alert('You did not select any image.');
    }
  };


  const [newAnomaly, setNewAnomaly] = useState("");

  return(
    <View  style={style}>
        {data.chantier ? (
            <ThemedView lvl={4} style={styles.anomaliesContainer}>
                <ThemedText style={styles.anomaliesTitle}>Anomalies</ThemedText>
                  {/* Add Anomaly Section */}
                  <View style={styles.addContainer}>
                    <TextInput style={styles.input} placeholder="Nouvelle anomalie..." value={newAnomaly} onChangeText={setNewAnomaly} />
                    <TouchableOpacity style={styles.addButton} onPress={handleAdd}>
                      <ThemedText style={styles.addButtonText}>Ajouter</ThemedText>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={selectImage} style={styles.addButton}>
                      <ThemedText style={styles.addButton}>Choisir une image</ThemedText>
                    </TouchableOpacity>
                    {imageUri && (
                      <Image source={{ uri: imageUri }} style={styles.image} />
                    )}
                  </View>


                  {data.chantier.anomalies.length > 0 ? (
                    data.chantier.anomalies.map((anomaly, index) => (
                      <ThemedView key={index} lvl={2} style={styles.anomalyItem}>
                        <ThemedText style={styles.anomalyText}>• {anomaly}</ThemedText>
                        <TouchableOpacity onPress={() => handleDelete(anomaly)} style={styles.deleteButton}>
                        <Text style={styles.deleteText}>✕</Text>
                        </TouchableOpacity>
                      </ThemedView>
                    ))
                  ) : (
                    <ThemedText style={styles.noAnomaly}>Aucune anomalie</ThemedText>
                  ) }
                </ThemedView>
        ): null}
    </View>
  )
}

const styles = StyleSheet.create({
  //Anomalies styles
  anomaliesContainer: {
    padding: 5,
    borderRadius: 10,
  },
  anomaliesTitle: {
    fontSize: 16,
    fontWeight: "bold",
    marginBottom: 8,
  },
  anomalyItem: {
    flexDirection: "row",
    alignItems: "flex-start",
    padding: 8,
    marginBottom: 5,
    borderRadius: 8,
  },
  anomalyText: {
  flex: 1,
  marginLeft: 5,
  },
  noAnomaly: {
    fontStyle: "italic",
    opacity: 0.7,
  },
  //delete button styles
  deleteButton: {
    backgroundColor: "red",
    width: 24,
    height: 24,
    borderRadius: 12,
    alignItems: "center",
    justifyContent: "center",
  },
  deleteText: {
    color: "white",
    fontWeight: "bold",
    fontSize: 14,
    lineHeight: 14,
  },
  //add anomaly styles
  addContainer: {
    marginLeft: 2,
    flexDirection: "row",
    alignItems: "center"
  },
  input: {
    flex: 1,
    backgroundColor: "white",
    padding: 8,
    borderRadius: 8,
    marginRight: 8,
  },
  addButton: {
    paddingVertical: 8,
    paddingHorizontal: 12,
    borderRadius: 8,
  },
  addButtonText: {
    fontWeight: "bold",
  },
  image: { width: 200, height: 200, borderRadius: 10 }
})