import React, { useState } from "react";
import { View, TextInput, StyleSheet } from "react-native";
import Button from "@/components/Button";
import AppText from "@/components/AppText";
import { useUsers } from "@/contexts/UserContext";

type Props = {
  visible: boolean;
  onClose: () => void;
  sectionKey: string | null;
  sectionLabel: string | null;
};

const AddItemPopup: React.FC<Props> = ({
  visible,
  onClose,
  sectionKey,
  sectionLabel
}) => {

  const { currentUser, updateCurrentUser } = useUsers();
  const [text, setText] = useState("");

  if (!visible) return null;

  if (!sectionKey) {
    console.warn("❌ AddItemPopup — sectionKey est NULL → impossible d'ajouter");
    return null;
  }

  const handleSave = () => {
    if (!text.trim()) return;

    const newItem = {
      text,
      date: new Date().toISOString(),
      qui: currentUser?.username || "User"
    };

    const previousItems = currentUser?.dossier?.[sectionKey] || [];

    console.log("🟦 AJOUT — sectionKey =", sectionKey);
    console.log("🟦 AJOUT — ancien tableau =", previousItems);
    console.log("🟦 AJOUT — newItem =", newItem);

    const updatedItems = [...previousItems, newItem];

    console.log("🟦 AJOUT — nouveau tableau =", updatedItems);

    updateCurrentUser({
      dossier: {
        ...currentUser.dossier,
        [sectionKey]: updatedItems
      }
    });

    console.log("🟩 SAUVEGARDE EFFECTUÉE — chemin =", {
      dossier: {
        ...currentUser.dossier,
        [sectionKey]: updatedItems
      }
    });

    setText("");
    onClose();
  };

  return (
    <View style={styles.overlay}>
      <View style={styles.popup}>
        <AppText
          text={`Ajouter ${sectionLabel ?? ""}`}
          style={styles.title}
        />

        <View style={styles.inputContainer}>
          <TextInput
            style={styles.input}
            multiline
            value={text}
            onChangeText={setText}
            placeholder={`Nouveau ${sectionLabel ?? ""}...`}
          />
        </View>

        <View style={styles.buttonRow}>
          <View style={styles.buttonSmall}>
            <Button text="Annuler" onPress={onClose} />
          </View>

          <View style={styles.buttonSmall}>
            <Button text="Valider" isSelected onPress={handleSave} />
          </View>
        </View>

      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  overlay: {
    position: "absolute",
    top: 0, left: 0, right: 0, bottom: 0,
    backgroundColor: "rgba(0,0,0,0.5)",
    justifyContent: "center",
    alignItems: "center"
  },
  popup: {
    width: "90%",
    maxHeight: "85%",
    minHeight: "85%",
    backgroundColor: "white",
    padding: 20,
    borderRadius: 10,
    display: "flex"
  },

  inputContainer: {
    flex: 1,
    borderWidth: 1,
    borderColor: "#ccc",
    borderRadius: 8,
    padding: 10,
    marginBottom: 15
  },

  input: {
    flex: 1,
    textAlignVertical: "top",
    padding: 0
  },

  buttonRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginTop: 10
  },

  buttonSmall: {
    width: "45%"
  }
});

export default AddItemPopup;
