import React, { useCallback, useEffect, useState } from "react";
import { View, Text, TextInput, FlatList, Pressable, StyleSheet } 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 { getProducts, getLocalOrder } from "../db/repository";
import { Product } from "../types";
import { useCartStore } from "../store/cartStore";
import ProductImage from "../components/ProductImage";

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

export default function NewOrderScreen({ navigation, route }: Props) {
  const { storeId, storeName, editingClientUuid } = route.params;
  const [search, setSearch] = useState("");
  const [products, setProducts] = useState<Product[]>([]);
  const setStore = useCartStore((s) => s.setStore);
  const loadLines = useCartStore((s) => s.loadLines);
  const lines = useCartStore((s) => s.lines);
  const setQuantity = useCartStore((s) => s.setQuantity);
  const totalValue = useCartStore((s) => s.totalValue());
  const totalItems = useCartStore((s) => s.totalItems());

  useEffect(() => {
    if (editingClientUuid) {
      getLocalOrder(editingClientUuid).then((order) => {
        if (order) loadLines(storeId, storeName, order.lines);
      });
    } else {
      setStore(storeId, storeName);
    }
  }, [storeId, storeName, editingClientUuid]);

  const load = useCallback(async () => {
    const rows = await getProducts(search || undefined);
    setProducts(rows);
  }, [search]);

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

  return (
    <SafeAreaView style={styles.container} edges={["bottom", "left", "right"]}>
      <Text style={styles.storeLabel}>{editingClientUuid ? "Editing order for" : "Ordering for"}: {storeName}</Text>
      <TextInput
        style={styles.search}
        placeholder="Search product name, code, generic…"
        value={search}
        onChangeText={setSearch}
      />
      <FlatList
        data={products}
        keyExtractor={(item) => item.id}
        contentContainerStyle={{ paddingBottom: 100 }}
        renderItem={({ item }) => {
          const cartLine = lines[item.id];
          const qty = cartLine?.quantity ?? 0;
          const bonusQty = cartLine?.bonusQty ?? 0;
          return (
            <View style={styles.row}>
              <ProductImage productId={item.id} remoteUrl={item.imageUrl} productName={item.name} />
              <View style={styles.info}>
                <Text style={styles.name}>{item.name}</Text>
                <Text style={styles.meta}>
                  {[item.packing, item.company].filter(Boolean).join(" · ")}
                </Text>
                {item.netRate != null ? <Text style={styles.rate}>Rs. {item.netRate.toFixed(2)}</Text> : null}
                {item.bonus && item.bonusBuyQty && item.bonusFreeQty ? (
                  <Text style={styles.bonus}>
                    Bonus: {item.bonusBuyQty}+{item.bonusFreeQty}
                    {qty > 0 ? ` · Free: ${bonusQty} · Total: ${qty + bonusQty}` : ""}
                  </Text>
                ) : null}
              </View>
              <View style={styles.qtyControls}>
                <Pressable style={styles.qtyButton} onPress={() => setQuantity(item, Math.max(0, qty - 1))}>
                  <Text style={styles.qtyButtonText}>−</Text>
                </Pressable>
                <TextInput
                  style={styles.qtyInput}
                  keyboardType="numeric"
                  value={qty ? String(qty) : ""}
                  placeholder="0"
                  onChangeText={(v) => setQuantity(item, Math.max(0, parseInt(v || "0", 10) || 0))}
                />
                <Pressable style={styles.qtyButton} onPress={() => setQuantity(item, qty + 1)}>
                  <Text style={styles.qtyButtonText}>+</Text>
                </Pressable>
              </View>
            </View>
          );
        }}
      />

      <View style={styles.footer}>
        <View>
          <Text style={styles.footerCount}>{totalItems} product{totalItems === 1 ? "" : "s"} selected</Text>
          <Text style={styles.footerTotal}>Total: Rs. {totalValue.toFixed(2)}</Text>
        </View>
        <Pressable
          style={[styles.reviewButton, totalItems === 0 && styles.reviewButtonDisabled]}
          disabled={totalItems === 0}
          onPress={() => navigation.navigate("OrderReview", { editingClientUuid })}
        >
          <Text style={styles.reviewButtonText}>Review Order</Text>
        </Pressable>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#fff" },
  storeLabel: { fontSize: 13, color: "#555", paddingHorizontal: 16, paddingTop: 12, fontWeight: "600" },
  search: { borderWidth: 1, borderColor: "#ccc", borderRadius: 8, marginHorizontal: 16, marginVertical: 10, paddingHorizontal: 12, paddingVertical: 8 },
  row: { flexDirection: "row", alignItems: "center", paddingHorizontal: 16, paddingVertical: 10, borderBottomWidth: 1, borderBottomColor: "#f0f0f0" },
  info: { flex: 1, marginLeft: 12 },
  name: { fontSize: 15, fontWeight: "600" },
  meta: { fontSize: 12, color: "#777", marginTop: 2 },
  rate: { fontSize: 12, color: "#1a3d7c", marginTop: 2, fontWeight: "600" },
  bonus: { fontSize: 11, color: "#b8860b", marginTop: 2, fontWeight: "600" },
  qtyControls: { flexDirection: "row", alignItems: "center" },
  qtyButton: { width: 30, height: 30, borderRadius: 6, backgroundColor: "#eef1f6", alignItems: "center", justifyContent: "center" },
  qtyButtonText: { fontSize: 18, fontWeight: "700", color: "#1a3d7c" },
  qtyInput: { width: 42, textAlign: "center", fontSize: 15, marginHorizontal: 4, borderWidth: 1, borderColor: "#ddd", borderRadius: 6, paddingVertical: 4 },
  footer: {
    position: "absolute", bottom: 0, left: 0, right: 0,
    flexDirection: "row", justifyContent: "space-between", alignItems: "center",
    backgroundColor: "#fff", borderTopWidth: 1, borderTopColor: "#eee", padding: 16,
  },
  footerCount: { fontSize: 12, color: "#777" },
  footerTotal: { fontSize: 18, fontWeight: "700", color: "#1a3d7c" },
  reviewButton: { backgroundColor: "#1a3d7c", borderRadius: 10, paddingVertical: 12, paddingHorizontal: 20 },
  reviewButtonDisabled: { backgroundColor: "#aab4c4" },
  reviewButtonText: { color: "#fff", fontWeight: "600" },
});
