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 '@/components/add/select/ressourceSummary';

type RessourcesQte = [Ressources, number];

type Props = {
    sendMachines: (machine: RessourcesQte[]) => void;
    style?: StyleProp<ViewStyle>;
};

export default function SelectMachine({style,sendMachines: sendMachines , ...otherProps }: Props) {

    const [machines, setMachines] = useState<RessourcesQte[]>([]);
    const [isOpen,setIsOpen] = useState(false);
    const [listMachines,setListMachines] = useState<Ressources[]>([]);

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


    useEffect(() => {
      sendMachines(machines);
    }, [machines])
  

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

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

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




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


    const MachineSearch = () => {
      return(
        <Modal transparent={true}>
          <View style={styles.overlay}>
            <ThemedView style={styles.overlayView}>
                <ThemedText style={{fontSize: 25}}>Rechercher des machines :</ThemedText>
                <FlatList
                  style={{width:"100%"}}
                  data={listMachines}
                  renderItem={MachineSummaryItem}
                  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}>{machines? getTotalMachine()+" machine(s) sélectionné dont "+ machines.length+" différente":"sélectionner des machine(s)"}</ThemedText>
                {isOpen && MachineSearch()}
            </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',
  },
  
});
