// ProfileScreen.js
import React, { useEffect, useState, useCallback } from 'react';
import { Image, View, Text, StyleSheet, TouchableOpacity, Alert, ScrollView } from 'react-native';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
import PropTypes from 'prop-types';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import { auth, db } from '../utils/firebase';
import { doc, getDoc } from 'firebase/firestore';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useVocabulary } from './VocabularyContext';
import { Ionicons } from '@expo/vector-icons';
import HeartedStories from './HeartedStories'; // Güncellenmiş HeartedStories bileşeni

const ProfileScreen = ({ route }) => {
  const { theme, t, locale } = useThemeAndLanguage();
  const navigation = useNavigation();
  const { logout } = useVocabulary();
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [user, setUser] = useState(null);
  const [displayName1, setDisplayName1] = useState('');
  const [catImageUrl, setCatImageUrl] = useState('https://cataas.com/cat?width=300&height=300');
  const [coverImageUrl, setCoverImageUrl] = useState('https://picsum.photos/800/300');

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged(fetchUserData);
    return () => unsubscribe();
  }, []);

  useFocusEffect(
    useCallback(() => {
      const currentUser = auth.currentUser;
      if (currentUser) {
        fetchUserData(currentUser);
      } else if (route.params?.refresh) {
        fetchUserData();
      }
    }, [route.params?.refresh])
  );

  const fetchUserData = async (currentUser) => {
    if (currentUser) {
      setIsLoggedIn(true);
      setUser(currentUser);

      const userDoc = doc(db, 'users', currentUser.uid);
      const docSnap = await getDoc(userDoc);

      if (docSnap.exists()) {
        setDisplayName1(docSnap.data().displayName1 || '');
        await AsyncStorage.setItem('displayName1', docSnap.data().displayName1 || '');
      } else {
        console.log('No such document!');
      }
    } else {
      setIsLoggedIn(false);
      setUser(null);
      setDisplayName1('');
      await AsyncStorage.removeItem('displayName1');
    }
  };

  const handleLogout = async () => {
    try {
      await auth.signOut();
      await AsyncStorage.clear();
      await logout();
    } catch (error) {
      Alert.alert('Error', error.message);
    }
  };

  const refreshImages = () => {
    const newCatImageUrl = `https://cataas.com/cat?width=300&height=300&timestamp=${new Date().getTime()}`;
    const newCoverImageUrl = `https://picsum.photos/800/300?timestamp=${new Date().getTime()}`;
    setCatImageUrl(newCatImageUrl);
    setCoverImageUrl(newCoverImageUrl);
  };

  return (
    <ScrollView style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
      {isLoggedIn && user ? (
        <View>
          <View style={styles.coverImageContainer}>
            <Image
              source={{ uri: coverImageUrl }}
              style={styles.coverImage}
              resizeMode="cover"
            />
          </View>
          <View style={styles.profileInfo}>
            <Image
              source={{ uri: catImageUrl }}
              style={styles.profileImage}
              resizeMode="cover"
            />
            <Text style={[styles.username, { color: theme.textColor }]}>
              {displayName1 || 'Anonymous User'}
            </Text>
            <Text style={[styles.email, { color: theme.secondaryColor }]}>
              {user.email}
            </Text>
          </View>

          <View style={styles.buttonContainer}>
            <View style={styles.row}>
              <TouchableOpacity
                style={[styles.button, { backgroundColor: theme.primaryColor }]}
                onPress={refreshImages}
              >
                <Ionicons name="refresh" size={20} color={theme.textColor2} style={styles.buttonIcon} />
                <Text style={[styles.buttonText, { color: theme.textColor2 }]}>
                  {t('refreshImages')}
                </Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={[styles.button, { backgroundColor: theme.primaryColor }]}
                onPress={() => navigation.navigate('Settings')}
              >
                <Ionicons name="settings-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
                <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('settingsNav')}</Text>
              </TouchableOpacity>
            </View>

            <View style={styles.row}>
              <TouchableOpacity
                style={[styles.button, { backgroundColor: theme.primaryColor }]}
                onPress={() => navigation.navigate('EditProfile')}
              >
                <Ionicons name="create-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
                <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('editProfile')}</Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={[styles.button, { backgroundColor: theme.primaryColor }]}
                onPress={handleLogout}
              >
                <Ionicons name="log-out-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
                <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('logout')}</Text>
              </TouchableOpacity>
            </View>
          </View>

          {/* HeartedStories Bileşenini Burada Kullanıyoruz */}
          <HeartedStories />
        </View>
      ) : (
        <View style={styles.buttonContainer}>
          <Image
            source={require('../../assets/kabe.jpg')}
            style={styles.image}
            resizeMode="cover"
          />
          <Text style={[styles.title, { color: theme.textColor }]}>{t('loginToYourAccount')}</Text>
         
          <TouchableOpacity
            style={[styles.button, { backgroundColor: theme.primaryColor }]}
            onPress={() => navigation.navigate('Login')}
          >
            <Ionicons name="log-in-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
            <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('login')}</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.button, { backgroundColor: theme.primaryColor }]}
            onPress={() => navigation.navigate('Register')}
          >
            <Ionicons name="person-add-outline" size={20} color={theme.textColor2} style={styles.buttonIcon} />
            <Text style={[styles.buttonText, { color: theme.textColor2 }]}>{t('register')}</Text>
          </TouchableOpacity>
        </View>
      )}
    </ScrollView>
  );
};

ProfileScreen.propTypes = {
  route: PropTypes.object.isRequired,
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  coverImageContainer: {
    width: '100%',
    height: 200,
  },
  coverImage: {
    width: '100%',
    height: '100%',
  },
  profileInfo: {
    alignItems: 'center',
    marginTop: -75,
    paddingVertical: 10,
  },
  profileImage: {
    width: 150,
    height: 150,
    borderRadius: 75,
    borderWidth: 3,
    borderColor: '#fff',
  },
  username: {
    fontSize: 20,
    fontWeight: 'bold',
    marginTop: 5,
  },
  email: {
    fontSize: 14,
    color: '#888',
    marginTop: 5,
  },
  buttonContainer: {
    paddingHorizontal: 16,
    paddingVertical: 20,
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 15,
  },
  button: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 10,
    paddingHorizontal: 15,
    borderRadius: 8,
    flex: 1,
    marginHorizontal: 5,
  },
  buttonIcon: {
    marginRight: 8,
  },
  buttonText: {
    fontSize: 16,
  },
  image: {
    width: '100%',
    height: 250,
    borderRadius: 10,
    
  },
  title: {
    fontSize: 18,
    textAlign: 'center',
    marginBottom: 20,
  },
});

export default ProfileScreen; bu sayfadaki söyleyeceğim yerleri düzelt. profil girişi yapılmadan önceki butonlar   button: {
    width: '85%',
    padding: 15,
    borderRadius: 5,
    alignItems: 'center',
    marginTop: 15,
        elevation:2,

  },
  buttonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  }, bu şekilde olsunlar. kullanıcı girişi yapıldıktan sonraki 4 buton (edit,newprofilepicture,logout,settings) bunlar da şu an oldukları halde kalsınlar. height değerini 70px e sabitle bu 4 buton için.