import { useEffect, useState } from "react";
import {
  ScrollView,
  View,
  Text,
  StyleSheet,
  Pressable,
  ActivityIndicator,
  Alert,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Ionicons } from "@expo/vector-icons";
import { Redirect, useRouter } from "expo-router";

import { COLORS } from "../constants/colors";
import SectionTitle from "../components/SectionTitle";
import PrimaryButton from "../components/PrimaryButton";

import { useApp } from "../context/AppContext";
import {
  listColonias,
  getMyAddress,
  setMyAddress,
  type Colonia,
  type MyAddress,
} from "../services/addresses.service";

export default function AddressesScreen() {
  const { user, refreshStatus } = useApp();
  const router = useRouter();

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [colonias, setColonias] = useState<Colonia[]>([]);
  const [myAddress, setMy] = useState<MyAddress | null>(null);
  const [selected, setSelected] = useState<string | null>(null);

  useEffect(() => {
    if (!user) return;
    void (async () => {
      try {
        const [c, mine] = await Promise.all([listColonias(), getMyAddress()]);
        setColonias(c);
        setMy(mine);
        setSelected(mine.colonia);
      } catch (err) {
        console.error(err);
      } finally {
        setLoading(false);
      }
    })();
  }, [user]);

  if (!user) return <Redirect href="/login" />;

  const handleSave = async () => {
    if (!selected) {
      Alert.alert("Selecciona una colonia.");
      return;
    }
    try {
      setSaving(true);
      const result = await setMyAddress(selected);
      setMy(result);
      await refreshStatus();
      Alert.alert(
        "Domicilio validado",
        `Tu zona es ${result.colonia}. Horario: ${result.horarioEstimado}`,
      );
      router.replace("/");
    } catch (err) {
      Alert.alert(
        "No se pudo guardar",
        err instanceof Error ? err.message : "Error desconocido",
      );
    } finally {
      setSaving(false);
    }
  };

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: COLORS.background }}>
      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={{ padding: 20, paddingBottom: 120 }}
      >
        <SectionTitle title="Mi domicilio" />

        <Text style={styles.subtitle}>
          Selecciona la colonia donde quieres recibir avisos de recolección.
          Solo verás la ruta que cubre tu zona.
        </Text>

        {myAddress && (
          <View style={styles.currentBox}>
            <Text style={styles.currentLabel}>Domicilio actual</Text>
            <Text style={styles.currentValue}>{myAddress.colonia}</Text>
            <Text style={styles.currentMeta}>
              Ruta {myAddress.routeId}
              {myAddress.horarioEstimado
                ? ` • ${myAddress.horarioEstimado}`
                : ""}
            </Text>
          </View>
        )}

        <Text style={styles.label}>Colonias disponibles</Text>

        {loading ? (
          <ActivityIndicator color="#0E8A61" style={{ marginTop: 20 }} />
        ) : (
          colonias.map((c) => {
            const active = selected === c.colonia;
            return (
              <Pressable
                key={c.colonia}
                onPress={() => setSelected(c.colonia)}
                style={[
                  styles.optionRow,
                  active && {
                    borderColor: "#0E8A61",
                    borderWidth: 2,
                  },
                ]}
              >
                <Ionicons
                  name={active ? "radio-button-on" : "radio-button-off"}
                  size={22}
                  color={active ? "#0E8A61" : "#9CA3AF"}
                />
                <View style={{ marginLeft: 12, flex: 1 }}>
                  <Text style={styles.optionTitle}>{c.colonia}</Text>
                  <Text style={styles.optionMeta}>
                    Ruta {c.routeId} • {c.horarioEstimado}
                  </Text>
                </View>
              </Pressable>
            );
          })
        )}

        <View style={{ height: 16 }} />
        <PrimaryButton
          title={saving ? "Guardando..." : "Validar domicilio"}
          onPress={handleSave}
        />
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  subtitle: {
    color: "#6B7280",
    fontSize: 14,
    marginBottom: 16,
    marginLeft: 12,
  },
  currentBox: {
    backgroundColor: "#FFFFFF",
    borderRadius: 14,
    padding: 16,
    marginBottom: 18,
    marginHorizontal: 2,
    borderLeftWidth: 4,
    borderLeftColor: "#0E8A61",
  },
  currentLabel: {
    fontSize: 11,
    color: "#6B7280",
    fontWeight: "700",
    marginBottom: 4,
    textTransform: "uppercase",
  },
  currentValue: { fontSize: 18, fontWeight: "800", color: "#1F2937" },
  currentMeta: { fontSize: 13, color: "#6B7280", marginTop: 4 },
  label: {
    fontSize: 13,
    fontWeight: "700",
    color: "#374151",
    marginBottom: 10,
    marginLeft: 12,
  },
  optionRow: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#FFFFFF",
    borderRadius: 12,
    padding: 14,
    marginBottom: 10,
    borderColor: "transparent",
    borderWidth: 2,
  },
  optionTitle: { fontSize: 15, fontWeight: "700", color: "#1F2937" },
  optionMeta: { fontSize: 12, color: "#6B7280", marginTop: 2 },
});
