import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, TouchableOpacity, Button, TextInput, StyleSheet } from 'react-native';
import { collection, addDoc, query, where, getDocs, deleteDoc, doc } from 'firebase/firestore';
import { db, auth } from '../config/firebase';

function ProjectsScreen({ navigation }: any) {
  const [projects, setProjects] = useState<any[]>([]);
  const [name, setName] = useState('');

  useEffect(() => {
    loadProjects();
  }, []);

  const loadProjects = async () => {
    const q = query(collection(db, 'projects'), where('userId', '==', auth.currentUser!.uid));
    const snapshot = await getDocs(q);
    setProjects(snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })));
  };

  const addProject = async () => {
    await addDoc(collection(db, 'projects'), {
      name,
      userId: auth.currentUser!.uid,
      status: 'aktív',
    });
    setName('');
    loadProjects();
  };

  const deleteProject = async (id: string) => {
    await deleteDoc(doc(db, 'projects', id));
    loadProjects();
  };

  return (
    <View style={styles.container}>
      <TextInput style={styles.input} placeholder="Projekt név" value={name} onChangeText={setName} />
      <Button title="Hozzáadás" onPress={addProject} />
      <FlatList
        data={projects}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <TouchableOpacity
            style={styles.item}
            onPress={() => navigation.navigate('Details', { project: item })}
          >
            <Text>{item.name} - {item.status}</Text>
            <TouchableOpacity onPress={() => deleteProject(item.id)}>
              <Text>🗑️</Text>
            </TouchableOpacity>
          </TouchableOpacity>
        )}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16 },
  input: { borderWidth: 1, padding: 8, marginBottom: 8, borderRadius: 4 },
  item: { padding: 16, borderBottomWidth: 1, flexDirection: 'row', justifyContent: 'space-between' },
});

export default ProjectsScreen;
