import {
  FlatList,
  RefreshControl,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import React, { useEffect } from "react";
import { Film } from "@/types/film";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { FAVORITES_KEY } from "@/constants/keys";
import { COLORS } from "@/constants/colors";
import FilmItem from "@/components/FilmItem";
import ListEmptyComponent from "@/components/ListEmptyComponent";
import { Ionicons } from "@expo/vector-icons";
import { useFocusEffect } from "expo-router";

const Page = () => {
  const [favorites, setFavorites] = React.useState<Film[]>([]);
  const [refreshing, setRefreshing] = React.useState(false);

  const fetchFavorites = async () => {
    try {
      const favorites = await AsyncStorage.getItem(FAVORITES_KEY);
      if (favorites) {
        setFavorites(JSON.parse(favorites) as Film[]);
      }
    } catch (error) {
    } finally {
      setRefreshing(false);
    }
  };

  const onRefresh = () => {
    setRefreshing(true);
    fetchFavorites();
  };

  const removeFavorite = async (film: Film) => {
    const updatedFavorites = favorites.filter(
      (f) => f.episode_id !== film.episode_id,
    );
    try {
      setFavorites(updatedFavorites);
      await AsyncStorage.setItem(
        FAVORITES_KEY,
        JSON.stringify(updatedFavorites),
      );
    } catch (error) {
      console.error(error);
    }
  };

  const renderItem = ({ item }: { item: Film }) => (
    <View style={styles.itemContainer}>
      <Text style={styles.itemText}>{item.title}</Text>
      <TouchableOpacity onPress={() => removeFavorite(item)}>
        <Ionicons name="trash-outline" size={24} color={COLORS.text} />
      </TouchableOpacity>
    </View>
  );

  useFocusEffect(
    React.useCallback(() => {
      fetchFavorites();
    }, []),
  );

  return (
    <View style={styles.container}>
      <FlatList
        data={favorites}
        renderItem={renderItem}
        keyExtractor={(item) => item.episode_id.toString()}
        refreshing={refreshing}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={COLORS.text}
          />
        }
        ListEmptyComponent={() => <ListEmptyComponent loading={false} />}
      />
    </View>
  );
};

export default Page;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.containerBackground,
  },
  itemContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    backgroundColor: COLORS.itemBackground,
    padding: 16,
    marginVertical: 8,
    marginHorizontal: 16,
    borderRadius: 8,
  },
  itemText: {
    fontSize: 16,
    color: COLORS.text,
  },
});
