import React, { useCallback, useEffect, useState } from "react";
import { View, Text, FlatList, Pressable, StyleSheet, ActivityIndicator } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { NativeStackScreenProps } from "@react-navigation/native-stack";
import { RootStackParamList } from "../navigation/types";
import { useAreaStore } from "../store/areaStore";
import { runSync } from "../sync/syncManager";
import { Area } from "../types";

type Props = NativeStackScreenProps<RootStackParamList, "SelectArea">;

export default function SelectAreaScreen({ navigation }: Props) {
  const { mode, options, selectArea, loadToday } = useAreaStore();
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(async () => {
    setLoading(true);
    await runSync();
    await loadToday();
    setLoading(false);
  }, [loadToday]);

  useEffect(() => {
    refresh();
  }, [refresh]);

  const onSelect = (area: Area) => {
    selectArea(area);
    navigation.navigate("Home");
  };

  const continueWithoutFilter = () => {
    selectArea(null);
    navigation.navigate("Home");
  };

  if (loading) {
    return (
      <View style={styles.center}>
        <ActivityIndicator size="large" color="#1a3d7c" />
        <Text style={styles.loadingText}>Checking today's schedule…</Text>
      </View>
    );
  }

  return (
    <SafeAreaView style={styles.container} edges={["bottom", "left", "right"]}>
      <Text style={styles.title}>{mode === "scheduled" ? "Today's Assigned Areas" : "Select an Area"}</Text>
      <Text style={styles.subtitle}>
        {mode === "scheduled"
          ? "Admin has scheduled you for these areas today. Pick one to continue."
          : "No route assigned for today — pick an area to see its medical stores."}
      </Text>

      <FlatList
        data={options}
        keyExtractor={(item) => item.id}
        contentContainerStyle={{ paddingVertical: 12 }}
        renderItem={({ item }) => (
          <Pressable style={styles.card} onPress={() => onSelect(item)}>
            <Text style={styles.cardName}>{item.name}</Text>
            {item.city ? <Text style={styles.cardCity}>{item.city}</Text> : null}
          </Pressable>
        )}
        ListEmptyComponent={
          <View style={styles.empty}>
            <Text style={styles.emptyText}>
              No areas available offline yet. Connect to the internet and try again.
            </Text>
            <Pressable style={styles.retryButton} onPress={refresh}>
              <Text style={styles.retryButtonText}>Retry</Text>
            </Pressable>
          </View>
        }
      />

      {mode === "free" && options.length > 0 ? (
        <Pressable style={styles.skipButton} onPress={continueWithoutFilter}>
          <Text style={styles.skipButtonText}>Continue without an area filter</Text>
        </Pressable>
      ) : null}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#fff", padding: 20 },
  center: { flex: 1, alignItems: "center", justifyContent: "center", backgroundColor: "#fff" },
  loadingText: { marginTop: 12, color: "#777" },
  title: { fontSize: 20, fontWeight: "700", marginTop: 12 },
  subtitle: { fontSize: 13, color: "#666", marginTop: 6, lineHeight: 18 },
  card: {
    backgroundColor: "#f2f4f7",
    borderRadius: 12,
    paddingVertical: 18,
    paddingHorizontal: 18,
    marginBottom: 12,
  },
  cardName: { fontSize: 17, fontWeight: "700", color: "#1a3d7c" },
  cardCity: { fontSize: 13, color: "#777", marginTop: 2 },
  empty: { alignItems: "center", marginTop: 40 },
  emptyText: { textAlign: "center", color: "#999", marginBottom: 16 },
  retryButton: { backgroundColor: "#1a3d7c", borderRadius: 10, paddingVertical: 10, paddingHorizontal: 24 },
  retryButtonText: { color: "#fff", fontWeight: "600" },
  skipButton: { alignItems: "center", paddingVertical: 14 },
  skipButtonText: { color: "#777", fontWeight: "600", fontSize: 13, textDecorationLine: "underline" },
});
