import { useChantier } from "@/app/ContextChantier";
import { Chantier } from "@/class/class";
import { getChantiers } from "@/services/ressourcesService";
import { useRouter } from "expo-router";
import { useEffect, useState } from "react";
import {
  ActivityIndicator,
  Dimensions,
  FlatList,
  Image,
  Pressable,
  ScrollView,
  StyleSheet,
  View
} from "react-native";
import Animated, {
  interpolate,
  LinearTransition,
  useAnimatedStyle,
  useSharedValue,
  withTiming
} from "react-native-reanimated";
import { ThemedButton } from "@/components/theme/themed-button";
import { ThemedText } from "@/components/theme/themed-text";
import { ThemedTextInput } from "@/components/theme/themed-textinput";
import { ThemedView } from "@/components/theme/themed-view";

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

/*

<ThemedView style={{width:"100%", position: 'absolute', backgroundColor:'transparent',}}>
  <SelectChantier ></SelectChantier>
</ThemedView>

*/

export default function SelectChantier() {
  const { chantier, setChantier } = useChantier();
  const [search, setSearch] = useState("");
  const [isOpen, setIsOpen] = useState(false);
  const [isLoaded, setIsLoaded] = useState(false);
  const [chantiers, setChantiers] = useState<Chantier[]>([]);
  const router = useRouter();

  
  const AnimatedThemedView = Animated.createAnimatedComponent(ThemedView);
  const AnimatedThemedText = Animated.createAnimatedComponent(ThemedText);
  const AnimatedThemedButton = Animated.createAnimatedComponent(ThemedButton);
  const AnimatedThemedTextInput =
    Animated.createAnimatedComponent(ThemedTextInput);

  async function onPressOpen(){
    setIsLoaded(false);
    setIsOpen(!isOpen);
    if(!isOpen){
      const updatedChantiers = await getChantiers();
      setIsLoaded(true);
      setChantiers(updatedChantiers)
    }
  }

    useEffect(() => {
    open.value = withTiming(isOpen ? 1 : 0);
  }, [isOpen]);

  useEffect(() => {
    async function loadChantiers() {
      const list = await getChantiers();
      setChantiers(list);
    }

    loadChantiers();
  }, []);

  const filteredChantiers = chantiers.filter((chantier) => {
    var keyWords:string[] = search.toLowerCase().split(" ") ;
    var containsAllKeyWord:boolean = true;
    keyWords.forEach(keyWord => {
      containsAllKeyWord = containsAllKeyWord && (chantier.adresse.toLowerCase().includes(keyWord) || chantier.name.toLowerCase().includes(keyWord))
    });
    return containsAllKeyWord
  });

  function selectChantier(chantier: Chantier): void {
    setChantier(chantier);
    setIsOpen(false);
  }


  const open = useSharedValue(0);

  const animatedWindowStyle = useAnimatedStyle(() => {
    return {
      width: `${interpolate(open.value, [0, 1], [50, 100])}%`,
      height: interpolate(
        open.value,
        [0, 1],
        [60, screenHeight * 0.75]
      ),
      padding: 10,
      overflow: "hidden",
      zIndex: 1000,
    };
  });

  const animatedButtonStyle = useAnimatedStyle(() => ({
    width: `${interpolate(open.value, [0, 1], [100, 50])}%`,
    margin: interpolate(open.value, [0, 1], [0, 5]),
    borderRadius: interpolate(open.value, [0, 1], [15, 10]),
    padding: 10,
    height: 40,
  }));


  const renderChantier = ({ item }: { item:Chantier }) => {
    return (
        <Pressable onPress={() => selectChantier(item)}>
          <ThemedView lvl={4} style={styles.chantier}>
            <View>
              <Image source={{ uri:"https://cdn.discordapp.com/attachments/1425108443571945644/1427207643180826757/raw.png?ex=693f1a72&is=693dc8f2&hm=86ffb97145fc8d3aec822b87d99be233c98477d4424c1ef58f80eb81b17c7c80&" /*chantier.urlImg*/ }} style={styles.image} />
            </View>
            <View style={{flex: 1}}>
            <ThemedText>Renovation: {item.name}</ThemedText>
              <ThemedText>Adresse: {item.adresse}</ThemedText>
              <ThemedText>Chef de chantier: {item.chef.last_name}{" "}{item.chef.name}</ThemedText>
              <ThemedText>État: {item.etat}</ThemedText>
            </View>
          </ThemedView>
        </Pressable>
    );
  };

  return (
    <Animated.View style={animatedWindowStyle}>
      {isOpen && (<Pressable style={styles.autoClose} onPress={() => setIsOpen(false)}/>)}
      <ThemedView lvl={2} shadow={true} style={styles.window}>
        <AnimatedThemedButton style={animatedButtonStyle} lvl={isOpen ? 1 : 1} onPress={() => onPressOpen()}>
          <ThemedText style={styles.buttonText}>
            {isOpen ? "Fermer" : (chantier!=null ? chantier.adresse : "Chantier")}
          </ThemedText>
        </AnimatedThemedButton>
        {isOpen && (
          <View style={styles.menu}>

            <ThemedTextInput lvl={1} border={4} style={styles.input} placeholder="Rechercher un chantier" value={search} onChangeText={setSearch}/>
            <View style={styles.list}>
              {isLoaded?
                <FlatList
                data={filteredChantiers}
                renderItem={renderChantier}
                keyExtractor={(_, index) => index.toString()}
                contentContainerStyle={{ gap: 8 }}
                />



              : <ActivityIndicator style={{height:"100%"}} color="#808080" size="large" />}
            </View>

        </View>
        )}
      </ThemedView>
    </Animated.View>
  );
}


const styles = StyleSheet.create({
  windowClose: {
    //backgroundColor: '#00FF0040',
    //borderRadius:10,
    padding: 10,
    width: "50%",
    height: 60,
    overflow: "hidden",
    zIndex:1000,
  },
  windowOpean: {
    //backgroundColor: '#00FF0040',
    //borderRadius:10,
    width: "100%",
    height: screenHeight * 3/4,
    padding: 10,
    zIndex:1000,
  },
  window: {
    borderRadius: 15,
    height: "100%",
    //backgroundColor: '#00FF00',
    overflow: "hidden",
  },
    autoClose: {
    
    position: 'absolute',
    top: -height,
    left: -width,
    width:width*2,
    height:height*2,
    //backgroundColor: 'rgba(255, 0, 0, 0.5)',
  },
  menu: {
    padding: 5,
    flex: 1,
    minHeight: 0,
    //backgroundColor:'#FF00FF',
  },
  list: {
    flex: 1,
    overflow: "hidden",
    borderRadius: 10,
  },
  chantiersList: {
    //padding:5,
    //backgroundColor:'0000FF',
    //flexDirection: 'row',
    //alignItems: 'center',
    gap: 8,
  },
  chantier: {
    padding: 5,
    //marginTop:5,
    //margin:5,
    borderRadius: 10,
    //borderWidth: 1,
    flexDirection: 'row',
    //height: 130,
  },
  image:{
    margin:0,
    width: 60,
    height: 90,
    borderRadius: 5,
    marginRight: 10,
  },
  input: {
    width: "100%",
    borderWidth: 1,
    borderRadius: 10,
    padding: 10,
    fontSize: 16,
    marginBottom: 10,
  },
  buttonClose: {
    width: "100%",
    margin: 0,
    borderRadius: 15,
    padding: 10,
    height: 40,
  },
  buttonOpen: {
    width: "50%",
    margin: 5,
    borderRadius: 10,
    padding: 10,
    height: 40,
  },
  buttonText: {
    textAlign: "center",
  },
});
