import React, { useEffect, useState } from "react";
import { View, Text, FlatList, Pressable, StyleSheet, TextInput, Alert } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { NativeStackScreenProps } from "@react-navigation/native-stack";
import { RootStackParamList } from "../navigation/types";
import { useCartStore } from "../store/cartStore";
import { saveLocalOrder, getLocalOrder, updateOrderLines, getProducts } from "../db/repository";
import { generateUuid } from "../utils/uuid";
import { runSync } from "../sync/syncManager";
import { api } from "../api/client";
import { Product } from "../types";

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

export default function OrderReviewScreen({ navigation, route }: Props) {
  const editingClientUuid = route.params?.editingClientUuid;
  const { storeId, storeName, lines, clear } = useCartStore();
  const setQuantityByProductId = useCartStore((s) => s.setQuantity);
  const totalValue = useCartStore((s) => s.totalValue());
  const [submitting, setSubmitting] = useState(false);
  const [productsById, setProductsById] = useState<Record<string, Product>>({});
  const lineList = Object.values(lines);

  useEffect(() => {
    getProducts().then((products) => {
      setProductsById(Object.fromEntries(products.map((p) => [p.id, p])));
    });
  }, []);

  const submitNew = async () => {
    if (!storeId || !storeName || lineList.length === 0) return;
    const clientUuid = generateUuid();
    await saveLocalOrder({
      clientUuid,
      storeId,
      storeNameSnap: storeName,
      orderDate: new Date().toISOString(),
      totalValue,
      syncStatus: "PENDING_SYNC",
      locked: false,
      createdAt: new Date().toISOString(),
      lines: lineList,
    });
    clear();
    runSync();
    navigation.replace("OrderConfirmation", { clientUuid });
  };

  const submitEdit = async () => {
    if (!editingClientUuid || lineList.length === 0) return;
    const existing = await getLocalOrder(editingClientUuid);
    if (!existing) return;

    if (existing.syncStatus === "SYNCED" && existing.serverId) {
      if (existing.locked) {
        Alert.alert("Order locked", "This order has been locked by Admin and can no longer be edited.");
        return;
      }
      try {
        await api.put(`/orders/${existing.serverId}/edit`, {
          storeId: existing.storeId,
          storeNameSnap: existing.storeNameSnap,
          lines: lineList,
        });
      } catch (e: any) {
        Alert.alert("Could not save changes", e.message || "Check your connection and try again.");
        return;
      }
    }

    await updateOrderLines(editingClientUuid, lineList, totalValue);
    clear();
    navigation.navigate("OrderDetail", { clientUuid: editingClientUuid });
  };

  const submit = async () => {
    setSubmitting(true);
    try {
      if (editingClientUuid) {
        await submitEdit();
      } else {
        await submitNew();
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <SafeAreaView style={styles.container} edges={["bottom", "left", "right"]}>
      <Text style={styles.storeLabel}>{editingClientUuid ? "Editing order for " : ""}{storeName}</Text>
      <FlatList
        data={lineList}
        keyExtractor={(item) => item.productId}
        renderItem={({ item }) => {
          const product = productsById[item.productId];
          const bonusQty = item.bonusQty ?? 0;
          return (
            <View style={styles.row}>
              <View style={{ flex: 1 }}>
                <Text style={styles.name}>{item.productNameSnap}</Text>
                <Text style={styles.meta}>{item.packingSnap || ""}</Text>
                {bonusQty > 0 ? (
                  <Text style={styles.bonus}>
                    Bonus: {bonusQty} · Total Qty: {item.quantity + bonusQty}
                  </Text>
                ) : null}
              </View>
              <TextInput
                style={styles.qtyInput}
                keyboardType="numeric"
                value={String(item.quantity)}
                onChangeText={(v) => {
                  const qty = Math.max(0, parseInt(v || "0", 10) || 0);
                  setQuantityByProductId(
                    {
                      id: item.productId,
                      name: item.productNameSnap,
                      packing: item.packingSnap,
                      netRate: item.rateSnap,
                      bonus: product?.bonus,
                      bonusBuyQty: product?.bonusBuyQty,
                      bonusFreeQty: product?.bonusFreeQty,
                    },
                    qty
                  );
                }}
              />
              <Text style={styles.lineValue}>Rs. {item.lineValue.toFixed(2)}</Text>
            </View>
          );
        }}
        ListEmptyComponent={<Text style={styles.empty}>No products selected.</Text>}
      />

      <View style={styles.footer}>
        <Text style={styles.footerTotal}>Total: Rs. {totalValue.toFixed(2)}</Text>
        <Pressable style={styles.submitButton} disabled={submitting || lineList.length === 0} onPress={submit}>
          <Text style={styles.submitButtonText}>
            {submitting ? "Saving…" : editingClientUuid ? "Save Changes" : "Submit Order"}
          </Text>
        </Pressable>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#fff", padding: 16 },
  storeLabel: { fontSize: 16, fontWeight: "700", marginBottom: 12 },
  row: { flexDirection: "row", alignItems: "center", paddingVertical: 10, borderBottomWidth: 1, borderBottomColor: "#f0f0f0" },
  name: { fontSize: 15, fontWeight: "600" },
  meta: { fontSize: 12, color: "#777" },
  bonus: { fontSize: 11, color: "#b8860b", fontWeight: "600", marginTop: 2 },
  qtyInput: { width: 44, textAlign: "center", borderWidth: 1, borderColor: "#ddd", borderRadius: 6, paddingVertical: 4, marginHorizontal: 8 },
  lineValue: { width: 90, textAlign: "right", fontWeight: "600" },
  empty: { textAlign: "center", color: "#999", marginTop: 40 },
  footer: { borderTopWidth: 1, borderTopColor: "#eee", paddingTop: 12, marginTop: 8 },
  footerTotal: { fontSize: 20, fontWeight: "700", color: "#1a3d7c", marginBottom: 12, textAlign: "right" },
  submitButton: { backgroundColor: "#1a3d7c", borderRadius: 10, paddingVertical: 14, alignItems: "center" },
  submitButtonText: { color: "#fff", fontWeight: "700", fontSize: 16 },
});
