import React, { useCallback, useState } from "react";
import { View, Text, FlatList, StyleSheet, Pressable, Alert } 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, deleteLocalOrder } from "../db/repository";
import { LocalOrder } from "../types";
import { api } from "../api/client";
import ProductImage from "../components/ProductImage";

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

export default function OrderDetailScreen({ route, navigation }: Props) {
  const { clientUuid } = route.params;
  const [order, setOrder] = useState<LocalOrder | null>(null);
  const [busy, setBusy] = useState(false);

  const load = useCallback(() => {
    getLocalOrders().then((orders) => setOrder(orders.find((o) => o.clientUuid === clientUuid) || null));
  }, [clientUuid]);

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

  if (!order) return null;

  const canEdit = !order.locked;

  const onEdit = () => {
    navigation.navigate("NewOrder", {
      storeId: order.storeId,
      storeName: order.storeNameSnap,
      editingClientUuid: order.clientUuid,
    });
  };

  const onDelete = () => {
    Alert.alert(
      "Delete order?",
      `This will permanently delete ${order.orderNumber || "this order"}. This can't be undone.`,
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Delete",
          style: "destructive",
          onPress: async () => {
            setBusy(true);
            try {
              if (order.serverId) {
                try {
                  await api.delete(`/orders/${order.serverId}`);
                } catch (e: any) {
                  Alert.alert("Could not delete", e.message || "Check your connection and try again.");
                  setBusy(false);
                  return;
                }
              }
              await deleteLocalOrder(order.clientUuid);
              navigation.goBack();
            } finally {
              setBusy(false);
            }
          },
        },
      ]
    );
  };

  return (
    <SafeAreaView style={styles.container} edges={["bottom", "left", "right"]}>
      <View style={styles.headerRow}>
        <View>
          <Text style={styles.orderNumber}>{order.orderNumber || "Pending order number"}</Text>
          <Text style={styles.store}>{order.storeNameSnap}</Text>
          <Text style={styles.date}>{new Date(order.orderDate).toLocaleString()}</Text>
        </View>
        {order.locked ? (
          <View style={styles.lockedBadge}>
            <Text style={styles.lockedBadgeText}>🔒 Locked by Admin</Text>
          </View>
        ) : null}
      </View>

      <Text style={styles.status}>
        Status: {order.syncStatus.replace("_", " ")}
      </Text>

      <FlatList
        style={{ marginTop: 16 }}
        data={order.lines}
        keyExtractor={(item) => item.productId}
        renderItem={({ item }) => (
          <View style={styles.row}>
            <ProductImage productId={item.productId} productName={item.productNameSnap} />
            <View style={{ flex: 1, marginLeft: 12 }}>
              <Text style={styles.name}>{item.productNameSnap}</Text>
              <Text style={styles.meta}>
                {item.packingSnap ? `${item.packingSnap} · ` : ""}Qty {item.quantity}
                {item.rateSnap != null ? ` · Rs. ${item.rateSnap.toFixed(2)} each` : ""}
              </Text>
              {item.bonusQty ? (
                <Text style={styles.bonus}>Bonus: {item.bonusQty} · Total Qty: {item.quantity + item.bonusQty}</Text>
              ) : null}
            </View>
            <Text style={styles.value}>Rs. {item.lineValue.toFixed(2)}</Text>
          </View>
        )}
      />

      <View style={styles.footer}>
        <Text style={styles.totalLabel}>Total</Text>
        <Text style={styles.totalValue}>Rs. {order.totalValue.toFixed(2)}</Text>
      </View>

      {canEdit ? (
        <View style={styles.actions}>
          <Pressable style={styles.editButton} onPress={onEdit} disabled={busy}>
            <Text style={styles.editButtonText}>Edit Order</Text>
          </Pressable>
          <Pressable style={styles.deleteButton} onPress={onDelete} disabled={busy}>
            <Text style={styles.deleteButtonText}>Delete Order</Text>
          </Pressable>
        </View>
      ) : (
        <Text style={styles.lockedNote}>This order is locked and can no longer be edited or deleted.</Text>
      )}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#fff", padding: 16 },
  headerRow: { flexDirection: "row", justifyContent: "space-between", alignItems: "flex-start" },
  orderNumber: { fontSize: 20, fontWeight: "700" },
  store: { fontSize: 15, color: "#333", marginTop: 4 },
  date: { fontSize: 12, color: "#999", marginTop: 2 },
  status: { fontSize: 13, color: "#1a3d7c", fontWeight: "600", marginTop: 8 },
  lockedBadge: { backgroundColor: "#fff3cd", paddingHorizontal: 10, paddingVertical: 6, borderRadius: 8 },
  lockedBadgeText: { fontSize: 12, color: "#b8860b", fontWeight: "700" },
  row: { flexDirection: "row", alignItems: "center", paddingVertical: 10, borderBottomWidth: 1, borderBottomColor: "#f0f0f0" },
  name: { fontSize: 15, fontWeight: "600" },
  meta: { fontSize: 12, color: "#777", marginTop: 2 },
  bonus: { fontSize: 11, color: "#b8860b", fontWeight: "600", marginTop: 2 },
  value: { fontWeight: "600" },
  footer: { flexDirection: "row", justifyContent: "space-between", borderTopWidth: 1, borderTopColor: "#eee", paddingTop: 12, marginTop: 8 },
  totalLabel: { fontSize: 16, fontWeight: "700" },
  totalValue: { fontSize: 18, fontWeight: "700", color: "#1a3d7c" },
  actions: { flexDirection: "row", gap: 12, marginTop: 20 },
  editButton: { flex: 1, backgroundColor: "#1a3d7c", borderRadius: 10, paddingVertical: 14, alignItems: "center" },
  editButtonText: { color: "#fff", fontWeight: "700" },
  deleteButton: { flex: 1, backgroundColor: "#fdecea", borderRadius: 10, paddingVertical: 14, alignItems: "center" },
  deleteButtonText: { color: "#c0392b", fontWeight: "700" },
  lockedNote: { textAlign: "center", color: "#999", marginTop: 20, fontSize: 12 },
});
