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

import { EmptyState } from "@/components/iptv-ui";
import { ScreenContainer } from "@/components/screen-container";
import { useColors } from "@/hooks/use-colors";
import { loadSeriesInfo } from "@/lib/iptv/api";
import { useIptv } from "@/lib/iptv/store";
import type { SeriesEpisode, SeriesInfo, SeriesSeason } from "@/lib/iptv/types";

type EpisodeRow = SeriesEpisode & { season: string };
type SeasonOption = { key: string; label: string; count?: number; cover?: string };

function firstImage(value?: string[] | string): string | undefined {
  return Array.isArray(value) ? value[0] : value;
}

function displayValue(value?: string | number | null): string | undefined {
  if (value === undefined || value === null || String(value).trim() === "") return undefined;
  return String(value);
}

function seasonKey(season?: SeriesSeason): string | undefined {
  if (season?.season_number === undefined || season.season_number === null) return undefined;
  return String(season.season_number);
}

export default function SeriesDetailScreen() {
  const colors = useColors("dark");
  const router = useRouter();
  const { credentials } = useIptv();
  const params = useLocalSearchParams<{ id?: string; title?: string; cover?: string; plot?: string; year?: string; rating?: string }>();
  const [episodes, setEpisodes] = useState<EpisodeRow[]>([]);
  const [seriesInfo, setSeriesInfo] = useState<SeriesInfo | null>(null);
  const [seasonOptions, setSeasonOptions] = useState<SeasonOption[]>([]);
  const [season, setSeason] = useState("all");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let active = true;
    if (!credentials || !params.id) {
      setLoading(false);
      return;
    }
    setLoading(true);
    loadSeriesInfo(credentials, Number(params.id))
      .then((result) => {
        if (!active) return;
        const rows = Object.entries(result.episodes || {})
          .flatMap(([seasonNumber, items]) => items.map((episode) => ({ ...episode, season: seasonNumber })))
          .sort((a, b) => String(a.season).localeCompare(String(b.season), undefined, { numeric: true }) || (a.episode_num || 0) - (b.episode_num || 0));
        const apiOptions = (result.seasons || []).flatMap((item) => {
          const key = seasonKey(item);
          return key ? [{ key, label: item.name || `Temporada ${key}`, count: item.episode_count, cover: item.cover }] : [];
        });
        const fallbackOptions = Array.from(new Set(rows.map((episode) => episode.season))).sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).map((key) => ({ key, label: `Temporada ${key}`, count: rows.filter((episode) => episode.season === key).length }));
        setEpisodes(rows);
        setSeriesInfo(result.info || null);
        setSeasonOptions(apiOptions.length ? apiOptions : fallbackOptions);
        setSeason("all");
        setError(null);
      })
      .catch((reason) => {
        if (active) setError(reason instanceof Error ? reason.message : "Não foi possível carregar os episódios.");
      })
      .finally(() => {
        if (active) setLoading(false);
      });
    return () => {
      active = false;
    };
  }, [credentials, params.id]);

  const filteredEpisodes = season === "all" ? episodes : episodes.filter((episode) => episode.season === season);
  const title = seriesInfo?.name || params.title || "Série";
  const image = seriesInfo?.cover_big || seriesInfo?.cover || firstImage(seriesInfo?.backdrop_path) || params.cover;
  const plot = seriesInfo?.plot || params.plot;
  const year = displayValue(seriesInfo?.year || seriesInfo?.release_date || seriesInfo?.releasedate || params.year);
  const rating = displayValue(seriesInfo?.rating_5based || seriesInfo?.rating || params.rating);
  const meta = [year, rating ? `Nota ${rating}` : undefined, `${episodes.length} episódios`].filter(Boolean).join("  ·  ");

  if (!credentials) return <ScreenContainer><EmptyState icon="lock-outline" title="Sessão não encontrada" message="Conecte uma conta Xtream para acessar esta série." actionLabel="Voltar" onAction={() => router.back()} /></ScreenContainer>;

  return (
    <ScreenContainer>
      <FlatList
        data={filteredEpisodes}
        keyExtractor={(item, index) => `episode-${item.id}-${index}`}
        contentContainerStyle={styles.content}
        showsVerticalScrollIndicator={false}
        ListHeaderComponent={
          <>
            <View style={styles.topBar}><Pressable onPress={() => router.back()} hitSlop={10} style={({ pressed }) => [styles.backButton, pressed && { opacity: 0.6 }]}><MaterialIcons name="arrow-back" size={22} color={colors.foreground} /></Pressable><Text numberOfLines={1} style={[styles.topTitle, { color: colors.foreground }]}>{title}</Text></View>
            <View style={[styles.hero, { backgroundColor: colors.surface, borderColor: colors.border }]}>
              <View style={[styles.heroPoster, { backgroundColor: colors.background }]}>{image ? <Image source={{ uri: image }} contentFit="cover" transition={180} style={StyleSheet.absoluteFillObject} /> : <MaterialIcons name="video-library" size={34} color={colors.muted} />}</View>
              <View style={styles.heroText}><Text style={[styles.heroTitle, { color: colors.foreground }]}>{title}</Text><Text style={[styles.heroMeta, { color: colors.muted }]}>{meta}</Text></View>
            </View>
            <Text style={[styles.sectionTitle, { color: colors.foreground }]}>Sinopse</Text>
            <View style={[styles.plotBox, { backgroundColor: colors.surface, borderColor: colors.border }]}><Text style={[styles.plot, { color: plot ? colors.foreground : colors.muted }]}>{plot || "A API não forneceu uma sinopse para esta série."}</Text></View>
            {(seriesInfo?.genre || seriesInfo?.cast || seriesInfo?.director) ? <View style={[styles.metaBox, { backgroundColor: colors.surface, borderColor: colors.border }]}>{seriesInfo.genre ? <MetaLine label="Gênero" value={seriesInfo.genre} /> : null}{seriesInfo.director ? <MetaLine label="Direção" value={seriesInfo.director} /> : null}{seriesInfo.cast ? <MetaLine label="Elenco" value={seriesInfo.cast} /> : null}</View> : null}
            <Text style={[styles.sectionTitle, { color: colors.foreground }]}>Temporadas</Text>
            <FlatList
              data={[{ key: "all", label: "Todas", count: episodes.length }, ...seasonOptions]}
              horizontal
              showsHorizontalScrollIndicator={false}
              keyExtractor={(item) => `season-${item.key}`}
              contentContainerStyle={styles.seasonList}
              renderItem={({ item }) => <Pressable onPress={() => setSeason(item.key)} style={({ pressed }) => [styles.seasonPill, { backgroundColor: season === item.key ? colors.primary : colors.surface, borderColor: season === item.key ? colors.primary : colors.border }, pressed && { opacity: 0.7 }]}><Text style={[styles.seasonText, { color: season === item.key ? "#F4F7FB" : colors.muted }]}>{item.label}{item.count !== undefined ? `  ·  ${item.count}` : ""}</Text></Pressable>}
            />
            {loading ? <View style={styles.loading}><ActivityIndicator color={colors.primary} /><Text style={[styles.loadingText, { color: colors.muted }]}>Carregando temporadas e episódios…</Text></View> : null}
            {error ? <View style={styles.errorBox}><MaterialIcons name="error-outline" size={18} color="#FF6B7A" /><Text style={styles.errorText}>{error}</Text></View> : null}
            {!loading && !error && seasonOptions.length === 0 ? <Text style={[styles.noSeasonText, { color: colors.muted }]}>A API não retornou temporadas para esta série.</Text> : null}
          </>
        }
        renderItem={({ item }) => <EpisodeRowView item={item} onPress={() => router.push({ pathname: "/player" as never, params: { title: `${title} · ${item.title || `Episódio ${item.episode_num || ""}`}`, kind: "series", id: String(item.id), extension: item.container_extension || "mp4" } })} />}
        ListEmptyComponent={!loading ? <EmptyState icon="video-library" title="Nenhum episódio disponível" message="A API não retornou episódios para esta série." /> : null}
      />
    </ScreenContainer>
  );
}

