"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 { 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 } 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;
    },
  });

  // const { ReturnNote, refetch } = noteListHandler(id);
  const searchParams = useSearchParams();
  const firstName = searchParams.get("firstName");
  const lastName = searchParams.get("lastName");
  const userData = useUserStore((state) => state.data);
  const isAdminOrOwner =
    userData?.role?.toLowerCase() === "admin" ||
    userData?.role?.toLowerCase() === "owner";

  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">
            <AddProductDialog
              refetchProducts={refetchProducts}
              isAdminOrOwner={isAdminOrOwner}
            />
            <AddOrderDialog
              customerId={id}
              products={productsData || []}
              refetchOrders={refetchOrders}
              refetchProducts={refetchProducts}
              isAdminOrOwner={isAdminOrOwner}
            />
          </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-muted/50 hover:bg-muted/50">
                  <TableHead className="font-semibold whitespace-nowrap">Date & Time</TableHead>
                  <TableHead className="font-semibold whitespace-nowrap">Created By</TableHead>
                  <TableHead className="font-semibold whitespace-nowrap">Product Name</TableHead>
                  <TableHead className="font-semibold whitespace-nowrap">Count</TableHead>
                  <TableHead className="font-semibold whitespace-nowrap text-center">Edit</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {ordersLoading ? (
                  <TableRow>
                    <TableCell colSpan={5} 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}
                    />
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={5} 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;
}

function AddOrderDialog({
  customerId,
  products,
  refetchOrders,
  refetchProducts,
  isAdminOrOwner,
}: {
  customerId: number;
  products: ProductT[];
  refetchOrders: () => void;
  refetchProducts: () => void;
  isAdminOrOwner: boolean;
}) {
  const [open, setOpen] = useState(false);
  const [orderItems, setOrderItems] = useState<OrderItem[]>([
    { productId: 0, count: 1 },
  ]);
  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 }]);
  };

  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 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 createOrderDto: CreateOrderDto = {
      customerId,
      orderItems: orderItems.map((item) => ({
        productId: item.productId,
        count: item.count,
      })),
    };

    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) => (
            <div key={index} 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>
              {orderItems.length > 1 && (
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => handleRemoveProduct(index)}
                >
                  <X className="w-4 h-4" />
                </Button>
              )}
            </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>
            {isAdminOrOwner && (
              <AddProductDialog
                refetchProducts={refetchProducts}
                isAdminOrOwner={isAdminOrOwner}
              />
            )}
          </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,
}: {
  order: OrderT;
  products: ProductT[];
  refetchOrders: () => void;
}) {
  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);
  };

  return (
    <TableRow className="hover:bg-muted/30">
      <TableCell className="py-3 align-top">
        <div className="space-y-1">
          <div className="flex items-center gap-2 text-sm">
            <CalendarIcon className="w-4 h-4 text-muted-foreground flex-shrink-0" />
            <span className="font-medium">
              {format(
                new Date(
                  typeof order.createdAt === "string"
                    ? order.createdAt
                    : order.createdAt
                ),
                "dd MMM, yyyy"
              )}
            </span>
          </div>
          <div className="flex items-center gap-2 text-xs text-muted-foreground">
            <ClockIcon className="w-3.5 h-3.5 flex-shrink-0" />
            <span>
              {format(
                new Date(
                  typeof order.createdAt === "string"
                    ? order.createdAt
                    : order.createdAt
                ),
                "h:mm aa"
              )}
            </span>
          </div>
        </div>
      </TableCell>
      <TableCell className="py-3 align-top">
        <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 className="py-3 align-top">
        {isEditing ? (
          <div className="space-y-2">
            {orderItems.map((item, index) => (
              <div key={`product-${index}-${item.productId}`} className="flex gap-2 items-center">
                  <Select
                    value={item.productId > 0 ? item.productId.toString() : ""}
                    onValueChange={(value) =>
                      handleProductChange(index, value)
                    }
                  >
                    <SelectTrigger className="h-9 text-sm">
                      <SelectValue placeholder="Select 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>
                {orderItems.length > 1 && (
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8"
                    onClick={() => handleRemoveProduct(index)}
                  >
                    <X className="w-3.5 h-3.5" />
                  </Button>
                )}
              </div>
            ))}
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={handleAddProduct}
              className="w-full mt-1"
            >
              <Plus className="w-3.5 h-3.5 mr-1" />
              Add Product
            </Button>
          </div>
        ) : (
          hasProducts ? (
            <div className="space-y-1.5">
              {orderItemsData.map((item, idx) => (
                <div key={item.id || idx} className="text-sm font-medium">
                  {item.product?.name || "N/A"}
                </div>
              ))}
            </div>
          ) : (
            <span className="text-sm text-muted-foreground">No products</span>
          )
        )}
      </TableCell>
      <TableCell className="py-3 align-top">
        {isEditing ? (
          <div className="space-y-2">
            {orderItems.map((item, index) => {
              // Ensure count is always a valid number string for the input
              const countValue = item.count && item.count >= 1 ? String(item.count) : "";
              // Use native input to ensure value is properly displayed
              return (
                <input
                  key={`count-${index}-${item.productId}`}
                  type="number"
                  min="1"
                  value={countValue}
                  onChange={(e) =>
                    handleCountChange(index, parseInt(e.target.value) || 1)
                  }
                  className="flex h-9 w-20 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 disabled:cursor-not-allowed disabled:opacity-50"
                />
              );
            })}
          </div>
        ) : (
          hasProducts ? (
            <div className="space-y-1.5">
              {orderItemsData.map((item, idx) => (
                <div key={item.id || idx}>
                  <span className="inline-flex items-center px-2.5 py-1 rounded-md bg-primary/10 text-primary text-sm font-medium">
                    {item.count}
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <span className="text-sm text-muted-foreground">-</span>
          )
        )}
      </TableCell>
      <TableCell className="py-3 align-top">
        {isEditing ? (
          <div className="flex gap-1">
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8 text-green-600 hover:text-green-700 hover:bg-green-50"
              onClick={handleSave}
              disabled={updateOrderMutation.isPending}
            >
              <Check className="w-4 h-4" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8 text-red-600 hover:text-red-700 hover:bg-red-50"
              onClick={handleCancel}
              disabled={updateOrderMutation.isPending}
            >
              <X className="w-4 h-4" />
            </Button>
          </div>
        ) : (
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8"
            onClick={handleEditClick}
          >
            <Pencil className="w-4 h-4" />
          </Button>
        )}
      </TableCell>
    </TableRow>
  );
}

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;
