import React from "react";
import { View, Text, Pressable, StyleSheet } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { NativeStackScreenProps } from "@react-navigation/native-stack";
import { RootStackParamList } from "../navigation/types";
import { useAuthStore } from "../store/authStore";
import { useSyncStore } from "../store/syncStore";
import { useAreaStore } from "../store/areaStore";
import { runSync } from "../sync/syncManager";

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

export default function HomeScreen({ navigation }: Props) {
  const user = useAuthStore((s) => s.user);
  const logout = useAuthStore((s) => s.logout);
  const { isOnline, isSyncing, pendingCount, lastSyncAt, lastError } = useSyncStore();
  const { selectedAreaName, mode } = useAreaStore();

  return (
    <SafeAreaView style={styles.container} edges={["top", "left", "right", "bottom"]}>
      <View style={styles.header}>
        <Text style={styles.welcome}>Hi, {user?.fullName}</Text>
        <Pressable onPress={logout}>
          <Text style={styles.logout}>Logout</Text>
        </Pressable>
      </View>

      <Pressable style={styles.areaBar} onPress={() => navigation.navigate("SelectArea")}>
        <Text style={styles.areaText}>
          Area: <Text style={styles.areaName}>{selectedAreaName || "All areas"}</Text>
        </Text>
        <Text style={styles.areaChange}>{mode === "scheduled" ? "Switch assigned area" : "Change"}</Text>
      </Pressable>

      <Pressable style={styles.syncBar} onPress={runSync}>
        <View style={[styles.dot, { backgroundColor: isOnline ? "#2ecc71" : "#e74c3c" }]} />
        <Text style={styles.syncText}>
          {isOnline ? "Online" : "Offline"}
          {isSyncing ? " · Syncing…" : pendingCount > 0 ? ` · ${pendingCount} pending sync` : " · Up to date"}
        </Text>
      </Pressable>

      {lastError ? <Text style={styles.errorText}>{lastError} · tap sync status to retry</Text> : null}

      <View style={styles.grid}>
        <MenuButton label="New Order" onPress={() => navigation.navigate("Stores", { pickMode: true })} />
        <MenuButton label="Medical Stores" onPress={() => navigation.navigate("Stores")} />
        <MenuButton label="My Orders" onPress={() => navigation.navigate("MyOrders")} />
      </View>

      {lastSyncAt ? <Text style={styles.footer}>Last synced: {new Date(lastSyncAt).toLocaleString()}</Text> : null}
    </SafeAreaView>
  );
}

function MenuButton({ label, onPress }: { label: string; onPress: () => void }) {
  return (
    <Pressable style={styles.menuButton} onPress={onPress}>
      <Text style={styles.menuButtonText}>{label}</Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#fff", padding: 20 },
  header: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginBottom: 16 },
  welcome: { fontSize: 20, fontWeight: "700" },
  logout: { color: "#c0392b", fontWeight: "600" },
  areaBar: {
    flexDirection: "row", justifyContent: "space-between", alignItems: "center",
    backgroundColor: "#eef1f6", padding: 12, borderRadius: 8, marginBottom: 12,
  },
  areaText: { fontSize: 14, color: "#333" },
  areaName: { fontWeight: "700", color: "#1a3d7c" },
  areaChange: { fontSize: 12, color: "#1a3d7c", fontWeight: "600", textDecorationLine: "underline" },
  syncBar: { flexDirection: "row", alignItems: "center", backgroundColor: "#f2f4f7", padding: 10, borderRadius: 8, marginBottom: 24 },
  dot: { width: 10, height: 10, borderRadius: 5, marginRight: 8 },
  syncText: { fontSize: 13, color: "#333" },
  errorText: { fontSize: 12, color: "#c0392b", marginTop: -16, marginBottom: 16 },
  grid: { gap: 12 },
  menuButton: { backgroundColor: "#1a3d7c", borderRadius: 10, paddingVertical: 18, alignItems: "center" },
  menuButtonText: { color: "#fff", fontSize: 16, fontWeight: "600" },
  footer: { marginTop: "auto", textAlign: "center", color: "#999", fontSize: 12 },
});
