import React, { useState } from "react";
import { ActivityIndicator, Pressable, Text, TextInput, View } from "react-native";
import { Image } from "expo-image";
import { LinearGradient } from "expo-linear-gradient";
import { router } from "expo-router";
import { KeyboardAwareScrollView } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Ionicons from "@react-native-vector-icons/ionicons";

import { useAppConfig, useAuth } from "@/src/auth";
import { Focusable } from "@/src/components/Focusable";
import { Logo } from "@/src/components/Logo";
import { makeStyles, useTheme } from "@/src/theme";
import { fs, radius, space } from "@/src/ui";

const DEFAULT_BG = "https://mango.blender.org/wp-content/uploads/2013/05/01_thom_celia_bridge.jpg";

export default function Login() {
  const styles = useStyles();
  const { colors } = useTheme();
  const insets = useSafeAreaInsets();
  const { login } = useAuth();
  const cfg = useAppConfig();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [show, setShow] = useState(false);
  const [remember, setRemember] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const submit = async () => {
    if (!username.trim() || !password) return setError("Informe usuário e senha.");
    setLoading(true);
    setError(null);
    try {
      await login(username.trim().toLowerCase(), password, remember);
      router.replace("/(tabs)");
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <View style={styles.root} testID="login-screen">
      <Image source={{ uri: cfg.background_url || DEFAULT_BG }} style={styles.bg} contentFit="cover" />
      <LinearGradient colors={[colors.scrimMid, colors.surface]} style={styles.bg} />
      <KeyboardAwareScrollView
        bottomOffset={24}
        keyboardShouldPersistTaps="handled"
        contentContainerStyle={[styles.scroll, { paddingTop: insets.top + space.xxl, paddingBottom: insets.bottom + space.xl }]}
      >
        <View style={styles.card}>
          <View style={styles.logoWrap}>
            <Logo size={34} />
            <Text style={styles.welcome}>{cfg.welcome_message || "Seu entretenimento, em qualquer tela."}</Text>
          </View>

          <Text style={styles.label}>Usuário</Text>
          <TextInput
            testID="login-username-input"
            value={username}
            onChangeText={setUsername}
            autoCapitalize="none"
            autoCorrect={false}
            placeholder="Seu usuário"
            placeholderTextColor={colors.muted}
            style={styles.input}
            returnKeyType="next"
          />
          <Text style={styles.label}>Senha</Text>
          <View style={styles.passRow}>
            <TextInput
              testID="login-password-input"
              value={password}
              onChangeText={setPassword}
              secureTextEntry={!show}
              placeholder="Sua senha"
              placeholderTextColor={colors.muted}
              style={[styles.input, { flex: 1, borderWidth: 0 }]}
              onSubmitEditing={submit}
              returnKeyType="go"
            />
            <Focusable testID="login-toggle-password" onPress={() => setShow(!show)} style={styles.eye} focusScale={1}>
              <Ionicons name={show ? "eye-off" : "eye"} size={22} color={colors.onSurfaceTertiary} />
            </Focusable>
          </View>

          <Pressable testID="login-remember-toggle" onPress={() => setRemember(!remember)} style={styles.rememberRow}>
            <View style={[styles.check, remember && { backgroundColor: colors.brandPrimary, borderColor: colors.brandPrimary }]}>
              {remember && <Ionicons name="checkmark" size={14} color={colors.onBrandPrimary} />}
            </View>
            <Text style={styles.rememberText}>Manter conectado</Text>
          </Pressable>

          {error && (
            <Text testID="login-error" style={styles.error}>
              {error}
            </Text>
          )}

          <Focusable testID="login-submit-button" style={styles.btn} onPress={submit} disabled={loading} hasTVPreferredFocus>
            {loading ? <ActivityIndicator color={colors.onBrandPrimary} /> : <Text style={styles.btnText}>Entrar</Text>}
          </Focusable>
          <Text style={styles.hint}>Acesso fornecido pelo administrador do serviço.</Text>
        </View>
      </KeyboardAwareScrollView>
    </View>
  );
}

const useStyles = makeStyles((c) => ({
  root: { flex: 1, backgroundColor: c.surface },
  bg: { position: "absolute", top: 0, left: 0, right: 0, bottom: 0 },
  scroll: { flexGrow: 1, justifyContent: "center", paddingHorizontal: space.xl },
  card: { width: "100%", maxWidth: 440, alignSelf: "center", backgroundColor: c.glass, borderRadius: radius.lg, padding: space.xl, borderWidth: 1, borderColor: c.border },
  logoWrap: { alignItems: "center", marginBottom: space.xl, gap: space.sm },
  welcome: { color: c.onSurfaceTertiary, fontSize: fs(14), textAlign: "center" },
  label: { color: c.onSurfaceSecondary, fontSize: fs(13), fontWeight: "600", marginBottom: space.sm, marginTop: space.md },
  input: { height: 52, backgroundColor: c.surfaceTertiary, color: c.onSurface, borderRadius: radius.md, paddingHorizontal: space.lg, fontSize: fs(16), borderWidth: 1, borderColor: c.border },
  passRow: { flexDirection: "row", alignItems: "center", backgroundColor: c.surfaceTertiary, borderRadius: radius.md, borderWidth: 1, borderColor: c.border },
  eye: { width: 48, height: 48, alignItems: "center", justifyContent: "center", borderRadius: radius.md },
  rememberRow: { flexDirection: "row", alignItems: "center", gap: space.sm, marginTop: space.lg, minHeight: 44 },
  check: { width: 22, height: 22, borderRadius: radius.sm, borderWidth: 1.5, borderColor: c.muted, alignItems: "center", justifyContent: "center" },
  rememberText: { color: c.onSurfaceSecondary, fontSize: fs(14) },
  error: { color: c.error, fontSize: fs(14), marginTop: space.sm },
  btn: { height: 54, backgroundColor: c.brandPrimary, borderRadius: radius.md, alignItems: "center", justifyContent: "center", marginTop: space.lg },
  btnText: { color: c.onBrandPrimary, fontSize: fs(17), fontWeight: "800", letterSpacing: 0.5 },
  hint: { color: c.muted, fontSize: fs(12), textAlign: "center", marginTop: space.lg },
}));