function MetaLine({ label, value }: { label: string; value: string }) {
  const colors = useColors("dark");
  return <View style={styles.metaLine}><Text style={[styles.metaLabel, { color: colors.muted }]}>{label}</Text><Text style={[styles.metaValue, { color: colors.foreground }]}>{value}</Text></View>;
}

function EpisodeRowView({ item, onPress }: { item: EpisodeRow; onPress: () => void }) {
  const colors = useColors("dark");
  return <Pressable onPress={onPress} style={({ pressed }) => [styles.episodeRow, { backgroundColor: colors.surface, borderColor: colors.border }, pressed && { opacity: 0.72 }]}><View style={[styles.episodeThumb, { backgroundColor: colors.background }]}>{item.info?.movie_image ? <Image source={{ uri: item.info.movie_image }} contentFit="cover" style={StyleSheet.absoluteFillObject} /> : <MaterialIcons name="play-circle-outline" size={26} color={colors.muted} />}</View><View style={styles.episodeText}><Text style={[styles.episodeNumber, { color: colors.primary }]}>TEMP. {item.season}  ·  EP. {item.episode_num || "—"}</Text><Text numberOfLines={2} style={[styles.episodeTitle, { color: colors.foreground }]}>{item.title || "Episódio sem título"}</Text>{item.info?.duration ? <Text style={[styles.episodeDuration, { color: colors.muted }]}>{item.info.duration}</Text> : null}</View><MaterialIcons name="play-circle-filled" size={27} color={colors.primary} /></Pressable>;
}

