import { ThemedText } from "@/components/themed-text";
import { ThemedTextInput } from "@/components/themed-textinput";
import { ThemedView } from "@/components/themed-view";
import { ThemedButton } from "@/components/themed-button";
import { useLocalSearchParams, useRouter } from "expo-router";
import React, { useEffect, useState } from "react";
import { FlatList, Image, StyleSheet, Text } from "react-native";
import { Ressources } from "../../class/class";
import { getRessources } from "../../services/ressourcesService";

export default function GestionnaireRessource() {
  const { nom, prenom } = useLocalSearchParams();
  const [search, setSearch] = useState("");
  const [ressource, setRessources] = useState<Ressources[]>([]);
  const [filterType, setFilterType] = useState("tout");
  const [showFilterMenu, setShowFilterMenu] = useState(false);
  const router = useRouter();

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

  const filteredData = ressource.filter((r) => {
    const matchName = r.name.toLowerCase().includes(search.toLowerCase());
    const matchType = filterType === "tout" || r.type === filterType;
    return matchName && matchType;
  });

  const renderRessource = ({ item }: { item: Ressources }) => {
    if (!item) return null;
    return (
      <ThemedView lvl={1} shadow={true} style={styles.card}>
        <Image source={{ uri: item.Image }} style={styles.image} />
        <ThemedView lvl={1} style={styles.info}>
          <ThemedText>{item.id}</ThemedText>
          <ThemedText>{item.name}</ThemedText>
          <ThemedText>{item.type}</ThemedText>
          <ThemedText>{item.quantity}</ThemedText>
          <ThemedText>{item.available_quantity}</ThemedText>
        </ThemedView>
      </ThemedView>
    );
  };

  return (
    <ThemedView lvl={3} style={styles.container}>
      {/* Overlay menu filtre */}
      {showFilterMenu && (
        <ThemedView lvl={2} style={styles.filterMenuOverlay}>
          <ThemedView lvl={1} style={styles.filterMenu}>
            <Text style={styles.filterTitle}>Filtrer par type</Text>
            {["tout", "Outil", "Machine"].map((t) => (
              <ThemedButton
                key={t}
                lvl={1}
                shadow={true}
                style={{ padding: 10, borderRadius: 8, marginBottom: 10 }}
                onPress={() => {
                  setFilterType(t);
                  setShowFilterMenu(false);
                }}
              >
                <ThemedText style={{ textAlign: "center" }}>{t}</ThemedText>
              </ThemedButton>
            ))}

            {/* Bouton "Fermer" remplacé */}
            <ThemedButton
              lvl={1}
              shadow={true}
              style={{ padding: 10, borderRadius: 8 }}
              onPress={() => setShowFilterMenu(false)}
            >
              <ThemedText style={{ textAlign: "center" }}>Fermer</ThemedText>
            </ThemedButton>
          </ThemedView>
        </ThemedView>
      )}

      <FlatList
        data={filteredData}
        renderItem={renderRessource}
        keyExtractor={(_, index) => index.toString()}
        contentContainerStyle={{ paddingBottom: 40 }}
        ListHeaderComponent={
          <ThemedView opacity="00" style={styles.header}>
            <ThemedText style={styles.text}>
              Bonjour {prenom} {nom}
            </ThemedText>

            {/* Bouton filtre en haut à droite */}
            <ThemedButton
              lvl={1}
              shadow={true}
              style={{ padding: 10, borderRadius: 8, marginBottom: 10 }}
              onPress={() => setShowFilterMenu(true)}
            >
              <ThemedText>{`Filtre: ${filterType}`}</ThemedText>
            </ThemedButton>

            <ThemedView lvl={1} shadow={true} style={styles.inputBack}>
              <ThemedTextInput
                lvl={0}
                style={styles.input}
                placeholder="Rechercher une ressource..."
                value={search}
                onChangeText={setSearch}
              />
            </ThemedView>
          </ThemedView>
        }
        ListEmptyComponent={
          <ThemedText style={styles.empty}>Aucun résultat trouvé</ThemedText>
        }
      />
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 60,
  },
  header: {
    marginBottom: 20,
    alignItems: "center",
    paddingHorizontal: 20,
  },
  text: {
    fontSize: 22,
    fontWeight: "bold",
    marginBottom: 10,
  },
  inputBack: {
    width: "100%",
    borderRadius: 10,
    backgroundColor: "transparent",
  },
  input: {
    width: "100%",
    borderRadius: 10,
    padding: 10,
    fontSize: 16,
  },
  card: {
    flexDirection: "row",
    marginHorizontal: 20,
    marginBottom: 15,
    borderRadius: 10,
    padding: 10,
  },
  image: {
    width: 80,
    height: 80,
    borderRadius: 8,
    marginRight: 10,
  },
  info: {
    flex: 1,
    justifyContent: "center",
  },
  footer: {
    padding: 20,
  },
  empty: {
    textAlign: "center",
    marginTop: 30,
    color: "#888",
  },
  filterMenuOverlay: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: "rgba(0,0,0,0.4)",
    justifyContent: "center",
    alignItems: "center",
    zIndex: 999,
  },
  filterMenu: {
    width: "80%",
    borderRadius: 12,
    padding: 20,
    backgroundColor: "#fff",
  },
  filterTitle: {
    fontSize: 18,
    fontWeight: "bold",
    marginBottom: 20,
    textAlign: "center",
  },
});
