import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { useRouter } from "expo-router";
import { useMemo, useState } from "react";
import {
  ActivityIndicator,
  FlatList,
  KeyboardAvoidingView,
  Platform,
  Pressable,
  ScrollView,
  StyleSheet,
  Switch,
  Text,
  TextInput,
  View,
} from "react-native";

import { ScreenContainer } from "@/components/screen-container";
import { AccountBadge, BrandMark, EmptyState, MediaCard, SectionHeader } from "@/components/iptv-ui";
import { useColors } from "@/hooks/use-colors";
import { useIptv } from "@/lib/iptv/store";
import type { XtreamCredentials } from "@/lib/iptv/types";

export default function HomeScreen() {
  const { isBootstrapping, credentials } = useIptv();
  if (isBootstrapping) return <LoadingScreen />;
  if (!credentials) return <LoginScreen />;
  return <DashboardScreen />;
}

function LoadingScreen() {
  return (
    <ScreenContainer edges={["top", "bottom", "left", "right"]}>
      <View style={styles.loadingScreen}>
        <BrandMark />
        <ActivityIndicator color="#5C7CFA" size="large" style={{ marginTop: 28 }} />
        <Text style={styles.loadingLabel}>Preparando sua biblioteca</Text>
      </View>
    </ScreenContainer>
  );
}

