import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { Image } from "expo-image";
import { useRouter } from "expo-router";
import { useMemo, useState } from "react";
import { FlatList, Pressable, StyleSheet, Text, TextInput, View, useWindowDimensions } from "react-native";

import { EmptyState, ScreenHeader } from "@/components/iptv-ui";
import { ScreenContainer } from "@/components/screen-container";
import { useColors } from "@/hooks/use-colors";
import { useIptv } from "@/lib/iptv/store";

export default function MoviesScreen() {
  const router = useRouter();
  const colors = useColors("dark");
  const { width } = useWindowDimensions();
  const { catalog, isFavorite, toggleFavorite } = useIptv();
  const [search, setSearch] = useState("");
  const [category, setCategory] = useState("all");
  const cardWidth = Math.floor((width - 18 * 2 - 12) / 2);
  const filtered = useMemo(() => catalog.movies.filter((item) => {
    const matchesSearch = item.name.toLowerCase().includes(search.trim().toLowerCase());
    const matchesCategory = category === "all" || String(item.category_id) === category;
    return matchesSearch && matchesCategory;
  }), [catalog.movies, search, category]);

  return (
    <ScreenContainer>
      <FlatList
        data={filtered}
        numColumns={2}
        keyExtractor={(item) => `movie-${item.stream_id}`}
        contentContainerStyle={styles.content}
        columnWrapperStyle={styles.column}
        showsVerticalScrollIndicator={false}
        ListHeaderComponent={<>
          <ScreenHeader title="Filmes" subtitle={`${filtered.length} títulos disponíveis`} />
          <SearchBox value={search} onChangeText={setSearch} placeholder="Buscar filmes" />
          <FlatList data={[{ category_id: "all", category_name: "Todos" }, ...catalog.movieCategories]} horizontal showsHorizontalScrollIndicator={false} keyExtractor={(item) => `movie-cat-${item.category_id}`} contentContainerStyle={styles.categoryList} renderItem={({ item }) => <Pressable onPress={() => setCategory(item.category_id)} style={({ pressed }) => [styles.categoryPill, { backgroundColor: category === item.category_id ? colors.primary : colors.surface, borderColor: category === item.category_id ? colors.primary : colors.border }, pressed && { opacity: 0.7 }]}><Text style={[styles.categoryText, { color: category === item.category_id ? "#F4F7FB" : colors.muted }]}>{item.category_name}</Text></Pressable>} />
        </>}
        renderItem={({ item }) => <PosterTile width={cardWidth} title={item.name} image={item.stream_icon} isFavorite={isFavorite(`movie:${item.stream_id}`)} onFavorite={() => toggleFavorite(`movie:${item.stream_id}`)} onPress={() => router.push({ pathname: "/movie/[id]" as never, params: { id: String(item.stream_id), title: item.name, image: item.stream_icon || "", plot: item.plot || "", year: String(item.year || ""), rating: String(item.rating || ""), extension: item.container_extension || "mp4" } })} />}
        ListEmptyComponent={<EmptyState icon="movie" title="Nenhum filme encontrado" message={catalog.movies.length === 0 ? "A fonte conectada ainda não retornou filmes." : "Tente outra busca ou categoria."} />}
      />
    </ScreenContainer>
  );
}

function SearchBox({ value, onChangeText, placeholder }: { value: string; onChangeText: (value: string) => void; placeholder: string }) {
  const colors = useColors("dark");
  return <View style={[styles.searchWrap, { backgroundColor: colors.surface, borderColor: colors.border }]}><MaterialIcons name="search" size={20} color={colors.muted} /><TextInput value={value} onChangeText={onChangeText} placeholder={placeholder} placeholderTextColor={colors.muted} style={[styles.searchInput, { color: colors.foreground }]} returnKeyType="search" />{value ? <Pressable onPress={() => onChangeText("")} hitSlop={8}><MaterialIcons name="close" size={18} color={colors.muted} /></Pressable> : null}</View>;
}

function PosterTile({ width, title, image, isFavorite, onFavorite, onPress }: { width: number; title: string; image?: string; isFavorite: boolean; onFavorite: () => void; onPress: () => void }) {
  const colors = useColors("dark");
  return <Pressable onPress={onPress} style={({ pressed }) => [{ width, marginBottom: 17 }, pressed && { opacity: 0.74, transform: [{ scale: 0.985 }] }]}><View style={[styles.poster, { backgroundColor: colors.surface }]}>{image ? <Image source={{ uri: image }} contentFit="cover" transition={160} style={StyleSheet.absoluteFillObject} /> : <View style={styles.posterFallback}><MaterialIcons name="movie" size={30} color={colors.muted} /></View>}<Pressable onPress={onFavorite} hitSlop={8} style={({ pressed }) => [styles.favorite, pressed && { opacity: 0.55 }]}><MaterialIcons name={isFavorite ? "favorite" : "favorite-border"} size={18} color={isFavorite ? "#FF6B7A" : "#F4F7FB"} /></Pressable></View><Text numberOfLines={2} style={[styles.posterTitle, { color: colors.foreground }]}>{title}</Text></Pressable>;
}

const styles = StyleSheet.create({
  content: { paddingHorizontal: 18, paddingTop: 18, paddingBottom: 30, flexGrow: 1 },
  column: { justifyContent: "space-between" },
  searchWrap: { minHeight: 48, borderWidth: 1, borderRadius: 14, flexDirection: "row", alignItems: "center", paddingHorizontal: 13, gap: 9 },
  searchInput: { flex: 1, minHeight: 46, fontSize: 14 },
  categoryList: { gap: 8, paddingVertical: 14 },
  categoryPill: { borderWidth: 1, borderRadius: 999, paddingHorizontal: 14, paddingVertical: 8 },
  categoryText: { fontSize: 12, fontWeight: "700" },
  poster: { width: "100%", height: 220, borderRadius: 16, overflow: "hidden", position: "relative" },
  posterFallback: { flex: 1, alignItems: "center", justifyContent: "center" },
  favorite: { position: "absolute", top: 9, right: 9, width: 30, height: 30, borderRadius: 15, backgroundColor: "rgba(9,17,31,0.78)", alignItems: "center", justifyContent: "center" },
  posterTitle: { fontSize: 13, lineHeight: 18, fontWeight: "700", marginTop: 8 },
});
