import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { useVideoPlayer, VideoView } from "expo-video";
import { useLocalSearchParams, useRouter } from "expo-router";
import { ActivityIndicator, Pressable, StyleSheet, Text, View } from "react-native";
import { useEffect, useState } from "react";
import { useKeepAwake } from "expo-keep-awake";

import { ScreenContainer } from "@/components/screen-container";
import { EmptyState } from "@/components/iptv-ui";
import { useColors } from "@/hooks/use-colors";
import { streamUrl } from "@/lib/iptv/api";
import { useIptv } from "@/lib/iptv/store";
import type { ContentKind } from "@/lib/iptv/types";

export default function PlayerScreen() {
  const router = useRouter();
  const colors = useColors("dark");
  const { credentials } = useIptv();
  const params = useLocalSearchParams<{ title?: string; kind?: string; id?: string; extension?: string }>();
  const kind = (params.kind === "movie" || params.kind === "series" ? params.kind : "live") as ContentKind;
  const id = Number(params.id);
  const source = credentials && Number.isFinite(id)
    ? streamUrl(credentials, kind, id, params.extension || undefined)
    : null;
  const player = useVideoPlayer(source, (instance) => {
    instance.play();
  });
  const [status, setStatus] = useState(player.status);
  const [playerError, setPlayerError] = useState<unknown>(null);
  useEffect(() => {
    const subscription = player.addListener("statusChange", ({ status: nextStatus, error: nextError }) => {
      setStatus(nextStatus);
      setPlayerError(nextError);
    });
    return () => subscription.remove();
  }, [player]);
  useKeepAwake();

  if (!credentials || !source) {
    return (
      <ScreenContainer edges={["top", "bottom", "left", "right"]}>
        <EmptyState icon="lock-outline" title="Sessão não encontrada" message="Conecte uma conta Xtream antes de iniciar a reprodução." actionLabel="Voltar" onAction={() => router.back()} />
      </ScreenContainer>
    );
  }

  const isLoading = status === "loading" || status === "idle";
  return (
    <ScreenContainer edges={["top", "bottom", "left", "right"]} containerClassName="bg-black">
      <View style={styles.container}>
        <View style={styles.topBar}>
          <Pressable onPress={() => router.back()} hitSlop={12} style={({ pressed }) => [styles.iconButton, pressed && { opacity: 0.6 }]}>
            <MaterialIcons name="arrow-back" size={24} color="#F4F7FB" />
          </Pressable>
          <Text numberOfLines={1} style={styles.playerTitle}>{params.title || "Reproduzindo"}</Text>
          <View style={styles.topBarSpacer} />
        </View>
        <View style={styles.videoShell}>
          <VideoView style={styles.video} player={player} allowsFullscreen allowsPictureInPicture contentFit="contain" />
          {isLoading ? (
            <View style={styles.loadingOverlay}>
              <ActivityIndicator color={colors.primary} size="large" />
              <Text style={styles.loadingText}>Conectando ao stream…</Text>
            </View>
          ) : null}
          {status === "error" || playerError ? (
            <View style={styles.errorOverlay}>
              <MaterialIcons name="error-outline" size={30} color="#FF6B7A" />
              <Text style={styles.errorTitle}>Não foi possível reproduzir</Text>
              <Text style={styles.errorMessage}>Verifique o stream ou tente novamente mais tarde.</Text>
            </View>
          ) : null}
        </View>
        <View style={styles.infoPanel}>
          <Text style={styles.infoEyebrow}>{kind === "live" ? "TV AO VIVO" : kind === "movie" ? "FILME" : "SÉRIE"}</Text>
          <Text numberOfLines={2} style={styles.infoTitle}>{params.title || "Conteúdo"}</Text>
          <Text style={styles.infoMessage}>A reprodução usa a fonte configurada na sua conta Xtream.</Text>
        </View>
      </View>
    </ScreenContainer>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#000" },
  topBar: { height: 58, flexDirection: "row", alignItems: "center", paddingHorizontal: 16, gap: 12 },
  iconButton: { width: 38, height: 38, alignItems: "center", justifyContent: "center", borderRadius: 19, backgroundColor: "#182238" },
  playerTitle: { color: "#F4F7FB", fontSize: 15, fontWeight: "700", flex: 1 },
  topBarSpacer: { width: 38 },
  videoShell: { width: "100%", aspectRatio: 16 / 9, backgroundColor: "#030507", position: "relative" },
  video: { flex: 1 },
  loadingOverlay: { ...StyleSheet.absoluteFillObject, alignItems: "center", justifyContent: "center", backgroundColor: "rgba(3,5,7,0.62)" },
  loadingText: { color: "#93A4BD", fontSize: 13, marginTop: 10 },
  errorOverlay: { ...StyleSheet.absoluteFillObject, alignItems: "center", justifyContent: "center", padding: 24, backgroundColor: "rgba(3,5,7,0.78)" },
  errorTitle: { color: "#F4F7FB", fontSize: 16, fontWeight: "800", marginTop: 8 },
  errorMessage: { color: "#93A4BD", fontSize: 12, textAlign: "center", marginTop: 6 },
  infoPanel: { padding: 20 },
  infoEyebrow: { color: "#5C7CFA", fontSize: 11, fontWeight: "800", letterSpacing: 1.5 },
  infoTitle: { color: "#F4F7FB", fontSize: 23, fontWeight: "800", marginTop: 6 },
  infoMessage: { color: "#93A4BD", fontSize: 13, lineHeight: 19, marginTop: 10 },
});
