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";
import type { LiveStream } from "@/lib/iptv/types";

export default function LiveScreen() {
  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.max(148, Math.floor((Math.min(width, 760) - 36 - 10) / 2));
  const filtered = useMemo(() => catalog.liveStreams.filter((item) => {
    const matchesSearch = item.name.toLowerCase().includes(search.trim().toLowerCase());
    const matchesCategory = category === "all" || String(item.category_id) === category;
    return matchesSearch && matchesCategory;
  }), [catalog.liveStreams, search, category]);

  return (
    <ScreenContainer>
      <FlatList
        data={filtered}
        numColumns={2}
        keyExtractor={(item) => `live-${item.stream_id}`}
        contentContainerStyle={styles.content}
        columnWrapperStyle={styles.column}
        showsVerticalScrollIndicator={false}
        ListHeaderComponent={
          <>
            <ScreenHeader title="TV ao vivo" subtitle={`${filtered.length} canais na sua grade`} />
            <View style={[styles.searchWrap, { backgroundColor: colors.surface, borderColor: colors.border }]}>
              <MaterialIcons name="search" size={20} color={colors.muted} />
              <TextInput value={search} onChangeText={setSearch} placeholder="Buscar canais" placeholderTextColor={colors.muted} style={[styles.searchInput, { color: colors.foreground }]} returnKeyType="search" />
              {search ? <Pressable onPress={() => setSearch("")} hitSlop={8}><MaterialIcons name="close" size={18} color={colors.muted} /></Pressable> : null}
            </View>
            <FlatList
              data={[{ category_id: "all", category_name: "Todos" }, ...catalog.liveCategories]}
              horizontal
              showsHorizontalScrollIndicator={false}
              keyExtractor={(item) => `live-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, index }) => (
          <ChannelCard
            item={item}
            index={index}
            width={cardWidth}
            isFavorite={isFavorite(`live:${item.stream_id}`)}
            onFavorite={() => toggleFavorite(`live:${item.stream_id}`)}
            onPress={() => router.push({ pathname: "/player" as never, params: { title: item.name, kind: "live", id: String(item.stream_id), extension: "m3u8" } })}
          />
        )}
        ListEmptyComponent={<EmptyState icon="live-tv" title="Nenhum canal encontrado" message={catalog.liveStreams.length === 0 ? "A fonte conectada ainda não retornou canais ao vivo." : "Tente outra busca ou categoria."} />}
      />
    </ScreenContainer>
  );
}

function ChannelCard({ item, index, width, isFavorite, onFavorite, onPress }: { item: LiveStream; index: number; width: number; isFavorite: boolean; onFavorite: () => void; onPress: () => void }) {
  const colors = useColors("dark");
  return (
    <Pressable onPress={onPress} style={({ pressed }) => [styles.card, { width, backgroundColor: colors.surface, borderColor: colors.border }, pressed && { opacity: 0.74, transform: [{ scale: 0.985 }] }]}>
      <View style={[styles.logoArea, { backgroundColor: colors.background }]}>
        {item.stream_icon ? <Image source={{ uri: item.stream_icon }} contentFit="contain" transition={150} style={styles.logo} /> : <MaterialIcons name="live-tv" size={35} color={colors.muted} />}
        <View style={styles.liveBadge}><View style={styles.liveDot} /><Text style={styles.liveText}>AO VIVO</Text></View>
        <Pressable onPress={(event) => { event.stopPropagation(); onFavorite(); }} hitSlop={8} style={({ pressed }) => [styles.favoriteButton, pressed && { opacity: 0.55 }]}>
          <MaterialIcons name={isFavorite ? "favorite" : "favorite-border"} size={18} color={isFavorite ? "#FF6B7A" : "#F4F7FB"} />
        </Pressable>
      </View>
      <View style={styles.cardBottom}>
        <View style={styles.channelIndex}><Text style={styles.channelIndexText}>{String(index + 1).padStart(2, "0")}</Text></View>
        <Text numberOfLines={2} style={[styles.channelName, { color: colors.foreground }]}>{item.name}</Text>
        <MaterialIcons name="play-arrow" size={18} color={colors.primary} />
      </View>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  content: { paddingHorizontal: 18, paddingTop: 18, paddingBottom: 30, flexGrow: 1 },
  column: { justifyContent: "space-between", gap: 10 },
  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" },
  card: { borderWidth: 1, borderRadius: 17, overflow: "hidden", marginBottom: 10 },
  logoArea: { height: 112, alignItems: "center", justifyContent: "center", position: "relative" },
  logo: { width: "62%", height: "62%" },
  liveBadge: { position: "absolute", left: 9, bottom: 8, flexDirection: "row", alignItems: "center", gap: 5, backgroundColor: "rgba(9,17,31,0.8)", borderRadius: 7, paddingHorizontal: 7, paddingVertical: 4 },
  liveDot: { width: 6, height: 6, borderRadius: 3, backgroundColor: "#FF6B7A" },
  liveText: { fontSize: 8, fontWeight: "800", color: "#FFB0B8", letterSpacing: 0.6 },
  favoriteButton: { position: "absolute", top: 8, right: 8, width: 30, height: 30, borderRadius: 15, backgroundColor: "rgba(9,17,31,0.78)", alignItems: "center", justifyContent: "center" },
  cardBottom: { minHeight: 58, paddingHorizontal: 9, paddingVertical: 9, flexDirection: "row", alignItems: "center", gap: 7 },
  channelIndex: { width: 26, height: 26, borderRadius: 8, backgroundColor: "#1B2B50", alignItems: "center", justifyContent: "center" },
  channelIndexText: { fontSize: 10, fontWeight: "800", color: "#AFC0FF" },
  channelName: { flex: 1, fontSize: 12, lineHeight: 16, fontWeight: "800" },
});
