"use client";
import React, { useEffect, useRef, useState } from "react";

import noteListHandler from "./noteListHandler";
import SendNote from "./sendNote";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useRouter, useSearchParams } from "next/navigation";
import {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
// import style from "@/components/tanstack-table/style.module.scss";
import style from "./style.module.scss";
import {
  ArchiveRestore,
  CalendarCheckIcon,
  CalendarHeart,
  CalendarIcon,
  ClockIcon,
  Pencil,
  Plus,
  Trash2,
  X,
  Check,
} from "lucide-react";

import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import Axios from "@/lib/Axios";
import { PaginationStructT } from "@/types/global";
import { NotesT } from "@/types/notes";
import { OrderT, ProductT, CreateOrderDto, CreateProductDto, PostageServiceChargeT } from "@/types/orders";
import { format } from "date-fns";
import { getRandomDarkColor } from "@/lib/getRandomDarkColor";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useToast } from "@/components/ui/use-toast";
import useUserStore from "@/store/useUserStore";

// Helper function to get user name
const getUserName = (user: any) => {
  if (!user) return "N/A";
  if (user.name) return user.name;
  if (user.firstName || user.lastName) {
    return `${user.firstName || ""} ${user.lastName || ""}`.trim() || "N/A";
  }
  return "N/A";
};

// Helper function to get user initial
const getUserInitial = (user: any) => {
  const name = getUserName(user);
  return name !== "N/A" ? name.charAt(0).toUpperCase() : "N";
};