const styles = StyleSheet.create({
  content: { paddingHorizontal: 18, paddingTop: 14, paddingBottom: 30, flexGrow: 1 },
  topBar: { flexDirection: "row", alignItems: "center", gap: 10, marginBottom: 17 },
  backButton: { width: 38, height: 38, borderRadius: 19, backgroundColor: "#111D30", alignItems: "center", justifyContent: "center" },
  topTitle: { fontSize: 20, fontWeight: "800", flex: 1 },
  hero: { minHeight: 116, borderWidth: 1, borderRadius: 20, padding: 13, flexDirection: "row", alignItems: "center", gap: 13 },
  heroPoster: { width: 70, height: 92, borderRadius: 12, overflow: "hidden", alignItems: "center", justifyContent: "center" },
  heroText: { flex: 1 },
  heroTitle: { fontSize: 20, lineHeight: 25, fontWeight: "800" },
  heroMeta: { fontSize: 12, marginTop: 7 },
  sectionTitle: { fontSize: 17, fontWeight: "800", marginTop: 22, marginBottom: 9 },
  plotBox: { borderWidth: 1, borderRadius: 16, padding: 15 },
  plot: { fontSize: 14, lineHeight: 21 },
  metaBox: { borderWidth: 1, borderRadius: 16, paddingHorizontal: 15, marginTop: 13 },
  metaLine: { minHeight: 42, borderBottomWidth: 1, borderBottomColor: "#22314A", justifyContent: "center", gap: 3 },
  metaLabel: { fontSize: 9, fontWeight: "800", textTransform: "uppercase", letterSpacing: 0.6 },
  metaValue: { fontSize: 13, lineHeight: 18 },
  seasonList: { gap: 8, paddingVertical: 12 },
  seasonPill: { borderWidth: 1, borderRadius: 999, paddingHorizontal: 14, paddingVertical: 8 },
  seasonText: { fontSize: 12, fontWeight: "700" },
  loading: { alignItems: "center", paddingVertical: 22 },
  loadingText: { fontSize: 12, marginTop: 7 },
  errorBox: { flexDirection: "row", alignItems: "flex-start", gap: 8, padding: 11, borderRadius: 12, backgroundColor: "rgba(255,107,122,0.12)", marginBottom: 12 },
  errorText: { color: "#FF9BA6", fontSize: 12, lineHeight: 17, flex: 1 },
  noSeasonText: { fontSize: 12, marginBottom: 8 },
  episodeRow: { minHeight: 76, borderWidth: 1, borderRadius: 15, padding: 9, flexDirection: "row", alignItems: "center", gap: 10, marginBottom: 9 },
  episodeThumb: { width: 70, height: 56, borderRadius: 10, alignItems: "center", justifyContent: "center", overflow: "hidden" },
  episodeText: { flex: 1 },
  episodeNumber: { fontSize: 9, fontWeight: "800", letterSpacing: 0.8 },
  episodeTitle: { fontSize: 13, lineHeight: 18, fontWeight: "700", marginTop: 4 },
  episodeDuration: { fontSize: 10, marginTop: 3 },
});
