import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { useRouter } from "expo-router";
import { ActivityIndicator, Pressable, ScrollView, StyleSheet, Text, View } from "react-native";

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

export default function MoreScreen() {
  const router = useRouter();
  const colors = useColors("dark");
  const { account, credentials, catalog, favorites, isLoading, reloadCatalog, logout } = useIptv();
  const total = catalog.liveStreams.length + catalog.movies.length + catalog.series.length;

  if (!credentials) return <ScreenContainer><EmptyState icon="lock-outline" title="Nenhuma conta conectada" message="Volte ao início para conectar uma conta Xtream." actionLabel="Ir para login" onAction={() => router.push("/(tabs)" as never)} /></ScreenContainer>;

  return (
    <ScreenContainer>
      <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.content}>
        <ScreenHeader title="Mais" subtitle="Ajustes e informações da sua conta" />
        <View style={[styles.accountCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
          <View style={styles.accountAvatar}><MaterialIcons name="person" size={26} color="#F4F7FB" /></View>
          <View style={styles.accountText}><AccountBadge label={account?.userInfo?.username || "Conta Xtream"} /><Text style={[styles.accountServer, { color: colors.muted }]} numberOfLines={1}>{credentials.serverUrl}</Text></View>
          <View style={styles.statusPill}><View style={styles.statusDot} /><Text style={styles.statusText}>Ativa</Text></View>
        </View>
        <Text style={[styles.sectionLabel, { color: colors.foreground }]}>Resumo da conta</Text>
        <View style={styles.statsRow}><Stat label="Canais" value={catalog.liveStreams.length} color="#5C7CFA" /><Stat label="Filmes" value={catalog.movies.length} color="#9B6DFF" /><Stat label="Séries" value={catalog.series.length} color="#36B9A5" /></View>
        <View style={[styles.detailCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
          <DetailRow icon="event" label="Expira em" value={formatExpiry(account?.userInfo?.exp_date)} />
          <DetailRow icon="devices" label="Conexões" value={`${account?.userInfo?.active_cons ?? "—"} / ${account?.userInfo?.max_connections ?? "—"}`} />
          <DetailRow icon="cloud-done" label="Conteúdo sincronizado" value={`${total} itens`} />
        </View>
        <Text style={[styles.sectionLabel, { color: colors.foreground }]}>Ações</Text>
        <ActionRow icon="refresh" label="Atualizar catálogo" description="Buscar os conteúdos mais recentes" onPress={reloadCatalog} loading={isLoading} />
        <ActionRow icon="favorite-border" label="Favoritos" description={`${favorites.length} itens salvos neste dispositivo`} onPress={() => {}} />
        <ActionRow icon="logout" label="Sair da conta" description="Remover a sessão deste dispositivo" destructive onPress={async () => { await logout(); router.replace("/(tabs)" as never); }} />
        <Text style={styles.version}>Manus IPTV Player · player técnico para fontes autorizadas</Text>
      </ScrollView>
    </ScreenContainer>
  );
}

function Stat({ label, value, color }: { label: string; value: number; color: string }) { return <View style={styles.stat}><Text style={[styles.statValue, { color }]}>{value}</Text><Text style={styles.statLabel}>{label}</Text></View>; }
function DetailRow({ icon, label, value }: { icon: React.ComponentProps<typeof MaterialIcons>["name"]; label: string; value: string }) { const colors = useColors("dark"); return <View style={styles.detailRow}><MaterialIcons name={icon} size={19} color={colors.muted} /><Text style={[styles.detailLabel, { color: colors.muted }]}>{label}</Text><Text numberOfLines={1} style={[styles.detailValue, { color: colors.foreground }]}>{value}</Text></View>; }
function ActionRow({ icon, label, description, onPress, destructive, loading }: { icon: React.ComponentProps<typeof MaterialIcons>["name"]; label: string; description: string; onPress: () => void; destructive?: boolean; loading?: boolean }) { const colors = useColors("dark"); return <Pressable onPress={onPress} disabled={loading} style={({ pressed }) => [styles.actionRow, { borderColor: colors.border, backgroundColor: colors.surface }, pressed && { opacity: 0.7 }]}><View style={[styles.actionIcon, { backgroundColor: destructive ? "rgba(255,107,122,0.12)" : "rgba(92,124,250,0.12)" }]}>{loading ? <ActivityIndicator size="small" color={colors.primary} /> : <MaterialIcons name={icon} size={20} color={destructive ? "#FF6B7A" : colors.primary} />}</View><View style={styles.actionText}><Text style={[styles.actionLabel, { color: destructive ? "#FF6B7A" : colors.foreground }]}>{label}</Text><Text style={[styles.actionDescription, { color: colors.muted }]}>{description}</Text></View><MaterialIcons name="chevron-right" size={20} color={colors.muted} /></Pressable>; }

const styles = StyleSheet.create({
  content: { paddingHorizontal: 18, paddingTop: 18, paddingBottom: 32 },
  accountCard: { borderWidth: 1, borderRadius: 20, padding: 15, flexDirection: "row", alignItems: "center", gap: 11 },
  accountAvatar: { width: 48, height: 48, borderRadius: 16, backgroundColor: "#5C7CFA", alignItems: "center", justifyContent: "center" },
  accountText: { flex: 1, gap: 7 },
  accountServer: { fontSize: 11 },
  statusPill: { flexDirection: "row", alignItems: "center", gap: 5, borderRadius: 999, paddingHorizontal: 8, paddingVertical: 6, backgroundColor: "rgba(54,211,153,0.12)" },
  statusDot: { width: 6, height: 6, borderRadius: 3, backgroundColor: "#36D399" },
  statusText: { color: "#62E6B4", fontSize: 10, fontWeight: "800" },
  sectionLabel: { fontSize: 16, fontWeight: "800", marginTop: 23, marginBottom: 11 },
  statsRow: { flexDirection: "row", gap: 10 },
  stat: { flex: 1, borderRadius: 16, padding: 14, backgroundColor: "#111D30" },
  statValue: { fontSize: 23, fontWeight: "800" },
  statLabel: { color: "#93A4BD", fontSize: 11, marginTop: 4 },
  detailCard: { borderWidth: 1, borderRadius: 17, paddingHorizontal: 14, marginTop: 11 },
  detailRow: { minHeight: 48, flexDirection: "row", alignItems: "center", gap: 9, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: "#22314A" },
  detailLabel: { fontSize: 12, flex: 1 },
  detailValue: { fontSize: 12, fontWeight: "700", maxWidth: "50%" },
  actionRow: { minHeight: 68, borderWidth: 1, borderRadius: 16, padding: 11, flexDirection: "row", alignItems: "center", gap: 11, marginBottom: 9 },
  actionIcon: { width: 40, height: 40, borderRadius: 13, alignItems: "center", justifyContent: "center" },
  actionText: { flex: 1 },
  actionLabel: { fontSize: 13, fontWeight: "800" },
  actionDescription: { fontSize: 11, marginTop: 4 },
  version: { color: "#647691", fontSize: 10, lineHeight: 15, textAlign: "center", marginTop: 18 },
});
