import { useEffect } from "react";
import {
  ScrollView,
  View,
  Text,
  Image,
  Pressable,
  StyleSheet,
} 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 { useApp } from "../context/AppContext";

type QuickAction = {
  key: string;
  title: string;
  icon: keyof typeof Ionicons.glyphMap;
  color: string;
  bg: string;
  onPress: () => void;
};

export default function HomeScreen() {
  const { user, eta, route, loading, refreshStatus } = useApp();
  const router = useRouter();

  useEffect(() => {
    if (user && !eta) {
      void refreshStatus();
    }
  }, [user]);

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

  const minutes = eta ? Math.max(0, eta.etaMinutes) : null;
  const windowText = eta?.arrivalWindow
    ? `${eta.arrivalWindow.from} - ${eta.arrivalWindow.to} a.m.`
    : "Calculando...";

  const statusOK = route?.status === "EN_RUTA" || route?.status === "ESPERA";
  const statusColor = statusOK ? "#22C55E" : "#EF4444";
  const statusLabel =
    route?.status === "EN_RUTA"
      ? "ESTABLE"
      : route?.status === "FALLA"
        ? "CON FALLA"
        : route?.status === "DETENIDO"
          ? "DETENIDO"
          : "EN ESPERA";

  const quickActions: QuickAction[] = [
    {
      key: "alerts",
      title: "Alertas",
      icon: "notifications-outline",
      color: "#22C55E",
      bg: "#ECFDF5",
      onPress: () => router.push("/alerts"),
    },
    {
      key: "guide",
      title: "Guía",
      icon: "leaf-outline",
      color: "#3B82F6",
      bg: "#EFF6FF",
      onPress: () => router.push("/guide"),
    },
    {
      key: "feedback",
      title: "Reportar",
      icon: "chatbubble-outline",
      color: "#EF4444",
      bg: "#FEF2F2",
      onPress: () => router.push("/feedback"),
    },
    {
      key: "address",
      title: "Domicilio",
      icon: "home-outline",
      color: "#8B5CF6",
      bg: "#F5F3FF",
      onPress: () => router.push("/addresses"),
    },
  ];

  return (
    <SafeAreaView
      style={{ flex: 1, backgroundColor: COLORS.background }}
      edges={["top"]}
    >
      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={{ paddingBottom: 130 }}
        refreshControl={undefined}
      >
        {/* Title */}
        <View style={styles.titleRow}>
          <View>
            <Text style={styles.title}>EcoRuta</Text>
            <Text style={styles.subtitle}>
              Ruta {route?.routeId ?? "—"}
            </Text>
          </View>
        </View>

        {/* Hero del camión */}
        <View style={styles.heroBox}>
          <Image
            source={require("../../assets/illustrations/truck-city.png")}
            style={styles.heroTruck}
            resizeMode="cover"
          />
        </View>

        {/* Card ETA */}
        <View style={styles.etaCard}>
          <View style={styles.etaContent}>
            <View style={styles.etaIcon}>
              <Ionicons name="time-outline" size={22} color="#0E8A61" />
            </View>
            <View style={{ flex: 1 }}>
              <Text style={styles.etaLabel}>LLEGADA ESTIMADA</Text>
              <Text style={styles.etaMinutes}>
                {minutes !== null
                  ? `${minutes} min`
                  : loading
                    ? "..."
                    : "—"}
              </Text>
              <Text style={styles.etaWindowLabel}>Ventana de recolección</Text>
              <View style={styles.windowPill}>
                <Text style={styles.windowText}>{windowText}</Text>
              </View>
            </View>
            <View style={styles.etaCircle}>
              <View style={styles.etaCircleInner}>
                <Ionicons name="bus-outline" size={28} color="#0E8A61" />
              </View>
            </View>
          </View>
        </View>

        {/* Estado de ruta */}
        <View style={styles.statusBanner}>
          <View
            style={[
              styles.statusDot,
              { backgroundColor: statusColor },
            ]}
          />
          <View style={{ flex: 1 }}>
            <Text style={[styles.statusTitle, { color: statusColor }]}>
              ESTADO DE RUTA: {statusLabel}
            </Text>
            <Text style={styles.statusBody}>
              {statusOK
                ? "Tu recolección sigue en horario normal."
                : "Hay incidencias en la ruta."}
            </Text>
          </View>
          <View
            style={[
              styles.statusShield,
              { backgroundColor: `${statusColor}15` },
            ]}
          >
            <Ionicons
              name="shield-checkmark-outline"
              size={20}
              color={statusColor}
            />
          </View>
        </View>

        {/* Mensaje preventivo */}
        <View style={styles.warningBanner}>
          <View style={styles.warningIcon}>
            <Ionicons name="alert" size={20} color="#FFFFFF" />
          </View>
          <Text style={styles.warningText}>
            No saques tus residuos fuera del horario{"\n"}y no persigas al camión.
          </Text>
          <View style={styles.warningRight}>
            <Ionicons name="walk-outline" size={20} color="#92400E" />
          </View>
        </View>

        {/* Acciones rápidas */}
        <Text style={styles.sectionTitle}>ACCIONES RÁPIDAS</Text>
        <View style={styles.actionsGrid}>
          {quickActions.map((a) => (
            <Pressable
              key={a.key}
              style={styles.actionCard}
              onPress={a.onPress}
            >
              <View style={[styles.actionIcon, { backgroundColor: a.bg }]}>
                <Ionicons name={a.icon} size={26} color={a.color} />
              </View>
              <Text style={styles.actionTitle}>{a.title}</Text>
            </Pressable>
          ))}
        </View>

        {/* Consejo rápido */}
        <View style={styles.tipCard}>
          <View style={styles.tipIcon}>
            <Ionicons name="leaf" size={22} color="#0E8A61" />
          </View>
          <View style={{ flex: 1 }}>
            <Text style={styles.tipTitle}>Consejo rápido</Text>
            <Text style={styles.tipBody}>
              Compacta cartón y PET para ahorrar espacio y ayudar al medio
              ambiente.
            </Text>
          </View>
          <Image
            source={require("../../assets/illustrations/pet-bottles.png")}
            style={styles.tipImage}
            resizeMode="contain"
          />
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  titleRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingHorizontal: 20,
    paddingTop: 8,
  },
  title: {
    fontSize: 32,
    fontWeight: "800",
    color: "#0E8A61",
  },
  subtitle: {
    fontSize: 14,
    color: "#6B7280",
    marginTop: 2,
  },
  heroBox: {
    height: 180,
    marginTop: 8,
    backgroundColor: "#DBEAFE",
    overflow: "hidden",
  },
  heroTruck: {
    width: "100%",
    height: "100%",
  },
  etaCard: {
    marginHorizontal: 20,
    marginTop: -30,
    backgroundColor: "#ECFDF5",
    borderRadius: 20,
    padding: 18,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 6 },
    shadowOpacity: 0.08,
    shadowRadius: 10,
    elevation: 6,
  },
  etaContent: {
    flexDirection: "row",
    alignItems: "center",
  },
  etaIcon: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: "#FFFFFF",
    justifyContent: "center",
    alignItems: "center",
    marginRight: 12,
  },
  etaLabel: {
    fontSize: 11,
    fontWeight: "800",
    color: "#065F46",
    letterSpacing: 0.5,
  },
  etaMinutes: {
    fontSize: 36,
    fontWeight: "800",
    color: "#0F172A",
    marginTop: 4,
    lineHeight: 38,
  },
  etaWindowLabel: {
    fontSize: 11,
    color: "#6B7280",
    marginTop: 6,
  },
  windowPill: {
    alignSelf: "flex-start",
    backgroundColor: "#D1FAE5",
    borderRadius: 10,
    paddingHorizontal: 10,
    paddingVertical: 4,
    marginTop: 4,
  },
  windowText: {
    fontSize: 13,
    color: "#065F46",
    fontWeight: "700",
  },
  etaCircle: {
    width: 88,
    height: 88,
    borderRadius: 44,
    borderWidth: 4,
    borderColor: "#22C55E",
    justifyContent: "center",
    alignItems: "center",
    marginLeft: 8,
  },
  etaCircleInner: {
    width: 64,
    height: 64,
    borderRadius: 32,
    backgroundColor: "#FFFFFF",
    justifyContent: "center",
    alignItems: "center",
  },
  statusBanner: {
    flexDirection: "row",
    alignItems: "center",
    marginHorizontal: 20,
    marginTop: 14,
    backgroundColor: "#FFFFFF",
    borderRadius: 14,
    padding: 14,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 2,
  },
  statusDot: {
    width: 12,
    height: 12,
    borderRadius: 6,
    marginRight: 12,
  },
  statusTitle: {
    fontSize: 13,
    fontWeight: "800",
  },
  statusBody: {
    fontSize: 12,
    color: "#374151",
    marginTop: 2,
  },
  statusShield: {
    width: 36,
    height: 36,
    borderRadius: 18,
    justifyContent: "center",
    alignItems: "center",
    marginLeft: 8,
  },
  warningBanner: {
    flexDirection: "row",
    alignItems: "center",
    marginHorizontal: 20,
    marginTop: 12,
    backgroundColor: "#FEF3C7",
    borderRadius: 14,
    padding: 12,
  },
  warningIcon: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: "#F59E0B",
    justifyContent: "center",
    alignItems: "center",
    marginRight: 10,
  },
  warningText: {
    flex: 1,
    fontSize: 12,
    color: "#92400E",
    fontWeight: "600",
    lineHeight: 16,
  },
  warningRight: {
    marginLeft: 8,
  },
  sectionTitle: {
    fontSize: 12,
    fontWeight: "800",
    color: "#6B7280",
    letterSpacing: 1,
    marginTop: 22,
    marginBottom: 10,
    marginLeft: 20,
  },
  actionsGrid: {
    flexDirection: "row",
    justifyContent: "space-between",
    paddingHorizontal: 20,
  },
  actionCard: {
    flex: 1,
    backgroundColor: "#FFFFFF",
    borderRadius: 14,
    paddingVertical: 14,
    alignItems: "center",
    marginHorizontal: 4,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 2,
  },
  actionIcon: {
    width: 50,
    height: 50,
    borderRadius: 25,
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 8,
  },
  actionTitle: {
    fontSize: 12,
    fontWeight: "700",
    color: "#0F172A",
    textAlign: "center",
  },
  tipCard: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#ECFDF5",
    borderRadius: 16,
    padding: 14,
    marginHorizontal: 20,
    marginTop: 16,
  },
  tipIcon: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: "#FFFFFF",
    justifyContent: "center",
    alignItems: "center",
    marginRight: 12,
  },
  tipTitle: {
    fontSize: 14,
    fontWeight: "800",
    color: "#065F46",
    marginBottom: 2,
  },
  tipBody: {
    fontSize: 12,
    color: "#065F46",
    lineHeight: 16,
  },
  tipImage: {
    width: 60,
    height: 60,
    marginLeft: 8,
  },
});
