"use client";

import { useEffect, useMemo, useState, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import Axios from "@/lib/Axios";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useToast } from "@/components/ui/use-toast";
import { Plus, ArrowLeft } from "lucide-react";
import { CreateOrderDto, OrderT, ProductT } from "@/types/orders";

type PostageServiceChargeT = {
  id: number;
  name: string;
  description?: string;
  amount: number;
};

interface OrderItemForm {
  productId: number;
  count: number;
  price?: number;
  isFreeProduct?: boolean;
}

const CreateOrderPageContent = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const customerIdParam = searchParams.get("customerId");
  const orderIdParam = searchParams.get("orderId");
  const firstName = searchParams.get("firstName") || "";
  const lastName = searchParams.get("lastName") || "";

  const customerId = customerIdParam ? Number(customerIdParam) : NaN;
  const orderId = orderIdParam ? Number(orderIdParam) : null;
  const isEditMode = !!orderId;

  const [orderItems, setOrderItems] = useState<OrderItemForm[]>([
    { productId: 0, count: 1 },
  ]);
  const [selectedPostageId, setSelectedPostageId] = useState<number | undefined>(
    undefined,
  );
  const [deductionNotes, setDeductionNotes] = useState<Record<number, string>>({});
  const [orderTotalOverride, setOrderTotalOverride] = useState<number | null>(null);
  const [orderTotalNote, setOrderTotalNote] = useState<string>("");
  const [orderNote, setOrderNote] = useState<string>("");
  const [isDataLoaded, setIsDataLoaded] = useState(false);

  // Fetch products
  const {
    data: productsData,
    isLoading: productsLoading,
  } = useQuery({
    queryKey: ["products-list"],
    queryFn: async () => {
      const res = await Axios.get<{ data: ProductT[]; total: number }>(
        "/products/",
        {
          params: {
            isActive: true,
            limit: 1000,
          },
        },
      );
      return res.data.data;
    },
  });

  // Fetch postage/service charges
  const {
    data: postageChargesData,
    isLoading: postageLoading,
  } = useQuery({
    queryKey: ["postage-service-charges"],
    queryFn: async () => {
      const res = await Axios.get<{ data: PostageServiceChargeT[] }>(
        "/postage-service-charges",
      );
      return res.data.data;
    },
  });

  const products = productsData || [];
  const postageCharges = postageChargesData || [];

  // Fetch existing order data when in edit mode
  const {
    data: existingOrderData,
    isLoading: orderLoading,
  } = useQuery({
    queryKey: ["order", orderId],
    queryFn: async () => {
      if (!orderId) return null;
      const res = await Axios.get<{ data: OrderT }>(`/orders/${orderId}`);
      return res.data.data;
    },
    enabled: !!orderId,
  });

  // Pre-populate form when order data is loaded
  useEffect(() => {
    if (isEditMode && existingOrderData && existingOrderData.orderItems && existingOrderData.orderItems.length > 0) {
      console.log('🔵 [EDIT MODE] Loading order data:', existingOrderData);
      console.log('🔵 [EDIT MODE] Order items from API:', existingOrderData.orderItems);
      
      // Map order items with proper type conversion
      const items = existingOrderData.orderItems.map((item, idx) => {
        // Handle count - could be number, string, or null from API
        let count = 1;
        const rawCount = item.count;
        console.log(`  [Item ${idx}] Raw count:`, rawCount, 'Type:', typeof rawCount);
        
        if (rawCount !== null && rawCount !== undefined) {
          const parsedCount = typeof rawCount === 'string' ? parseInt(rawCount, 10) : Number(rawCount);
          console.log(`  [Item ${idx}] Parsed count:`, parsedCount);
          if (!isNaN(parsedCount) && parsedCount > 0) {
            count = parsedCount;
          }
        }
        
        // Handle productId - could be number or string from API
        let productId = 0;
        const rawProductId = item.productId;
        console.log(`  [Item ${idx}] Raw productId:`, rawProductId, 'Type:', typeof rawProductId);
        
        if (rawProductId !== null && rawProductId !== undefined) {
          const parsedProductId = typeof rawProductId === 'string' ? parseInt(rawProductId, 10) : Number(rawProductId);
          console.log(`  [Item ${idx}] Parsed productId:`, parsedProductId);
          if (!isNaN(parsedProductId) && parsedProductId > 0) {
            productId = parsedProductId;
          }
        }
        
        // Handle price (amountPerTub) - could be number, string, or null from API
        let price: number | undefined = undefined;
        const rawPrice = item.amountPerTub;
        if (rawPrice !== null && rawPrice !== undefined) {
          const parsedPrice = typeof rawPrice === 'string' ? parseFloat(rawPrice) : Number(rawPrice);
          if (!isNaN(parsedPrice) && parsedPrice >= 0) {
            price = parsedPrice;
          }
        }
        
        // Identify free products (price = 0)
        const isFreeProduct = price === 0 || price === undefined || price === null;
        
        console.log(`  [Item ${idx}] Final: productId=${productId}, count=${count}, price=${price}, isFreeProduct=${isFreeProduct}`);
        
        return {
          productId: productId,
          count: count,
          price: price,
          isFreeProduct: isFreeProduct,
        };
      });
      
      console.log('🔵 [EDIT MODE] Mapped items to set:', items);
      console.log('🔵 [EDIT MODE] Current orderItems state before update:', orderItems);
      
      // Always update orderItems
      setOrderItems(items);
      console.log('🔵 [EDIT MODE] Called setOrderItems with:', items);

      // Set postage from first item (postage is per order, not per product)
      const firstItem = existingOrderData.orderItems[0];
      if (firstItem?.postageServiceChargeId) {
        const postageId = typeof firstItem.postageServiceChargeId === 'string' 
          ? parseInt(firstItem.postageServiceChargeId, 10) 
          : Number(firstItem.postageServiceChargeId);
        if (!isNaN(postageId) && postageId > 0) {
          console.log('🔵 [EDIT MODE] Setting postage ID:', postageId);
          setSelectedPostageId(postageId);
        }
      }

      // Load order note from first item's deductionNote (if it's not a specific deduction note)
      if (firstItem?.deductionNote) {
        // Check if this is a general note (not from order total override or product decrease)
        // For now, we'll load it as the order note
        setOrderNote(firstItem.deductionNote || "");
      }

      // Calculate and set the order total from existing order data
      const existingTotal = existingOrderData.orderItems.reduce((sum, item) => {
        if (item.totalAmount) {
          const itemTotal = typeof item.totalAmount === 'string' 
            ? parseFloat(item.totalAmount) 
            : Number(item.totalAmount);
          if (!isNaN(itemTotal)) {
            return sum + itemTotal;
          }
        }
        return sum;
      }, 0);
      
      console.log('🔵 [EDIT MODE] Calculated existing total:', existingTotal);
      
      // Set the order total override to show the actual order total
      if (existingTotal > 0 && !isNaN(existingTotal)) {
        console.log('🔵 [EDIT MODE] Setting orderTotalOverride to:', existingTotal);
        setOrderTotalOverride(existingTotal);
      } else {
        console.log('🔵 [EDIT MODE] No valid total, setting to null');
        setOrderTotalOverride(null);
      }
      setOrderTotalNote("");
    } else if (!isEditMode && !orderLoading) {
      // Reset to default for new orders (only when not loading)
      setOrderItems([{ productId: 0, count: 1 }]);
      setSelectedPostageId(undefined);
      setOrderTotalOverride(null);
      setOrderTotalNote("");
      setOrderNote("");
    }
  }, [existingOrderData, isEditMode, orderLoading]);

  // Debug: Log when orderItems state changes
  useEffect(() => {
    if (isEditMode) {
      console.log('🟢 [STATE CHANGE] orderItems updated:', orderItems);
      console.log('🟢 [STATE CHANGE] orderTotalOverride:', orderTotalOverride);
      console.log('🟢 [STATE CHANGE] selectedPostageId:', selectedPostageId);
    }
  }, [orderItems, orderTotalOverride, selectedPostageId, isEditMode]);

  const createOrderMutation = useMutation({
    mutationFn: async (data: CreateOrderDto) => {
      if (isEditMode && orderId) {
        // Update existing order - send UpdateOrderDto format
        const updatePayload = {
          orderItems: data.orderItems.map((item) => ({
            productId: Number(item.productId),
            count: Number(item.count),
            amountPerTub: Number(item.amountPerTub) || 0,
            totalAmount: Number(item.totalAmount) || 0,
            postageServiceChargeId: item.postageServiceChargeId ? Number(item.postageServiceChargeId) : undefined,
            deductionNote: item.deductionNote || undefined, // Include deduction note
          })),
        };
        const res = await Axios.patch<{ data: OrderT; message: string }>(
          `/orders/${orderId}`,
          updatePayload,
        );
        return res.data;
      } else {
        // Create new order
        const res = await Axios.post<{ data: OrderT; message: string }>(
          "/orders/",
          data,
        );
        return res.data;
      }
    },
    onSuccess: () => {
      toast({
        title: "Success",
        description: isEditMode
          ? "Order updated successfully"
          : "Order created successfully",
      });
      queryClient.invalidateQueries({ queryKey: ["customer-orders"] });
      queryClient.invalidateQueries({ queryKey: ["order", orderId] });
      if (!isNaN(customerId)) {
        router.push(
          `/customer/customer-manage/${customerId}?firstName=${encodeURIComponent(
            firstName,
          )}&lastName=${encodeURIComponent(lastName)}`,
        );
      } else {
        router.push("/customer");
      }
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description:
          error?.response?.data?.message ||
          (isEditMode ? "Failed to update order" : "Failed to create order"),
        variant: "destructive",
      });
    },
  });

  const handleAddProductRow = () => {
    setOrderItems((prev) => [...prev, { productId: 0, count: 1 }]);
  };

  const handleAddFreeProduct = () => {
    const firstItem = orderItems[0];
    const firstProductId = firstItem?.productId;
    if (firstProductId && firstProductId > 0) {
      setOrderItems((prev) => [...prev, { 
        productId: firstProductId, 
        count: 1, 
        price: 0, // Explicitly set price to 0 for free products
        isFreeProduct: true 
      }]);
    }
  };

  const handleRemoveProductRow = (index: number) => {
    setOrderItems((prev) =>
      prev.length > 1 ? prev.filter((_, i) => i !== index) : prev,
    );
  };

  const handleProductChange = (index: number, productId: number) => {
    setOrderItems((prev) => {
      const updated = [...prev];
      updated[index].productId = productId;
      // Initialize price from product if not already set, but allow user to override
      if (!updated[index].price && productId > 0) {
        const product = products.find((p) => p.id === productId);
        updated[index].price = product?.amount ? Number(product.amount) : undefined;
      }
      return updated;
    });
  };

  const handlePriceChange = (index: number, price: number | undefined) => {
    setOrderItems((prev) => {
      const updated = [...prev];
      updated[index].price = price !== undefined && !isNaN(price) && price >= 0 ? price : undefined;
      return updated;
    });
  };

  const handleCountChange = (index: number, count: number) => {
    setOrderItems((prev) => {
      const updated = [...prev];
      updated[index].count = Math.max(1, isNaN(count) ? 1 : count);
      return updated;
    });
  };

  const getProductAmount = (productId: number) => {
    const product = products.find((p) => p.id === productId);
    return product?.amount ? Number(product.amount) : 0;
  };

  // Check if amount is decreasing for a product (only in edit mode)
  // This compares the total amount including postage for the first item
  const isAmountDecreasing = (productId: number, index: number, newLineTotal: number): boolean => {
    if (!isEditMode || !existingOrderData) return false;
    const existingItem = existingOrderData.orderItems.find(
      (oi) => oi.productId === productId,
    );
    if (!existingItem || !existingItem.totalAmount) return false;
    const oldAmount = Number(existingItem.totalAmount);
    // For the first item, add postage to the new amount for comparison
    const isFirst = index === 0;
    const newTotalWithPostage = isFirst 
      ? newLineTotal + (postageAmount || 0)
      : newLineTotal;
    return newTotalWithPostage < oldAmount;
  };

  // Get old amount for a product (for display)
  const getOldAmount = (productId: number): number | null => {
    if (!isEditMode || !existingOrderData) return null;
    const existingItem = existingOrderData.orderItems.find(
      (oi) => oi.productId === productId,
    );
    return existingItem?.totalAmount ? Number(existingItem.totalAmount) : null;
  };

  const postageAmount = useMemo(() => {
    if (!selectedPostageId) return 0;
    const charge = postageCharges.find((p) => p.id === selectedPostageId);
    return charge?.amount ? Number(charge.amount) : 0;
  }, [selectedPostageId, postageCharges]);

  const totals = useMemo(() => {
    // If in edit mode and we have existing order data, use the actual totals from the database
    if (isEditMode && existingOrderData && existingOrderData.orderItems && existingOrderData.orderItems.length > 0) {
      // Calculate products total (sum of all items, but postage is only on first non-free item)
      // Exclude free products (price = 0) from totals
      let productsTotal = 0;
      let existingPostage = 0;
      
      // Find first non-free product for postage
      const firstNonFreeItem = existingOrderData.orderItems.find(
        (item) => item.amountPerTub && Number(item.amountPerTub) > 0
      );
      
      existingOrderData.orderItems.forEach((item, index) => {
        const amountPerTub = item.amountPerTub ? Number(item.amountPerTub) : 0;
        // Skip free products (price = 0)
        if (amountPerTub === 0) return;
        
        const itemTotal = item.totalAmount ? Number(item.totalAmount) : 0;
        const isFirstNonFree = firstNonFreeItem && item.id === firstNonFreeItem.id;
        
        if (isFirstNonFree && item.postageServiceCharge) {
          // First non-free item includes postage, so subtract it to get product total
          const postage = Number(item.postageServiceCharge.amount) || 0;
          existingPostage = postage;
          productsTotal += itemTotal - postage;
        } else {
          productsTotal += itemTotal;
        }
      });
      
      // Total is sum of all order items' totalAmount (excluding free products) + postage
      const existingTotal = productsTotal + existingPostage;
      
      // Use orderTotalOverride if set, otherwise use existingTotal
      const finalOrderTotal = orderTotalOverride !== null ? orderTotalOverride : existingTotal;
      
      return {
        productsTotal: productsTotal || 0,
        postageAmount: existingPostage || 0,
        orderTotal: finalOrderTotal || 0,
        calculatedTotal: existingTotal || 0,
      };
    }
    
    // For new orders, calculate from form state (exclude free products)
    let productsTotal = 0;
    orderItems.forEach((item) => {
      if (!item.productId || !item.count) return;
      
      // Exclude free products (explicitly marked as free)
      if (item.isFreeProduct === true) return;
      
      // Only include products with a valid price > 0
      const amountPerTub = item.price !== undefined && item.price !== null ? item.price : 0;
      if (amountPerTub > 0) {
        productsTotal += amountPerTub * item.count;
      }
    });
    const calculatedTotal = productsTotal + (postageAmount || 0);
    return {
      productsTotal: productsTotal || 0,
      postageAmount: postageAmount || 0,
      orderTotal: orderTotalOverride !== null ? orderTotalOverride : (calculatedTotal || 0),
      calculatedTotal: calculatedTotal || 0,
    };
  }, [orderItems, products, postageAmount, orderTotalOverride, isEditMode, existingOrderData]);

  const handleSubmit = () => {
    if (isNaN(customerId)) {
      toast({
        title: "Validation Error",
        description: "Customer is not specified.",
        variant: "destructive",
      });
      return;
    }

    if (!selectedPostageId) {
      toast({
        title: "Validation Error",
        description: "Please select a Postage/Service charge for this order.",
        variant: "destructive",
      });
      return;
    }

    // Validate items: free products can have price 0, regular products need price > 0
    const invalidItems = orderItems.filter((item) => {
      if (!item.productId || item.count < 1) return true;
      
      // Free products are allowed to have price 0 or undefined (will be set to 0)
      if (item.isFreeProduct === true) return false;
      
      // Regular products must have a valid price > 0
      if (item.price === undefined || item.price === null || item.price <= 0) return true;
      
      return false;
    });
    
    if (invalidItems.length > 0) {
      toast({
        title: "Validation Error",
        description:
          "Please select a product, enter a valid quantity, and enter a valid price (greater than 0) for all regular products. Free products are allowed to have price 0.",
        variant: "destructive",
      });
      return;
    }

    // Calculate the base total (products + postage)
    const calculatedProductsTotal = totals.productsTotal;
    const calculatedTotal = totals.productsTotal + totals.postageAmount;
    
    // Check if order total was manually overridden
    if (orderTotalOverride !== null && orderTotalOverride !== calculatedTotal) {
      if (!orderTotalNote || orderTotalNote.trim() === "") {
        toast({
          title: "Validation Error",
          description: "Please provide a reason for changing the order total amount.",
          variant: "destructive",
        });
        return;
      }
    }

    // Build payload: multiple products, single postage/service (applied once)
    // If order total is overridden, distribute the difference to the first item
    const totalDifference = orderTotalOverride !== null 
      ? orderTotalOverride - calculatedTotal 
      : 0;

    // Find the first non-free product for postage
    const firstNonFreeProductIndex = orderItems.findIndex((item) => !item.isFreeProduct);
    const firstNonFreeIndex = firstNonFreeProductIndex >= 0 ? firstNonFreeProductIndex : 0;

    const mappedItems = orderItems.map((item, index) => {
      // Determine if this is a free product (explicitly marked, not just price = 0)
      const isFreeProduct = item.isFreeProduct === true;
      const amountPerTub = isFreeProduct ? 0 : (item.price !== undefined && item.price !== null ? item.price : 0);
      const baseTotal = amountPerTub * item.count;

      // Free products should always have totalAmount = 0
      if (isFreeProduct) {
        return {
          productId: item.productId,
          count: item.count,
          amountPerTub: 0,
          totalAmount: 0,
          postageServiceChargeId: undefined,
          deductionNote: undefined,
        };
      }

      // Apply postage only to the first non-free product
      const isFirstNonFree = index === firstNonFreeIndex;
      let totalAmount = isFirstNonFree
        ? baseTotal + (postageAmount || 0)
        : baseTotal;

      // If order total is overridden, add the difference to the first non-free item
      if (isFirstNonFree && totalDifference !== 0) {
        totalAmount += totalDifference;
      }

      // Check if order total was overridden first - if so, use that note for the first non-free item
      let deductionNote: string | undefined = undefined;
      if (isFirstNonFree && orderTotalOverride !== null && orderTotalOverride !== calculatedTotal) {
        // Order total was overridden, use the order-level note
        deductionNote = orderTotalNote;
      }
      
      // If it's the first non-free item and no other note is set, use the general order note
      if (isFirstNonFree && !deductionNote && orderNote && orderNote.trim() !== "") {
        deductionNote = orderNote.trim();
      }

      return {
        productId: item.productId,
        count: item.count,
        amountPerTub: Number(amountPerTub) || 0,
        totalAmount: Number(totalAmount) || 0,
        postageServiceChargeId:
          isFirstNonFree && selectedPostageId ? selectedPostageId : undefined,
        deductionNote: deductionNote,
      };
    }).filter((item) => item !== null) as any[];

    // If any items were filtered out, don't submit
    if (mappedItems.length !== orderItems.length) {
      return;
    }

    const payload: CreateOrderDto = {
      customerId,
      orderItems: mappedItems,
    };

    createOrderMutation.mutate(payload);
  };

  useEffect(() => {
    if (!customerIdParam && !orderIdParam) {
      toast({
        title: "Missing Customer",
        description: "Customer Id is required to create an order.",
        variant: "destructive",
      });
      router.push("/customer");
    }
  }, [customerIdParam, orderIdParam, router, toast]);

  return (
    <div className="py-8 max-w-5xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <Button
            variant="outline"
            size="icon"
            onClick={() => router.back()}
            className="mr-1"
          >
            <ArrowLeft className="w-4 h-4" />
          </Button>
          <div>
            <h1 className="text-2xl font-semibold text-gray-800">
              {isEditMode ? "Edit Order" : "Create New Order"}
            </h1>
            {firstName || lastName ? (
              <p className="text-sm text-gray-500">
                For customer:{" "}
                <span className="font-medium">
                  {firstName} {lastName}
                </span>
              </p>
            ) : null}
          </div>
        </div>
      </div>

      <div className="bg-white border rounded-md p-6 space-y-6">
        <div className="space-y-2">
          <h2 className="text-lg font-semibold">Products</h2>
          <p className="text-xs text-gray-500">
            Select one or more products. Postage/Service charge will be applied
            once per order.
          </p>
        </div>

        <div className="space-y-3">
          {orderItems.map((item, index) => {
            // Determine if this is a free product (only if explicitly marked)
            const isFreeProduct = item.isFreeProduct === true;
            const amountPerTub = isFreeProduct ? 0 : (item.price !== undefined && item.price !== null ? item.price : 0);
            const lineTotal = amountPerTub * (item.count || 0);

            return (
              <div
                key={index}
                className="flex flex-col gap-2 border rounded-md p-3"
              >
                <div className="flex flex-col md:flex-row gap-3 items-end">
                  <div className="flex-1">
                    <label className="text-sm font-medium mb-1 block">
                      {isFreeProduct ? "Free Product" : "Product"}
                    </label>
                    <Select
                      key={`prod-${index}-${item.productId}`}
                      value={item.productId && item.productId > 0 ? String(item.productId) : ""}
                      onValueChange={(value) =>
                        handleProductChange(index, parseInt(value))
                      }
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select a product" />
                      </SelectTrigger>
                      <SelectContent>
                        {products.map((product) => {
                          // For free products, allow selecting the same product as the first row
                          // For regular products, prevent duplicates
                          const isSelectedElsewhere = isFreeProduct
                            ? orderItems.some(
                                (otherItem, otherIndex) => {
                                  const otherPrice = otherItem.price || 0;
                                  const otherIsFree = otherPrice === 0 || otherItem.isFreeProduct;
                                  return otherIndex !== index &&
                                    otherItem.productId === product.id &&
                                    otherIsFree; // Only block if another free product has it
                                }
                              )
                            : orderItems.some(
                                (otherItem, otherIndex) =>
                                  otherIndex !== index &&
                                  otherItem.productId === product.id,
                              );
                          return (
                            <SelectItem
                              key={product.id}
                              value={product.id.toString()}
                              disabled={isSelectedElsewhere}
                              className={
                                isSelectedElsewhere
                                  ? "opacity-50 cursor-not-allowed"
                                  : ""
                              }
                            >
                              {product.name}
                            </SelectItem>
                          );
                        })}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="w-32">
                    <label className="text-sm font-medium mb-1 block">
                      Quantity
                    </label>
                    <input
                      type="number"
                      min={0}
                      value={item.count ? String(item.count) : "0"}
                      onChange={(e) => {
                        const val = e.target.value;
                        handleCountChange(index, val ? parseInt(val) || 0 : 0);
                      }}
                      className="flex h-9 w-32 rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                    />
                  </div>
                  <div className="w-32">
                    <label className="text-sm font-medium mb-1 block">
                      Price
                    </label>
                    <input
                      type="number"
                      step="0.01"
                      min="0"
                      value={item.price !== undefined && item.price !== null ? String(item.price) : ""}
                      onChange={(e) => {
                        const val = e.target.value;
                        handlePriceChange(index, val === "" ? undefined : parseFloat(val));
                      }}
                      placeholder="0.00"
                      className="flex h-9 w-32 rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                    />
                  </div>
                  {orderItems.length > 1 && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleRemoveProductRow(index)}
                    >
                      Remove
                    </Button>
                  )}
                </div>
                <div className="flex flex-wrap gap-4 text-xs text-muted-foreground mt-1">
                  <span>
                    Amount per tub:{" "}
                    <span className="font-semibold">
                      £{amountPerTub.toFixed(2)}
                    </span>
                  </span>
                  <span>
                    Line total:{" "}
                    <span className="font-semibold text-primary">
                      £{lineTotal.toFixed(2)}
                    </span>
                  </span>
                  {isEditMode && existingOrderData && (() => {
                    const oldAmount = getOldAmount(item.productId);
                    if (oldAmount !== null) {
                      const isFirst = index === 0;
                      const totalWithPostage = lineTotal + (isFirst ? (postageAmount || 0) : 0);
                      const isDecreasing = totalWithPostage < oldAmount;
                      if (isDecreasing) {
                        return (
                          <span className="text-red-600">
                            (Old: £{oldAmount.toFixed(2)})
                          </span>
                        );
                      }
                    }
                    return null;
                  })()}
                </div>
              </div>
            );
          })}
        </div>

        <div className="flex justify-between items-center gap-2">
          <Button
            type="button"
            variant="outline"
            onClick={handleAddFreeProduct}
            className="gap-2"
            disabled={!orderItems[0]?.productId || orderItems[0].productId === 0}
          >
            <Plus className="w-4 h-4" />
            Add a free product
          </Button>
          <Button
            type="button"
            variant="outline"
            onClick={handleAddProductRow}
            className="gap-2"
          >
            <Plus className="w-4 h-4" />
            Add Another Product
          </Button>
        </div>

        <div className="pt-4 border-t space-y-4">
          <div className="max-w-sm">
            <label className="text-sm font-medium mb-1 block">
              Postage / Service * (applied once per order)
            </label>
            <Select
              value={selectedPostageId ? String(selectedPostageId) : ""}
              onValueChange={(value) =>
                setSelectedPostageId(value ? parseInt(value) : undefined)
              }
            >
              <SelectTrigger>
                <SelectValue placeholder="Select postage/service" />
              </SelectTrigger>
              <SelectContent>
                {postageCharges.map((charge) => (
                  <SelectItem key={charge.id} value={charge.id.toString()}>
                    {charge.name} - £{Number(charge.amount).toFixed(2)}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="text-sm text-gray-700 space-y-3">
            <p>
              Products total:{" "}
              <span className="font-semibold">
                £{totals.productsTotal.toFixed(2)}
              </span>
            </p>
            <p>
              Postage/Service:{" "}
              <span className="font-semibold">
                £{totals.postageAmount.toFixed(2)}
              </span>
            </p>
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <label className="font-semibold text-primary">
                  Order total:
                </label>
                <input
                  type="number"
                  step="0.01"
                  min="0"
                  value={
                    orderTotalOverride !== null && orderTotalOverride !== undefined && orderTotalOverride > 0
                      ? String(orderTotalOverride)
                      : totals.calculatedTotal > 0
                        ? String(totals.calculatedTotal)
                        : ""
                  }
                  onChange={(e) => {
                    const calculatedTotal = totals.calculatedTotal;
                    const inputValue = e.target.value;
                    
                    // Allow empty input while typing
                    if (inputValue === "" || inputValue === ".") {
                      setOrderTotalOverride(null);
                      setOrderTotalNote("");
                      return;
                    }
                    
                    const value = parseFloat(inputValue);
                    if (!isNaN(value) && value >= 0) {
                      // If value is different from calculated (with small tolerance for floating point), set override
                      if (Math.abs(value - calculatedTotal) > 0.01) {
                        setOrderTotalOverride(value);
                        // Clear note if value changed significantly, to require new note
                        const previousValue = orderTotalOverride !== null ? orderTotalOverride : calculatedTotal;
                        if (Math.abs(value - previousValue) > 0.01) {
                          setOrderTotalNote("");
                        }
                      } else {
                        // If reverting to calculated value, clear override and note
                        setOrderTotalOverride(null);
                        setOrderTotalNote("");
                      }
                    }
                  }}
                  onBlur={(e) => {
                    // On blur, if empty or invalid, reset to calculated total
                    const value = e.target.value;
                    if (value === "" || isNaN(parseFloat(value)) || parseFloat(value) < 0) {
                      setOrderTotalOverride(null);
                      setOrderTotalNote("");
                    }
                  }}
                  className="flex h-9 w-32 rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 font-semibold text-primary"
                />
                {orderTotalOverride !== null && orderTotalOverride !== totals.calculatedTotal && (
                  <span className="text-xs text-muted-foreground">
                    (Calculated: £{totals.calculatedTotal.toFixed(2)})
                  </span>
                )}
              </div>
              {orderTotalOverride !== null && orderTotalOverride !== totals.calculatedTotal && (
                <div>
                  <label className="text-sm font-medium mb-1 block text-red-600">
                    Reason for Amount Change <span className="text-red-500">*</span>
                  </label>
                  <Textarea
                    placeholder="Please provide a reason for changing the order total amount..."
                    value={orderTotalNote}
                    onChange={(e) => setOrderTotalNote(e.target.value)}
                    className="min-h-[80px]"
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    A note is required when manually changing the order total amount.
                  </p>
                </div>
              )}
              <div className="mt-4">
                <label className="text-sm font-medium mb-1 block">
                  Note
                </label>
                <Textarea
                  placeholder="Add a note for this order..."
                  value={orderNote}
                  onChange={(e) => setOrderNote(e.target.value)}
                  className="min-h-[80px]"
                />
                <p className="text-xs text-muted-foreground mt-1">
                  This note will be displayed in the &quot;Reason for discount&quot; column.
                </p>
              </div>
            </div>
          </div>
        </div>

        <div className="flex justify-end gap-3 pt-2">
          <Button
            type="button"
            variant="outline"
            onClick={() => router.back()}
          >
            Cancel
          </Button>
          <Button
            type="button"
            onClick={handleSubmit}
            disabled={createOrderMutation.isPending || orderLoading}
          >
            {createOrderMutation.isPending
              ? isEditMode
                ? "Updating..."
                : "Creating..."
              : isEditMode
                ? "Update Order"
                : "Create Order"}
          </Button>
        </div>
      </div>
    </div>
  );
};

const CreateOrderPage = () => {
  return (
    <Suspense fallback={
      <div className="py-8 max-w-5xl mx-auto">
        <div className="flex items-center justify-center h-64">
          <div className="text-center">
            <p className="text-gray-500">Loading...</p>
          </div>
        </div>
      </div>
    }>
      <CreateOrderPageContent />
    </Suspense>
  );
};

export default CreateOrderPage;


