import { useChantier } from '@/app/ContextChantier';
import { changeChantierStatus } from "@/services/ressourcesService";
import { useEffect, useState } from 'react';
import { Dimensions, FlatList, LayoutAnimation, Modal, Pressable, ScrollView, StyleProp, StyleSheet, View, ViewStyle } from 'react-native';
import Animated, { LinearTransition } from 'react-native-reanimated';
import { ThemedButton } from './theme/themed-button';
import { ThemedText } from './theme/themed-text';
import { ThemedView } from "./theme/themed-view";
import { Ressources, User } from '@/class/class';
import { getRessources } from "@/services/ressourcesService";
import RessourceSummary from './ressourceSummary';

const { width, height } = Dimensions.get("window");

type RessourcesQte = [Ressources, number];

type Props = {
  ressourceType: string;
  sendRessources: (ressource: RessourcesQte[]) => void;
  style?: StyleProp<ViewStyle>;
};

export default function SelectRessource({style,ressourceType,sendRessources: sendRessources , ...otherProps }: Props) {

    const [ressources, setRessources] = useState<RessourcesQte[]>([]);
    const [isOpen,setIsOpen] = useState(false);
    const [listRessource,setListRessource] = useState<Ressources[]>([]);

    useEffect(() => {
      async function loadData() {
        try {
          const data = await getRessources();
          const ressources = data.filter(user => user.type === ressourceType);
          setListRessource(ressources);
        } catch (error) {
          console.error("Erreur lors du chargement :", error);
        }
      }
      loadData();
    }, []);


    useEffect(() => {
      sendRessources(ressources);
    }, [ressources])
  

    function onPressOpen(): void {
       setIsOpen(!isOpen);
    }

    function getTotalRessource(): number{
      var total = 0;
      ressources.forEach(element => {
        total += element[1]
      });
      return total;
    }

    function addRessource(ressource: RessourcesQte): void{
      if(ressource[1]>0){
        setRessources(prev =>
          prev.some(i => i[0].name === ressource[0].name)
            ? prev.map(i =>
                i[0].name === ressource[0].name
                  ? [i[0], ressource[1]]
                  : i
              )
            : [...prev, ressource]
        );
      }
      else{
        setRessources(prev => prev.filter(item => item[0].name !== ressource[0].name));
      }
    }




    const RessourceSummaryItem = ({ item }: { item: Ressources }) => {
      if (!item) return null;
      const ressourceQte = ressources.find(([r]) => r.name === item.name);
      const qte = ressourceQte? ressourceQte[1]:0;
      return(
        <RessourceSummary style={{padding:10,width:"100%"}} ressource={item} qte={qte} sendRessource={addRessource}></RessourceSummary>
      )
    }


    const RessourceSearch = () => {
      return(
        <Modal transparent={true}>
          <View style={styles.overlay}>
            <ThemedView style={styles.overlayView}>
                <ThemedText style={{fontSize: 20}}>{"Rechercher des "+ressourceType+"s :"}</ThemedText>
                <FlatList
                  style={{width:"100%"}}
                  data={listRessource}
                  renderItem={RessourceSummaryItem}
                  keyExtractor={(_, index) => index.toString()}
                />


                <ThemedButton lvl={2} border={5} style={styles.buttonValid} onPress={() => setIsOpen(false)}>
                  <ThemedText style={{fontSize: 25}}>Valider</ThemedText>
                </ThemedButton>
            </ThemedView>
          </View>
        </Modal>
      )
    }

    return(
            <ThemedButton style={style} lvl={1} onPress={() => onPressOpen()}>
                <ThemedText style={styles.centeredText}>{ressources?getTotalRessource()+" "+ressourceType+(getTotalRessource()>1?"s":"")+", "+ ressources.length+" type"+(ressources.length>1?"s":""):"Selectionner des "+ressourceType+"s"}</ThemedText>
                {isOpen && RessourceSearch()}
            </ThemedButton>
            
      
    )
}

const styles = StyleSheet.create({

  centeredText:{
    textAlign: 'center',
  },
  overlay:{
    backgroundColor:'#00000080',
    padding:"5%",
    paddingVertical:"20%",
    width:"100%",
    height:"100%",
  },
  overlayView:{
    borderRadius: 20,
    padding: 20,
    alignItems: "center",
    width: "100%",
    height: "100%",
    //backgroundColor:'#ff0000',
  },
  buttonValid:{
    //borderWidth: 2,
    width:'100%',
    margin: 0,
    borderRadius: 15,
    padding: 10,
    height:60,
    alignItems: "center",
    justifyContent: 'center',
  },
  
});
