import React, { useCallback, useState } from "react";
import { View, Text, FlatList, Pressable, StyleSheet, TextInput } 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 { getLocalOrders } from "../db/repository";
import { LocalOrder } from "../types";

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

function isToday(iso: string) {
  const d = new Date(iso);
  const now = new Date();
  return d.toDateString() === now.toDateString();
}

function isThisMonth(iso: string) {
  const d = new Date(iso);
  const now = new Date();
  return d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth();
}

export default function MyOrdersScreen({ navigation }: Props) {
  const [orders, setOrders] = useState<LocalOrder[]>([]);
  const [search, setSearch] = useState("");

  useFocusEffect(
    useCallback(() => {
      getLocalOrders().then(setOrders);
    }, [])
  );

  const todayTotal = orders.filter((o) => isToday(o.orderDate)).reduce((s, o) => s + o.totalValue, 0);
  const monthTotal = orders.filter((o) => isThisMonth(o.orderDate)).reduce((s, o) => s + o.totalValue, 0);

  const q = search.trim().toLowerCase();
  const filtered = q
    ? orders.filter(
        (o) => (o.orderNumber || "").toLowerCase().includes(q) || o.storeNameSnap.toLowerCase().includes(q)
      )
    : orders;

  return (
    <SafeAreaView style={styles.container} edges={["bottom", "left", "right"]}>
      <View style={styles.summaryRow}>
        <View style={styles.summaryCard}>
          <Text style={styles.summaryLabel}>Today</Text>
          <Text style={styles.summaryValue}>Rs. {todayTotal.toFixed(0)}</Text>
        </View>
        <View style={styles.summaryCard}>
          <Text style={styles.summaryLabel}>This Month</Text>
          <Text style={styles.summaryValue}>Rs. {monthTotal.toFixed(0)}</Text>
        </View>
      </View>

      <TextInput
        style={styles.search}
        placeholder="Search order # or store…"
        value={search}
        onChangeText={setSearch}
      />

      <FlatList
        data={filtered}
        keyExtractor={(item) => item.clientUuid}
        renderItem={({ item }) => (
          <Pressable style={styles.row} onPress={() => navigation.navigate("OrderDetail", { clientUuid: item.clientUuid })}>
            <View style={{ flex: 1 }}>
              <View style={{ flexDirection: "row", alignItems: "center" }}>
                <Text style={styles.orderNumber}>{item.orderNumber || "Pending order number"}</Text>
                {item.locked ? <Text style={styles.lockIcon}> 🔒</Text> : null}
              </View>
              <Text style={styles.store}>{item.storeNameSnap}</Text>
              <Text style={styles.date}>{new Date(item.orderDate).toLocaleString()}</Text>
            </View>
            <View style={{ alignItems: "flex-end" }}>
              <Text style={styles.value}>Rs. {item.totalValue.toFixed(2)}</Text>
              <Text style={[styles.status, item.syncStatus !== "SYNCED" && styles.statusPending]}>
                {item.syncStatus.replace("_", " ")}
              </Text>
            </View>
          </Pressable>
        )}
        ListEmptyComponent={<Text style={styles.empty}>No orders yet.</Text>}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#fff", padding: 16 },
  summaryRow: { flexDirection: "row", gap: 12, marginBottom: 16 },
  summaryCard: { flex: 1, backgroundColor: "#eef1f6", borderRadius: 10, padding: 14 },
  summaryLabel: { fontSize: 12, color: "#666" },
  summaryValue: { fontSize: 18, fontWeight: "700", color: "#1a3d7c", marginTop: 4 },
  search: { borderWidth: 1, borderColor: "#ccc", borderRadius: 8, paddingHorizontal: 12, paddingVertical: 8, marginBottom: 12 },
  row: { flexDirection: "row", justifyContent: "space-between", paddingVertical: 12, borderBottomWidth: 1, borderBottomColor: "#f0f0f0" },
  orderNumber: { fontWeight: "700", fontSize: 15 },
  lockIcon: { fontSize: 12 },
  store: { fontSize: 13, color: "#555", marginTop: 2 },
  date: { fontSize: 11, color: "#999", marginTop: 2 },
  value: { fontWeight: "700" },
  status: { fontSize: 11, color: "#2ecc71", marginTop: 4 },
  statusPending: { color: "#b8860b" },
  empty: { textAlign: "center", color: "#999", marginTop: 40 },
});