const OrdersAndNotes = ({ id }: { id: number }) => {
  const { data, error, isLoading, isSuccess, refetch } = useQuery({
    queryKey: ["list-customer-comments1"],
    queryFn: fetchData,
  });

  // const { insertNode } = useCommentHandler();

  async function fetchData() {
    return Axios.get<PaginationStructT<NotesT[]>>("/customer/notes/", {
      params: {
        customer: id,
        ordering: "-created_at",
      },
    }).then((res) => {
      // for (let i of res.data.data) {
      //   insertNode(i, noteCommentStruct);
      // }

      return res.data.data;
    });
  }

  // Fetch orders for the customer
  const {
    data: ordersData,
    isLoading: ordersLoading,
    refetch: refetchOrders,
  } = useQuery({
    queryKey: ["customer-orders", id],
    queryFn: async () => {
      const res = await Axios.get<{ data: OrderT[]; total: number }>("/orders/", {
        params: {
          customerId: id,
          limit: 100, // Get all orders for this customer
        },
      });
      return res.data.data;
    },
  });

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

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

  // const { ReturnNote, refetch } = noteListHandler(id);
  const searchParams = useSearchParams();
  const router = useRouter();
  const firstName = searchParams.get("firstName");
  const lastName = searchParams.get("lastName");
  const userData = useUserStore((state) => state.data);

  return (
    <div className="space-y-3 pb-8">
      <div className="right-card bg-white border rounded-sm pt-5 px-8 pb-5">
        <div className="flex justify-between items-center mb-4">
          <p className="text-xl font-semibold">Order List</p>
          <div className="flex gap-2">
            <Button
              size="sm"
              className="gap-2"
              onClick={() => {
                const params = new URLSearchParams();
                params.set("customerId", String(id));
                if (firstName) params.set("firstName", firstName);
                if (lastName) params.set("lastName", lastName);
                router.push(`/customer/create-order?${params.toString()}`);
              }}
            >
              <Plus className="w-4 h-4" />
              Add Order
            </Button>
          </div>
        </div>

        <div className="rounded-md border overflow-hidden">
          <div className="max-h-[20rem] overflow-y-auto">
            <Table>
              <TableHeader className="sticky top-0 bg-white z-10 border-b">
                <TableRow className="bg-blue-50 hover:bg-blue-50">
                  <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3">Date & Time</TableHead>
                  <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3">Created By</TableHead>
                  <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3">Product</TableHead>
                  <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3 text-center">Quantity</TableHead>
                  <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3 text-right">Price</TableHead>
                  <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3 text-right">Subtotal</TableHead>
                  <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3 text-right">Total</TableHead>
                  <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3">Reason for discount</TableHead>
                  <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3 text-center">Edit</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {ordersLoading ? (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center py-8">
                      <div className="flex items-center justify-center">
                        <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
                        <span className="ml-2">Loading...</span>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : ordersData && ordersData.length > 0 ? (
                  ordersData.map((order) => (
                    <EditableOrderRow
                      key={order.id}
                      order={order}
                      products={productsData || []}
                      refetchOrders={refetchOrders}
                      customerId={id}
                      firstName={firstName || undefined}
                      lastName={lastName || undefined}
                    />
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={9} className="text-center py-12">
                      <div className="flex flex-col items-center justify-center text-muted-foreground">
                        <CalendarIcon className="w-12 h-12 mb-2 opacity-50" />
                        <p className="text-base font-medium">No Orders Found</p>
                        <p className="text-sm mt-1">
                          Create your first order to get started
                        </p>
                      </div>
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>
        </div>
      </div>

      <div className="right-card bg-yellowish/20 rounded-sm py-5 space-y-10 px-8">
        <p className=" text-xl font-semibold">Notes</p>
        <div className="h-[20rem] py-2 overflow-hidden overflow-y-scroll ">
          <div className="text-danger flex items-start gap-4 mb-10">
            <Avatar>
              <AvatarImage alt="@shadcn" />
              <AvatarFallback className="bg-primary text-white">
                {firstName?.charAt(0).toUpperCase() +
                  "" +
                  lastName?.charAt(0).toUpperCase() +
                  ""}
              </AvatarFallback>
            </Avatar>

            <SendNote id={id} refetch={refetch} />
          </div>
          {/* <ListComments id={1} /> */}
          {/* <ReturnNote /> */}
          <DisplayNote data={data || []} customerId={id} refetch={refetch} />
        </div>
      </div>
    </div>
  );
};

function DisplayNote({
  data,
  refetch,
  customerId,
  viewAmemded = false,
}: {
  data: NotesT[];
  refetch: () => void;
  customerId: number;
  viewAmemded?: boolean;
}) {
  return (
    <div className="space-y-3 ">
      {data?.map((item) => {
        return (
          <CommentNote
            customerId={customerId}
            data={item}
            refetch={refetch}
            key={item.id}
            viewAmemded={viewAmemded}
          />
        );
      })}
    </div>
  );
}

function CommentNote({
  data,
  customerId,
  refetch,
  viewAmemded,
}: {
  data: NotesT;
  customerId: number;
  refetch: () => void;
  viewAmemded: boolean;
}) {
  const [open, setOpen] = useState(viewAmemded);

  function toggle() {
    setOpen((prev) => !prev);
  }

  return (
    <div key={data.id} className="text-black ">
      <div className="flex datas-start gap-4 w-full">
        <Avatar>
          <AvatarImage alt="@shadcn" />
          <AvatarFallback
            style={{
              backgroundColor: getRandomDarkColor(),
            }}
            className=" text-white"
          >
            {/* {(data.created_by_name || "").charAt(0)?.toUpperCase()} */}
          </AvatarFallback>
        </Avatar>

        <CommentBox
          customerId={customerId}
          refetch={refetch}
          toggle={toggle}
          data={data}
        />
      </div>
      {open && (
        <div className=" ml-16 mt-5">
          <DisplayNote
            customerId={customerId}
            refetch={refetch}
            data={data?.replies}
            viewAmemded={open}
          />
        </div>
      )}
    </div>
  );
}

function CommentBox({
  data,
  toggle,
  customerId,
  refetch,
}: {
  data: NotesT;
  toggle: () => void;
  customerId: number;
  refetch: () => void;
}) {
  const [commentToggle, setCommentToggle] = useState(false);

  return (
    <div className="bg-white rounded-lg p-2 w-full relative">
      <p className="">
        <span className="font-semibold">{data.created_by_name + " "}</span>

        {format(data?.updated_at, "dd MMM, yyyy ") +
          "at" +
          format(data?.updated_at, " h:mm aa")}{" "}
        {/* {data?.updated_at + ""} */}
      </p>
      <div className="">
        <ClampText key={data.id} text={data?.note} />
      </div>
      {data?.replies?.length > 0 && (
        <p
          className="cursor-pointer text-sm"
          onClick={() => data?.replies.length && toggle()}
        >
          amended ({data?.total_parents_count})
        </p>
      )}

      {data.child_note === null && commentToggle && (
        <div className="my-2">
          <SendNote id={customerId} parent_id={data.id} refetch={refetch} />
        </div>
      )}

      {data.child_note === null && (
        <Pencil
          className="w-5 absolute right-2 top-2 cursor-pointer"
          onClick={() => setCommentToggle((prev) => !prev)}
        />
      )}
    </div>
  );
}

const ClampText = ({ text }: { text: string }) => {
  const pRef = useRef<HTMLParagraphElement>(null);
  const [show, setShow] = useState(false);
  const [showBtn, setShowBtn] = useState(false);

  function countLines() {
    if (!pRef.current) return;
    const divHeight = pRef?.current?.offsetHeight;
    const lineHeight = parseInt(pRef?.current?.style.lineHeight);

    const lines = divHeight / lineHeight;
    return lines;
  }
  useEffect(() => {
    const lines = countLines() || 0;

    if (lines > 2) {
      setShowBtn(true);
    }
  }, []);

  return (
    <div>
      <div
        ref={pRef}
        className={`text-black ${
          !show && " line-clamp-3 "
        } whitespace-pre-wrap my-2`}
        style={{ lineHeight: "20px" }}
      >
        {text}
      </div>

      {showBtn && (
        <p
          onClick={(e) => {
            e.stopPropagation();
            setShow((prev) => !prev);
          }}
          className="text-danger cursor-pointer text-right text-sm"
        >
          {!show ? "View more" : "View less"}
        </p>
      )}
    </div>
  );
};

interface OrderItem {
  productId: number;
  count: number;
  postageServiceChargeId?: number;
}

function AddOrderDialog({
  customerId,
  products,
  postageCharges,
  refetchOrders,
  refetchProducts,
  isAdminOrOwner,
}: {
  customerId: number;
  products: ProductT[];
  postageCharges: PostageServiceChargeT[];
  refetchOrders: () => void;
  refetchProducts: () => void;
  isAdminOrOwner: boolean;
}) {
  const [open, setOpen] = useState(false);
  const [orderItems, setOrderItems] = useState<OrderItem[]>([
    { productId: 0, count: 1, postageServiceChargeId: undefined },
  ]);
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const createOrderMutation = useMutation({
    mutationFn: async (data: CreateOrderDto) => {
      const res = await Axios.post<{ data: OrderT; message: string }>(
        "/orders/",
        data
      );
      return res.data;
    },
    onSuccess: () => {
      toast({
        title: "Success",
        description: "Order created successfully",
      });
      setOpen(false);
      setOrderItems([{ productId: 0, count: 1 }]);
      refetchOrders();
      queryClient.invalidateQueries({ queryKey: ["customer-orders"] });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description:
          error?.response?.data?.message || "Failed to create order",
        variant: "destructive",
      });
    },
  });

  const handleAddProduct = () => {
    setOrderItems([...orderItems, { productId: 0, count: 1, postageServiceChargeId: undefined }]);
  };

  const handleRemoveProduct = (index: number) => {
    if (orderItems.length > 1) {
      setOrderItems(orderItems.filter((_, i) => i !== index));
    }
  };

  const handleProductChange = (index: number, productId: number) => {
    const updated = [...orderItems];
    updated[index].productId = productId;
    setOrderItems(updated);
  };

  const handleCountChange = (index: number, count: number) => {
    const updated = [...orderItems];
    updated[index].count = Math.max(1, parseInt(count.toString()) || 1);
    setOrderItems(updated);
  };

  const handlePostageChange = (index: number, postageId: number | undefined) => {
    const updated = [...orderItems];
    updated[index].postageServiceChargeId = postageId;
    setOrderItems(updated);
  };

  // Helper to compute per-item pricing
  const getItemAmounts = (item: OrderItem) => {
    const product = products.find((p) => p.id === item.productId);
    const postage = item.postageServiceChargeId
      ? postageCharges.find((p) => p.id === item.postageServiceChargeId)
      : undefined;

    const amountPerTub = product?.amount ? Number(product.amount) : 0;
    const postageAmount = postage?.amount ? Number(postage.amount) : 0;
    const totalAmount = amountPerTub * (item.count || 0) + postageAmount;

    return { amountPerTub, postageAmount, totalAmount };
  };

  const handleSubmit = () => {
    // Validate all products are selected
    const invalidItems = orderItems.filter(
      (item) => !item.productId || item.count < 1
    );
    if (invalidItems.length > 0) {
      toast({
        title: "Validation Error",
        description: "Please select a product and enter a valid quantity for all items",
        variant: "destructive",
      });
      return;
    }

    const mappedOrderItems = orderItems.map((item) => {
      const { amountPerTub, totalAmount } = getItemAmounts(item);
      return {
        productId: item.productId,
        count: item.count,
        amountPerTub,
        totalAmount,
        postageServiceChargeId: item.postageServiceChargeId || undefined,
      };
    });

    const createOrderDto: CreateOrderDto = {
      customerId,
      orderItems: mappedOrderItems,
    };

    createOrderMutation.mutate(createOrderDto);
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button size="sm" className="gap-2">
          <Plus className="w-4 h-4" />
          Add Order
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Create New Order</DialogTitle>
          <DialogDescription>
            Add products to create an order for this customer
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4 py-4">
          {orderItems.map((item, index) => {
            const { amountPerTub, postageAmount, totalAmount } = getItemAmounts(item);
            return (
              <div key={index} className="flex flex-col gap-2 border rounded-md p-3">
                <div className="flex gap-2 items-end">
                  <div className="flex-1">
                    <label htmlFor={`product-${index}`} className="text-sm font-medium mb-1 block">
                      Product
                    </label>
                    <Select
                      value={item.productId > 0 ? item.productId.toString() : ""}
                      onValueChange={(value) =>
                        handleProductChange(index, parseInt(value))
                      }
                    >
                      <SelectTrigger 
                        id={`product-${index}`}
                      >
                        <SelectValue placeholder="Select a product" />
                      </SelectTrigger>
                      <SelectContent>
                        {products.map((product) => {
                          // Check if this product is already selected in another item
                          const isSelected = orderItems.some(
                            (otherItem, otherIndex) =>
                              otherIndex !== index && otherItem.productId === product.id
                          );
                          return (
                            <SelectItem
                              key={product.id}
                              value={product.id.toString()}
                              disabled={isSelected}
                              className={isSelected ? "opacity-50 cursor-not-allowed" : ""}
                            >
                              {product.name}
                            </SelectItem>
                          );
                        })}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="w-32">
                    <label htmlFor={`count-${index}`} className="text-sm font-medium mb-1 block">
                      Quantity
                    </label>
                    <Input
                      id={`count-${index}`}
                      type="number"
                      min="1"
                      value={item.count}
                      onChange={(e) =>
                        handleCountChange(index, parseInt(e.target.value) || 1)
                      }
                    />
                  </div>
                  <div className="w-56">
                    <label className="text-sm font-medium mb-1 block">
                      Postage / Service
                    </label>
                    <Select
                      value={item.postageServiceChargeId ? String(item.postageServiceChargeId) : ""}
                      onValueChange={(value) =>
                        handlePostageChange(index, value ? parseInt(value) : undefined)
                      }
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select postage (optional)" />
                      </SelectTrigger>
                      <SelectContent>
                        {postageCharges.map((charge) => (
                          <SelectItem key={charge.id} value={charge.id.toString()}>
                            {charge.name} - £{Number(charge.amount).toFixed(2)}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  {orderItems.length > 1 && (
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => handleRemoveProduct(index)}
                    >
                      <X className="w-4 h-4" />
                    </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>
                  {postageAmount > 0 && (
                    <span>
                      Postage: <span className="font-semibold">£{postageAmount.toFixed(2)}</span>
                    </span>
                  )}
                  <span>
                    Total: <span className="font-semibold text-primary">£{totalAmount.toFixed(2)}</span>
                  </span>
                </div>
              </div>
            );
          })}
          <div className="flex gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={handleAddProduct}
              className="flex-1"
            >
              <Plus className="w-4 h-4 mr-2" />
              Add Another Product
            </Button>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => setOpen(false)}>
            Cancel
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={createOrderMutation.isPending}
          >
            {createOrderMutation.isPending ? "Creating..." : "Create Order"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function EditableOrderRow({
  order,
  products,
  refetchOrders,
  customerId,
  firstName,
  lastName,
}: {
  order: OrderT;
  products: ProductT[];
  refetchOrders: () => void;
  customerId: number;
  firstName?: string;
  lastName?: string;
}) {
  const [isEditing, setIsEditing] = useState(false);
  const [orderItems, setOrderItems] = useState<OrderItem[]>([]);
  const initializedRef = useRef(false);
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const orderItemsData = order.orderItems || [];
  const hasProducts = orderItemsData.length > 0;

  // Initialize orderItems when entering edit mode (fallback if handleEditClick doesn't run)
  useEffect(() => {
    if (isEditing && orderItems.length === 0 && !initializedRef.current) {
      // Only initialize if orderItems is empty (to avoid overwriting handleEditClick)
      if (order.orderItems && order.orderItems.length > 0) {
        const mappedItems = order.orderItems
          .filter((item) => item.productId > 0) // Only include items with valid productId
          .map((item) => {
            // Ensure proper conversion of productId and count
            const productId = item.productId ? Number(item.productId) : 0;
            // Parse count more carefully - handle string, number, null, undefined
            let count = 1;
            if (item.count !== null && item.count !== undefined) {
              const parsedCount = Number(item.count);
              if (!isNaN(parsedCount) && parsedCount >= 1) {
                count = parsedCount;
              }
            }
            return {
              productId,
              count,
            };
          });
        // Set the orderItems, or default to one empty item if no valid items
        if (mappedItems.length > 0) {
          setOrderItems(mappedItems);
        } else {
          setOrderItems([{ productId: 0, count: 1 }]);
        }
      } else {
        // If no orderItems exist, start with one empty item
        setOrderItems([{ productId: 0, count: 1 }]);
      }
    } else if (!isEditing) {
      // Reset when not editing
      setOrderItems([]);
      initializedRef.current = false;
    }
  }, [isEditing, order.orderItems]);

  const updateOrderMutation = useMutation({
    mutationFn: async (data: { orderItems: { productId: number; count: number }[] }) => {
      const res = await Axios.patch<{ data: OrderT; message: string; }>(
        `/orders/${order.id}`,
        data
      );
      return res.data;
    },
    onSuccess: () => {
      toast({
        title: "Success",
        description: "Order updated successfully",
      });
      setIsEditing(false);
      refetchOrders();
      queryClient.invalidateQueries({ queryKey: ["customer-orders"] });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description:
          error?.response?.data?.message || "Failed to update order",
        variant: "destructive",
      });
    },
  });

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

  const handleRemoveProduct = (index: number) => {
    if (orderItems.length > 1) {
      setOrderItems(orderItems.filter((_, i) => i !== index));
    }
  };

  const handleProductChange = (index: number, productId: string | number) => {
    const updated = [...orderItems];
    updated[index].productId = Number(productId);
    setOrderItems(updated);
  };

  const handleCountChange = (index: number, count: number) => {
    const updated = [...orderItems];
    updated[index].count = Math.max(1, parseInt(count.toString()) || 1);
    setOrderItems(updated);
  };

  const handleSave = () => {
    // Filter out invalid items and validate
    const validItems = orderItems.filter(
      (item) => item.productId > 0 && item.count >= 1
    );

    if (validItems.length === 0) {
      toast({
        title: "Validation Error",
        description: "Please add at least one product with a valid quantity",
        variant: "destructive",
      });
      return;
    }

    // Check if there are any invalid items that were filtered out
    const invalidItems = orderItems.filter(
      (item) => item.productId <= 0 || item.count < 1
    );
    if (invalidItems.length > 0) {
      toast({
        title: "Validation Error",
        description: "Please select a product and enter a valid quantity for all items",
        variant: "destructive",
      });
      return;
    }

    updateOrderMutation.mutate({
      orderItems: validItems.map((item) => ({
        productId: Number(item.productId),
        count: Number(item.count),
      })),
    });
  };

  const handleCancel = () => {
    setIsEditing(false);
    setOrderItems([]);
    initializedRef.current = false;
  };

  const handleEditClick = () => {
    // Mark as initialized to prevent useEffect from interfering
    initializedRef.current = true;
    
    // Initialize orderItems immediately when clicking edit
    if (order.orderItems && order.orderItems.length > 0) {
      const mappedItems = order.orderItems
        .filter((item) => item.productId > 0)
        .map((item) => {
          const productId = item.productId ? Number(item.productId) : 0;
          // Parse count - use the actual count value from the item
          let count = 1;
          if (item.count !== null && item.count !== undefined) {
            const parsedCount = Number(item.count);
            // Use the parsed count if it's a valid number and >= 1
            if (!isNaN(parsedCount) && parsedCount >= 1) {
              count = parsedCount;
            }
          }
          return { productId, count };
        });
      
      // Set orderItems first, then set editing state
      if (mappedItems.length > 0) {
        setOrderItems(mappedItems);
      } else {
        setOrderItems([{ productId: 0, count: 1 }]);
      }
    } else {
      setOrderItems([{ productId: 0, count: 1 }]);
    }
    // Set editing state - React will batch these updates correctly
    setIsEditing(true);
  };

  // Handle empty orders
  if (!hasProducts || orderItemsData.length === 0) {
    return (
      <TableRow className="hover:bg-muted/30">
        <TableCell className="py-3">
          <div className="space-y-0.5">
            <div className="text-sm font-medium">
              {format(
                new Date(
                  typeof order.createdAt === "string"
                    ? order.createdAt
                    : order.createdAt
                ),
                "dd-MMM-yy"
              )}
            </div>
            <div className="text-xs text-muted-foreground">
              {format(
                new Date(
                  typeof order.createdAt === "string"
                    ? order.createdAt
                    : order.createdAt
                ),
                "h:mm aa"
              )}
            </div>
          </div>
        </TableCell>
        <TableCell className="py-3">
          <div className="flex items-center gap-2">
            <div className="w-7 h-7 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0">
              <span className="text-xs font-semibold text-primary">
                {getUserInitial(order.createdBy)}
              </span>
            </div>
            <span className="text-sm truncate">{getUserName(order.createdBy)}</span>
          </div>
        </TableCell>
        <TableCell colSpan={7} className="py-3 text-center text-muted-foreground">
          No products
        </TableCell>
      </TableRow>
    );
  }

  // Calculate order totals
  const orderDate = new Date(
    typeof order.createdAt === "string" ? order.createdAt : order.createdAt
  );
  const formattedDate = format(orderDate, "dd-MMM-yy");
  const formattedTime = format(orderDate, "h:mm aa");
  const createdByName = getUserName(order.createdBy);

  // Calculate totals
  let productsSubtotal = 0;
  let postageAmount = 0;
  let orderTotal = 0;
  let hasDiscount = false;
  let discountNote = "";

  orderItemsData.forEach((item, idx) => {
    const amountPerTub = Number(item.amountPerTub) || 0;
    // Exclude free products (amountPerTub = 0) from products subtotal
    // Free products should only be added via "Add a free product" button
    if (amountPerTub > 0) {
      const itemSubtotal = amountPerTub * item.count;
      productsSubtotal += itemSubtotal;
    }

    // Get postage from first item only
    if (idx === 0 && item.postageServiceCharge) {
      postageAmount = Number(item.postageServiceCharge.amount) || 0;
    }

    // Get order note from first item (general order note is stored in first item's deductionNote)
    if (idx === 0 && item.deductionNote) {
      discountNote = item.deductionNote;
    }
  });

  // Calculate order total (products + postage)
  orderTotal = productsSubtotal + postageAmount;
  
  // Get the actual order total by summing all items' totalAmount
  // This accounts for all products including any manual adjustments
  const actualOrderTotal = orderItemsData.reduce((sum, item) => {
    const itemTotal = item.totalAmount ? Number(item.totalAmount) : 0;
    return sum + itemTotal;
  }, 0);
  
  // Calculate discount amount if there's a difference
  // Discount = actual total - calculated total (products + postage, excluding free products)
  const discountAmount = actualOrderTotal !== orderTotal
    ? actualOrderTotal - orderTotal
    : 0;
  
  if (discountAmount !== 0 || discountNote) {
    hasDiscount = true;
  }

  // Use the actual total if available, otherwise use calculated
  const finalOrderTotal = actualOrderTotal > 0 ? actualOrderTotal : orderTotal;

  // Calculate total rows for rowSpan
  const totalRows = orderItemsData.length + (postageAmount > 0 ? 1 : 0) + (hasDiscount ? 1 : 0);

  // Render rows: one for each product, one for shipping, one for discount
  const rows: React.ReactNode[] = [];

  // Product rows
  orderItemsData.forEach((item, idx) => {
    const amountPerTub = Number(item.amountPerTub) || 0;
    const quantity = Number(item.count) || 0;
    const subtotal = amountPerTub * quantity;
    const isFreeProduct = amountPerTub === 0;
    const isFirstProduct = idx === 0;

    rows.push(
      <TableRow key={`product-${item.id || idx}`} className="hover:bg-muted/30 border-b">
        {isFirstProduct && (
          <>
            <TableCell rowSpan={totalRows} className="py-3 align-top border-r">
              <div className="space-y-0.5">
                <div className="text-sm font-medium text-gray-800">{formattedDate}</div>
                <div className="text-xs text-gray-500">{formattedTime}</div>
              </div>
            </TableCell>
            <TableCell rowSpan={totalRows} className="py-3 align-top border-r">
              <div className="flex items-center gap-2">
                <div className="w-7 h-7 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0">
                  <span className="text-xs font-semibold text-primary">
                    {getUserInitial(order.createdBy)}
                  </span>
                </div>
                <span className="text-sm truncate text-gray-700">{createdByName}</span>
              </div>
            </TableCell>
          </>
        )}
          <TableCell className="py-2 align-middle">
            <span className="text-sm text-gray-800">{item.product?.name || "N/A"}</span>
          </TableCell>
        <TableCell className="py-2 align-middle text-center">
          <span className="text-sm text-gray-700">{quantity}</span>
        </TableCell>
        <TableCell className="py-2 align-middle text-right">
          <span className="text-sm text-gray-700">{amountPerTub.toFixed(2)}</span>
        </TableCell>
        <TableCell className="py-2 align-middle text-right">
          <span className="text-sm font-medium text-gray-800">{subtotal.toFixed(2)}</span>
        </TableCell>
        {isFirstProduct && (
          <TableCell rowSpan={totalRows} className="py-3 align-top border-l border-r">
            <div className="text-sm font-bold text-primary">
              {finalOrderTotal.toFixed(2)}
            </div>
          </TableCell>
        )}
        {isFirstProduct && (
          <TableCell rowSpan={totalRows} className="py-3 align-top border-l border-r">
            <span className="text-xs text-gray-600 whitespace-normal break-words max-w-xs">
              {discountNote || "-"}
            </span>
          </TableCell>
        )}
        {isFirstProduct && (
          <TableCell rowSpan={totalRows} className="py-3 align-top border-l">
            <div className="flex justify-center">
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8 hover:bg-primary/10"
                onClick={() => {
                  const params = new URLSearchParams({
                    customerId: customerId.toString(),
                    orderId: order.id.toString(),
                    ...(firstName && { firstName }),
                    ...(lastName && { lastName }),
                  });
                  window.location.href = `/customer/create-order?${params.toString()}`;
                }}
              >
                <Pencil className="w-4 h-4 text-gray-600" />
              </Button>
            </div>
          </TableCell>
        )}
      </TableRow>
    );
  });

  // Shipping row
  if (postageAmount > 0) {
    rows.push(
      <TableRow key="shipping" className="hover:bg-muted/30 border-b">
        <TableCell className="py-2 align-middle">
          <span className="text-sm font-medium text-gray-800">Postage</span>
        </TableCell>
        <TableCell className="py-2 align-middle text-center">
          <span className="text-sm text-gray-400">-</span>
        </TableCell>
        <TableCell className="py-2 align-middle text-right">
          <span className="text-sm text-gray-400">-</span>
        </TableCell>
        <TableCell className="py-2 align-middle text-right">
          <span className="text-sm font-medium text-gray-800">{postageAmount.toFixed(2)}</span>
        </TableCell>
      </TableRow>
    );
  }

  // Discount/Round Off row
  if (hasDiscount) {
    rows.push(
      <TableRow key="discount" className="hover:bg-muted/30 border-b">
        <TableCell className="py-2 align-middle">
          <span className="text-sm font-medium text-gray-800">Discount/Round Off</span>
        </TableCell>
        <TableCell className="py-2 align-middle text-center">
          <span className="text-sm text-gray-400">-</span>
        </TableCell>
        <TableCell className="py-2 align-middle text-right">
          <span className="text-sm text-gray-400">-</span>
        </TableCell>
        <TableCell className="py-2 align-middle text-right">
          <span className={`text-sm font-medium ${discountAmount < 0 ? 'text-red-600' : 'text-gray-800'}`}>
            {discountAmount !== 0 ? discountAmount.toFixed(2) : "-"}
          </span>
        </TableCell>
      </TableRow>
    );
  }

  return <>{rows}</>;
}

function AddProductDialog({
  refetchProducts,
  isAdminOrOwner,
}: {
  refetchProducts: () => void;
  isAdminOrOwner: boolean;
}) {
  const [open, setOpen] = useState(false);
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const createProductMutation = useMutation({
    mutationFn: async (data: CreateProductDto) => {
      const res = await Axios.post<{ data: ProductT; message: string }>(
        "/products/",
        data
      );
      return res.data;
    },
    onSuccess: () => {
      toast({
        title: "Success",
        description: "Product created successfully",
      });
      setOpen(false);
      setName("");
      setDescription("");
      refetchProducts();
      queryClient.invalidateQueries({ queryKey: ["products-list"] });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description:
          error?.response?.data?.message || "Failed to create product",
        variant: "destructive",
      });
    },
  });

  const handleSubmit = () => {
    if (!name.trim()) {
      toast({
        title: "Validation Error",
        description: "Product name is required",
        variant: "destructive",
      });
      return;
    }

    const createProductDto: CreateProductDto = {
      name: name.trim(),
      description: description.trim() || undefined,
    };

    createProductMutation.mutate(createProductDto);
  };

  if (!isAdminOrOwner) {
    return null;
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button size="sm" variant="outline" className="gap-2">
          <Plus className="w-4 h-4" />
          Add Product
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Create New Product</DialogTitle>
          <DialogDescription>
            Add a new product to the database
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4 py-4">
          <div>
            <label htmlFor="product-name" className="text-sm font-medium mb-1 block">
              Product Name *
            </label>
            <Input
              id="product-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Enter product name"
            />
          </div>
          <div>
            <label htmlFor="product-description" className="text-sm font-medium mb-1 block">
              Description
            </label>
            <Input
              id="product-description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Enter product description (optional)"
            />
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => setOpen(false)}>
            Cancel
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={createProductMutation.isPending}
          >
            {createProductMutation.isPending ? "Creating..." : "Create Product"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

export default OrdersAndNotes;
