import { useChantier } from "@/app/ContextChantier";
import { Chantier } from "@/class/class";
import { getChantiers } from "@/services/ressourcesService";
import { useEffect, useState } from "react";
import {
  Dimensions,
  Image,
  Pressable,
  ScrollView,
  StyleSheet,
  View
} from "react-native";
import Animated, {
  LinearTransition
} from "react-native-reanimated";
import { ThemedButton } from "./themed-button";
import { ThemedText } from "./themed-text";
import { ThemedTextInput } from "./themed-textinput";
import { ThemedView } from "./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(props: {
  data?: any[];
  multiple?: boolean;
  selected?: string[] | string | null;
  onChange?: (val: any) => void;
  placeholder?: string;
}) {
  const { data: propData, multiple = false, selected, onChange, placeholder } = props || {};
  const { chantier, setChantier } = useChantier();
  const [search, setSearch] = useState("");
  const [isOpen, setIsOpen] = useState(false);
  const [chantiers, setChantiers] = useState<any[]>([]);

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

  async function onPressOpen(){
    setIsOpen(!isOpen);
    if(!isOpen){
      if (propData && propData.length) {
        setChantiers(propData as any[]);
      } else {
        const updatedChantiers = await getChantiers();
        setChantiers(updatedChantiers);
      }
    }
  }

  function onPressAddChantier(){

  }

  useEffect(() => {
    // If parent provided data, use it. Otherwise fetch chantiers.
    if (propData && propData.length) {
      setChantiers(propData as any[]);
      return;
    }

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

    loadChantiers();
  }, []);

  function getId(item: any) {
    return (item && (item.id ?? item._id ?? item.uid ?? item.key)) ?? String(item);
  }

  function getLabel(item: any) {
    if (!item) return String(item);
    if (item.adresse) return item.adresse;
    if (item.nom) return item.nom;
    if (item.name && item.last_name) return `${item.last_name} ${item.name}`;
    if (item.name) return item.name;
    if (item.label) return item.label;
    if (typeof item === 'string') return item;
    return JSON.stringify(item);
  }

  function selectChantier(item: any): void {
    const id = String(getId(item));
    if (multiple) {
      // for multiple selection toggle id in selected array
      const current = Array.isArray(selected) ? [...selected] : [];
      const idx = current.indexOf(id);
      if (idx >= 0) current.splice(idx, 1);
      else current.push(id);
      onChange?.(current);
      // keep menu open for multiple selection
      return;
    }

    // single selection
    if (onChange) {
      onChange(id);
    } else {
      // fallback behavior for old usage: if selecting a Chantier, update context
      setChantier(item as Chantier);
    }
    setIsOpen(false);
  }

  const renderChantier = (item: any, index: number) => {
    const label = getLabel(item);
    const id = String(getId(item));
    const isSelected = Array.isArray(selected) ? selected.includes(id) : selected === id;
    return (
        <Pressable key={index} onPress={() => selectChantier(item)}>
          <ThemedView lvl={4} style={[styles.chantier, isSelected ? { borderWidth: 1 } : {}]}>
            <View>
              <Image source={{ uri: "https://cdn.discordapp.com/attachments/1425108443571945644/1427207643180826757/raw.png?ex=69392bb2&is=6937da32&hm=dcc09e76d3dca89d2418947b46efbd38673b9dc559027724b2e51d493b173bc9&" }} style={styles.image} />
            </View>
            <View>
              <ThemedText>{label}</ThemedText>
            </View>
          </ThemedView>
        </Pressable>
    );
  };

  return (
    <Animated.View layout={LinearTransition.duration(200)} style={isOpen ? styles.windowOpean : styles.windowClose}>
      {isOpen && (<Pressable style={styles.autoClose} onPress={() => setIsOpen(false)}/>)}
      <AnimatedThemedView layout={LinearTransition.duration(200)} lvl={2} shadow={true} style={styles.window}>
        <AnimatedThemedButton style={isOpen ? styles.buttonOpen : styles.buttonClose} lvl={isOpen ? 1 : 1} onPress={() => onPressOpen()}>
          <ThemedText style={styles.buttonText}>
            {isOpen
              ? "Fermer"
              : (multiple
                  ? (Array.isArray(selected) && selected.length ? `${selected.length} sélectionnés` : (placeholder ?? "Sélectionner"))
                  : (selected ? (() => {
                      // show label of selected single item if provided in propData
                      if (selected && propData) {
                        const found = propData.find((it: any) => String(getId(it)) === String(selected));
                        return found ? getLabel(found) : (chantier ? (chantier.adresse ?? getLabel(chantier)) : (placeholder ?? "Chantier"));
                      }
                      return chantier ? (chantier.adresse ?? getLabel(chantier)) : (placeholder ?? "Chantier");
                    })() : (placeholder ?? "Chantier"))
                )}
          </ThemedText>
        </AnimatedThemedButton>
        {isOpen && (
          <View style={styles.menu}>

            <ThemedTextInput lvl={1} border={4} style={styles.input} placeholder="Rechercher un chantier" value={search} onChangeText={setSearch}/>

            <ThemedButton style={styles.buttonAdd} onPress={() => onPressAddChantier()}>
              <ThemedText style={styles.buttonText}>
                +
              </ThemedText>
            </ThemedButton>

            <ThemedView lvl={2} style={styles.list}>
              <ScrollView contentContainerStyle={styles.chantiersList}>
                {chantiers.map((chantier, index) =>
                  renderChantier(chantier, index)
                )}
              </ScrollView>
            </ThemedView>
        </View>
        )}
      </AnimatedThemedView>
    </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: 100,
  },
  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",
  },
  buttonAdd:{
    borderRadius: 10,
    marginBottom: 10,
  }
});
