import React, { useCallback, useState } from "react";
import { View, Text, TextInput, FlatList, Pressable, StyleSheet } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { useFocusEffect } from "@react-navigation/native";
import { NativeStackScreenProps } from "@react-navigation/native-stack";
import { RootStackParamList } from "../navigation/types";
import { getStores } from "../db/repository";
import { useAreaStore } from "../store/areaStore";
import { MedicalStore } from "../types";

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

export default function StoresScreen({ navigation, route }: Props) {
  const pickMode = !!route.params?.pickMode;
  const [search, setSearch] = useState("");
  const [stores, setStores] = useState<MedicalStore[]>([]);
  const selectedAreaId = useAreaStore((s) => s.selectedAreaId);
  const selectedAreaName = useAreaStore((s) => s.selectedAreaName);

  const load = useCallback(async () => {
    const rows = await getStores(search || undefined, selectedAreaId || undefined);
    setStores(rows);
  }, [search, selectedAreaId]);

  useFocusEffect(
    useCallback(() => {
      load();
    }, [load])
  );

  const onSelectStore = (store: MedicalStore) => {
    if (pickMode) {
      navigation.navigate("NewOrder", { storeId: store.id, storeName: store.name });
    } else {
      navigation.navigate("StoreForm", { storeId: store.id });
    }
  };

  return (
    <SafeAreaView style={styles.container} edges={["bottom", "left", "right"]}>
      <Text style={styles.title}>{pickMode ? "Select a Medical Store" : "Medical Stores"}</Text>
      {selectedAreaName ? <Text style={styles.areaNote}>Showing stores in {selectedAreaName}</Text> : null}
      <TextInput
        style={styles.search}
        placeholder="Search by name…"
        value={search}
        onChangeText={setSearch}
      />
      <FlatList
        data={stores}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <Pressable style={styles.row} onPress={() => onSelectStore(item)}>
            <View>
              <Text style={styles.rowTitle}>{item.name}</Text>
              <Text style={styles.rowSub}>
                {[item.city, item.phone].filter(Boolean).join(" · ") || "No contact details"}
              </Text>
            </View>
            {item.syncStatus === "PENDING_SYNC" ? <Text style={styles.badge}>Pending</Text> : null}
          </Pressable>
        )}
        ListEmptyComponent={
          <Text style={styles.empty}>
            {selectedAreaName ? `No stores found in ${selectedAreaName}. Add one below.` : "No stores found. Add one below."}
          </Text>
        }
      />
      <Pressable style={styles.addButton} onPress={() => navigation.navigate("StoreForm")}>
        <Text style={styles.addButtonText}>+ Add Medical Store</Text>
      </Pressable>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#fff", padding: 16 },
  title: { fontSize: 18, fontWeight: "700", marginBottom: 4 },
  areaNote: { fontSize: 12, color: "#1a3d7c", fontWeight: "600", marginBottom: 8 },
  search: { borderWidth: 1, borderColor: "#ccc", borderRadius: 8, paddingHorizontal: 12, paddingVertical: 10, marginBottom: 12 },
  row: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", paddingVertical: 14, borderBottomWidth: 1, borderBottomColor: "#eee" },
  rowTitle: { fontSize: 16, fontWeight: "600" },
  rowSub: { fontSize: 13, color: "#777", marginTop: 2 },
  badge: { fontSize: 11, color: "#b8860b", backgroundColor: "#fff3cd", paddingHorizontal: 8, paddingVertical: 3, borderRadius: 10 },
  empty: { textAlign: "center", color: "#999", marginTop: 40 },
  addButton: { backgroundColor: "#1a3d7c", borderRadius: 10, paddingVertical: 14, alignItems: "center", marginTop: 12 },
  addButtonText: { color: "#fff", fontWeight: "600", fontSize: 15 },
});
