import React, { useEffect, useState } 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 { getLocalOrders } from "../db/repository";
import { LocalOrder } from "../types";
import { useSyncStore } from "../store/syncStore";

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

export default function OrderConfirmationScreen({ navigation, route }: Props) {
  const { clientUuid } = route.params;
  const [order, setOrder] = useState<LocalOrder | null>(null);
  const isSyncing = useSyncStore((s) => s.isSyncing);

  useEffect(() => {
    const load = async () => {
      const orders = await getLocalOrders();
      setOrder(orders.find((o) => o.clientUuid === clientUuid) || null);
    };
    load();
    const interval = setInterval(load, 1500);
    return () => clearInterval(interval);
  }, [clientUuid]);

  return (
    <SafeAreaView style={styles.container} edges={["bottom", "left", "right"]}>
      <Text style={styles.check}>✓</Text>
      <Text style={styles.title}>Order Submitted</Text>
      <Text style={styles.orderNumber}>{order?.orderNumber || "Order number pending sync"}</Text>
      <Text style={styles.store}>{order?.storeNameSnap}</Text>
      <Text style={styles.total}>Total: Rs. {order?.totalValue.toFixed(2)}</Text>

      <View style={styles.statusPill}>
        <Text style={styles.statusText}>
          {order?.syncStatus === "SYNCED" ? "Synced" : isSyncing ? "Syncing…" : "Pending Sync"}
        </Text>
      </View>

      <Pressable style={styles.button} onPress={() => navigation.popToTop()}>
        <Text style={styles.buttonText}>Back to Home</Text>
      </Pressable>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#fff", alignItems: "center", justifyContent: "center", padding: 24 },
  check: { fontSize: 56, color: "#2ecc71", marginBottom: 8 },
  title: { fontSize: 22, fontWeight: "700" },
  orderNumber: { fontSize: 16, color: "#1a3d7c", fontWeight: "600", marginTop: 8 },
  store: { fontSize: 14, color: "#555", marginTop: 4 },
  total: { fontSize: 18, fontWeight: "700", marginTop: 12 },
  statusPill: { backgroundColor: "#eef1f6", paddingHorizontal: 16, paddingVertical: 8, borderRadius: 20, marginTop: 16 },
  statusText: { fontWeight: "600", color: "#1a3d7c" },
  button: { backgroundColor: "#1a3d7c", borderRadius: 10, paddingVertical: 14, paddingHorizontal: 32, marginTop: 32 },
  buttonText: { color: "#fff", fontWeight: "600", fontSize: 15 },
});
