import React, { useEffect, useState, useSyncExternalStore } from "react";
import { View, StyleSheet, Text, Button, TouchableHighlight, Image } from "react-native";
import { useDispatch } from "react-redux";
import { City, FAVORITE_CITY_DATA, getCurrentWeather, Weather } from "../data/stub";
import { addFavoriteCity } from "../redux/actions/addFavoriteCity";


type VilleProps = {
    weather: Weather,
    fav: City | null
}


export function VilleCompopo(props: VilleProps){
  const dispatch = useDispatch();


  async function changeFavoriteCity(city: City | null, already: boolean) {
    if (already){
      city = null
    }
    dispatch(addFavoriteCity(city))
  }

  const isFavorite = props.fav != null && props.weather.city.longitude===props.fav.longitude && props.weather.city.latitude===props.fav.latitude

  return (
      <View style={styles.container}>
        <View style={{flex: 1, flexDirection: "row", justifyContent: "space-between"}}>
          <View style={styles.bothtext}>
            <Text style={styles.title}>{props.weather.city.name}</Text>
            <Text>{props.weather.city.latitude} - {props.weather.city.longitude}</Text>
          </View>
          <View style={{flexDirection: "row", alignItems: "center"}}>
            <Text style={styles.title}>{props.weather.temperature}</Text>
            <TouchableHighlight onPress={() => changeFavoriteCity(props.weather.city, isFavorite)}>
              <Image source={ isFavorite ? require('../assets/yellowstar.png') : require('../assets/blackstar.png')} style={styles.button}/>
            </TouchableHighlight>
          </View>
        </View>
      </View>
    );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "darksalmon",
    marginVertical: 5,
    borderRadius: 15,
    width: "90%",
    alignSelf: 'center'
  },
  title: {
    fontWeight: "bold",
    fontSize: 18
  },
  bothtext: {
    margin: 10
  },
  temperature: {
    marginTop: 20,
    fontSize: 18,
    fontWeight: "bold"
  },
  button: {
    height: 30,
    width: 30,
    alignSelf: "flex-end",
    marginRight: "5%",
    marginLeft: "10%"
  },

});