function LoginScreen() {
  const colors = useColors("dark");
  const { connect, isLoading, error, rememberLogin, setRememberLogin, clearError } = useIptv();
  const [serverUrl, setServerUrl] = useState("");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);

  const handleConnect = async () => {
    clearError();
    const input: XtreamCredentials = { serverUrl, username, password };
    try {
      await connect(input);
    } catch {
      // A mensagem amigável é apresentada pelo provider.
    }
  };

  return (
    <ScreenContainer edges={["top", "bottom", "left", "right"]}>
      <KeyboardAvoidingView style={styles.flex} behavior={Platform.OS === "ios" ? "padding" : undefined}>
        <ScrollView contentContainerStyle={styles.loginContent} keyboardShouldPersistTaps="handled">
          <View style={styles.loginBrand}><BrandMark /></View>
          <Text style={styles.loginKicker}>SUA CENTRAL DE ENTRETENIMENTO</Text>
          <Text style={styles.loginTitle}>Conecte sua conta</Text>
          <Text style={styles.loginDescription}>Use os dados Xtream Codes do seu provedor para acessar sua biblioteca.</Text>

          <View style={[styles.formCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
            <Field label="URL do servidor" value={serverUrl} onChangeText={setServerUrl} placeholder="https://seu-servidor.com:8080" autoCapitalize="none" keyboardType="url" />
            <Field label="Usuário" value={username} onChangeText={setUsername} placeholder="Digite seu usuário" autoCapitalize="none" />
            <View>
              <Text style={styles.fieldLabel}>Senha</Text>
              <View style={[styles.inputWrap, { borderColor: colors.border, backgroundColor: colors.background }]}>
                <MaterialIcons name="lock-outline" size={18} color={colors.muted} />
                <TextInput
                  value={password}
                  onChangeText={setPassword}
                  placeholder="Digite sua senha"
                  placeholderTextColor={colors.muted}
                  secureTextEntry={!showPassword}
                  autoCapitalize="none"
                  style={[styles.input, { color: colors.foreground }]}
                />
                <Pressable onPress={() => setShowPassword((current) => !current)} hitSlop={8} style={({ pressed }) => [pressed && { opacity: 0.6 }]}>
                  <MaterialIcons name={showPassword ? "visibility-off" : "visibility"} size={19} color={colors.muted} />
                </Pressable>
              </View>
            </View>

            <View style={styles.rememberRow}>
              <View style={styles.rememberTextWrap}>
                <Text style={[styles.rememberTitle, { color: colors.foreground }]}>Lembrar desta conta</Text>
                <Text style={[styles.rememberDescription, { color: colors.muted }]}>As credenciais ficam protegidas no dispositivo.</Text>
              </View>
              <Switch value={rememberLogin} onValueChange={setRememberLogin} trackColor={{ false: colors.border, true: colors.primary }} thumbColor="#F4F7FB" />
            </View>

            {error ? (
              <View style={styles.errorBox}>
                <MaterialIcons name="error-outline" size={18} color="#FF6B7A" />
                <Text style={styles.errorText}>{error}</Text>
              </View>
            ) : null}

            <Pressable onPress={handleConnect} disabled={isLoading} style={({ pressed }) => [styles.connectButton, pressed && styles.buttonPressed, isLoading && styles.buttonDisabled]}>
              {isLoading ? <ActivityIndicator color="#F4F7FB" /> : <><Text style={styles.connectButtonText}>Conectar à conta</Text><MaterialIcons name="arrow-forward" size={19} color="#F4F7FB" /></>}
            </Pressable>
          </View>
          <Text style={styles.loginFooter}>O Manus IPTV Player não fornece listas ou canais. Use somente fontes autorizadas por você.</Text>
        </ScrollView>
      </KeyboardAvoidingView>
    </ScreenContainer>
  );
}

function Field({ label, value, onChangeText, placeholder, ...props }: { label: string; value: string; onChangeText: (value: string) => void; placeholder: string } & Omit<React.ComponentProps<typeof TextInput>, "value" | "onChangeText" | "placeholder">) {
  const colors = useColors("dark");
  return (
    <View>
      <Text style={styles.fieldLabel}>{label}</Text>
      <View style={[styles.inputWrap, { borderColor: colors.border, backgroundColor: colors.background }]}>
        <MaterialIcons name={label === "URL do servidor" ? "language" : "person-outline"} size={18} color={colors.muted} />
        <TextInput value={value} onChangeText={onChangeText} placeholder={placeholder} placeholderTextColor={colors.muted} style={[styles.input, { color: colors.foreground }]} {...props} />
      </View>
    </View>
  );
}

function DashboardScreen() {
  const router = useRouter();
  const colors = useColors("dark");
  const { account, catalog, isLoading, reloadCatalog, favorites, isFavorite, toggleFavorite } = useIptv();
  const displayName = account?.userInfo?.username || "Sua conta";
  const featuredMovies = useMemo(() => catalog.movies.slice(0, 8), [catalog.movies]);
  const featuredSeries = useMemo(() => catalog.series.slice(0, 8), [catalog.series]);
  const go = (route: string) => router.push(route as never);

  return (
    <ScreenContainer>
      <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.dashboardContent}>
        <View style={styles.dashboardHeader}>
          <BrandMark compact />
          <AccountBadge label={displayName} />
        </View>
        <View style={styles.heroCard}>
          <View style={styles.heroTextWrap}>
            <Text style={styles.heroEyebrow}>BEM-VINDO DE VOLTA</Text>
            <Text style={styles.heroTitle}>Tudo o que você quer assistir, em um só lugar.</Text>
            <Text style={styles.heroMessage}>{catalog.liveStreams.length + catalog.movies.length + catalog.series.length} itens disponíveis na sua conta.</Text>
          </View>
          <View style={styles.heroOrb}><MaterialIcons name="play-arrow" size={42} color="#F4F7FB" /></View>
        </View>

        <SectionHeader title="Acessar biblioteca" />
        <View style={styles.quickGrid}>
          <QuickTile icon="live-tv" label="TV ao vivo" count={catalog.liveStreams.length} color="#5C7CFA" onPress={() => go("/(tabs)/live")} />
          <QuickTile icon="movie" label="Filmes" count={catalog.movies.length} color="#9B6DFF" onPress={() => go("/(tabs)/movies")} />
          <QuickTile icon="video-library" label="Séries" count={catalog.series.length} color="#36B9A5" onPress={() => go("/(tabs)/series")} />
          <QuickTile icon="favorite" label="Favoritos" count={favorites.length} color="#FF6B7A" onPress={() => go("/(tabs)/more")} />
        </View>

        {isLoading ? <View style={styles.refreshing}><ActivityIndicator color={colors.primary} /><Text style={[styles.refreshingText, { color: colors.muted }]}>Atualizando catálogo…</Text></View> : null}
        {featuredMovies.length > 0 ? (
          <>
            <SectionHeader title="Filmes em destaque" actionLabel="Ver todos" onAction={() => go("/(tabs)/movies")} />
            <FlatList data={featuredMovies} horizontal showsHorizontalScrollIndicator={false} keyExtractor={(item) => `movie-${item.stream_id}`} renderItem={({ item }) => <MediaCard item={item} kind="movie" onPress={() => router.push({ pathname: "/player" as never, params: { title: item.name, kind: "movie", id: String(item.stream_id), extension: item.container_extension || "mp4" } })} isFavorite={isFavorite(`movie:${item.stream_id}`)} onToggleFavorite={() => toggleFavorite(`movie:${item.stream_id}`)} />} />
          </>
        ) : null}
        {featuredSeries.length > 0 ? (
          <>
            <SectionHeader title="Séries para descobrir" actionLabel="Ver todas" onAction={() => go("/(tabs)/series")} />
            <FlatList data={featuredSeries} horizontal showsHorizontalScrollIndicator={false} keyExtractor={(item) => `series-${item.series_id}`} renderItem={({ item }) => <MediaCard item={item} kind="series" onPress={() => go("/(tabs)/series")} isFavorite={isFavorite(`series:${item.series_id}`)} onToggleFavorite={() => toggleFavorite(`series:${item.series_id}`)} />} />
          </>
        ) : null}
        {catalog.liveStreams.length === 0 && catalog.movies.length === 0 && catalog.series.length === 0 ? <EmptyState icon="cloud-off" title="Catálogo vazio" message="A conta conectou, mas não retornou conteúdos. Atualize ou revise a fonte Xtream." actionLabel="Atualizar catálogo" onAction={reloadCatalog} /> : null}
      </ScrollView>
    </ScreenContainer>
  );
}

function QuickTile({ icon, label, count, color, onPress }: { icon: React.ComponentProps<typeof MaterialIcons>["name"]; label: string; count: number; color: string; onPress: () => void }) {
  return (
    <Pressable onPress={onPress} style={({ pressed }) => [styles.quickTile, { borderColor: `${color}55` }, pressed && styles.buttonPressed]}>
      <View style={[styles.quickIcon, { backgroundColor: `${color}22` }]}><MaterialIcons name={icon} size={22} color={color} /></View>
      <Text style={styles.quickLabel}>{label}</Text>
      <Text style={styles.quickCount}>{count} itens</Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  flex: { flex: 1 },
  loadingScreen: { flex: 1, alignItems: "center", justifyContent: "center" },
  loadingLabel: { color: "#93A4BD", fontSize: 13, marginTop: 12 },
  loginContent: { flexGrow: 1, paddingHorizontal: 20, paddingTop: 40, paddingBottom: 28 },
  loginBrand: { alignItems: "center", marginBottom: 36 },
  loginKicker: { color: "#5C7CFA", fontSize: 10, fontWeight: "800", letterSpacing: 1.6, textAlign: "center" },
  loginTitle: { color: "#F4F7FB", fontSize: 30, lineHeight: 36, fontWeight: "800", textAlign: "center", marginTop: 10 },
  loginDescription: { color: "#93A4BD", fontSize: 14, lineHeight: 20, textAlign: "center", marginTop: 10, paddingHorizontal: 20 },
  formCard: { borderWidth: 1, borderRadius: 24, padding: 18, marginTop: 28, gap: 16 },
  fieldLabel: { color: "#F4F7FB", fontSize: 12, fontWeight: "700", marginBottom: 7 },
  inputWrap: { minHeight: 50, borderWidth: 1, borderRadius: 14, flexDirection: "row", alignItems: "center", paddingHorizontal: 14, gap: 10 },
  input: { flex: 1, minHeight: 48, fontSize: 14 },
  rememberRow: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", gap: 10, marginTop: 2 },
  rememberTextWrap: { flex: 1 },
  rememberTitle: { fontSize: 13, fontWeight: "700" },
  rememberDescription: { fontSize: 11, marginTop: 3 },
  errorBox: { flexDirection: "row", alignItems: "flex-start", gap: 8, padding: 11, borderRadius: 12, backgroundColor: "rgba(255,107,122,0.12)" },
  errorText: { color: "#FF9BA6", fontSize: 12, lineHeight: 17, flex: 1 },
  connectButton: { minHeight: 52, borderRadius: 15, backgroundColor: "#5C7CFA", flexDirection: "row", alignItems: "center", justifyContent: "center", gap: 8, marginTop: 2 },
  connectButtonText: { color: "#F4F7FB", fontSize: 15, fontWeight: "800" },
  buttonPressed: { opacity: 0.75, transform: [{ scale: 0.985 }] },
  buttonDisabled: { opacity: 0.6 },
  loginFooter: { color: "#647691", fontSize: 11, lineHeight: 16, textAlign: "center", marginTop: 20, paddingHorizontal: 14 },
  dashboardContent: { paddingHorizontal: 18, paddingTop: 12, paddingBottom: 36 },
  dashboardHeader: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", marginBottom: 20 },
  heroCard: { borderRadius: 24, backgroundColor: "#172641", padding: 20, minHeight: 154, flexDirection: "row", overflow: "hidden", position: "relative" },
  heroTextWrap: { flex: 1, paddingRight: 12 },
  heroEyebrow: { color: "#8EA7FF", fontSize: 10, fontWeight: "800", letterSpacing: 1.4 },
  heroTitle: { color: "#F4F7FB", fontSize: 21, lineHeight: 26, fontWeight: "800", marginTop: 8 },
  heroMessage: { color: "#AAB9D0", fontSize: 12, marginTop: 10 },
  heroOrb: { width: 74, height: 74, borderRadius: 37, backgroundColor: "#5C7CFA", alignItems: "center", justifyContent: "center", alignSelf: "center", opacity: 0.95 },
  quickGrid: { flexDirection: "row", flexWrap: "wrap", gap: 10 },
  quickTile: { width: "48%", minHeight: 112, borderWidth: 1, borderRadius: 18, padding: 13, backgroundColor: "#111D30" },
  quickIcon: { width: 36, height: 36, borderRadius: 12, alignItems: "center", justifyContent: "center" },
  quickLabel: { color: "#F4F7FB", fontSize: 13, fontWeight: "800", marginTop: 10 },
  quickCount: { color: "#93A4BD", fontSize: 11, marginTop: 3 },
  refreshing: { flexDirection: "row", alignItems: "center", gap: 8, marginTop: 18 },
  refreshingText: { fontSize: 12 },
});
