"use client";
import { useState, useEffect } from "react";
import {
  ChevronLeft,
  ChevronDown,
  Trash2,
  CircleDashed,
  ArrowLeft,
  Drumstick,
  Beef,
  Ham,
  PrinterIcon,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useGetProductsQuery } from "@/redux/services/products.api";
import {
  OrderDetails,
  useCreateOrdersMutation,
} from "@/redux/services/orders.api";
import { toast } from "@/components/ui/use-toast";
import { useGetBranchByNameQuery } from "@/redux/services/branchs.api";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import Image from "next/image";
import logo from "../../../../../public/logodark.webp";

// Example product data from the API

// Define types for product and order item
type Product = {
  _id: string;
  name: string;
  images: string[];
  description: string;
  status: string;

  quantity: number[];
  // price: number | string;
  categoryName: string;
};

type OrderItem = {
  productId: string;
  name: string;
  quantity: number;
  inventoryQuantity: number;
  // price: number;
  image: string;
};

export default function Component(params: { params: { slug: string } }) {
  //   new Date(new Date().setDate(new Date().getDate() + 1))
  //     .toISOString()
  //     .split("T")[0]
  // );
  const router = useRouter();
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [orderData, setOrderData] = useState<OrderDetails>();
  const [orderItems, setOrderItems] = useState<OrderItem[]>([]);
  // const [totalAmount, setTotalAmount] = useState<number>(0);
  const {
    data: products,
    isLoading: isProductsLoading,
    error: productsError,
  } = useGetProductsQuery();
  const {
    data: branch,
    isLoading: isbranchLoading,
    error: branchError,
  } = useGetBranchByNameQuery(params.params.slug);

  const [createOrder, { isLoading, error }] = useCreateOrdersMutation({});
  const formatDate = (dateString: string) => {
    const [day, month, year] = dateString.split("-");
    const date = new Date(`${year}-${month}-${day}`);
    return date.toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    });
  };

  const formatDateWithOrdinal = (dateString: string): string => {
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    });
  };
  // useEffect(() => {
  //   // Simulate fetching data from an API
  //   setProducts(productData.data);
  // }, []);

  // Recalculate the total amount whenever orderItems change
  // useEffect(() => {
  //   if (!branch) {
  //     router.push("/create-order");
  //   }
  // });
  // useEffect(() => {
  //   const newTotalAmount = orderItems.reduce(
  //     // (acc, item) => acc + item.price * item.quantity,
  //     0
  //   );
  //   setTotalAmount(newTotalAmount);
  // }, [orderItems]);

  const addProduct = (product: Product) => {
    const existingItem = orderItems.find(
      (item) => item.productId === product._id
    );

    if (existingItem) {
      // Update quantity if the product is already in the order
      if (existingItem.quantity !== product.quantity[0])
        updateQuantity(product._id, existingItem.quantity + 1);
    } else {
      const newItem: OrderItem = {
        productId: product._id,
        name: product.name,
        quantity: 1,
        inventoryQuantity: product.quantity[0],
        // price: parseFloat(product.price.toString()),
        image: product.images[0],
      };
      setOrderItems((prevItems) => [...prevItems, newItem]);
    }
  };

  const updateQuantity = (id: string, quantity: number) => {
    if (quantity <= 0) return; // Don't allow quantities below 1

    setOrderItems((prevItems) =>
      prevItems.map((item) => {
        if (item.productId === id) {
          return { ...item, quantity };
        }
        return item;
      })
    );
  };

  const removeItem = (id: string) => {
    setOrderItems((prevItems) =>
      prevItems.filter((item) => item.productId !== id)
    );
  };
  const handleCreate = (e: any) => {
    e.preventDefault();
    if (orderItems.length < 1) {
      return toast({
        title: "Please add Items to Order",
        variant: "destructive",
      });
    }

    const formData = new FormData(e.target);

    // Get the values from the form
    const customerName = "default";
    const customerPhone = "default";
    const d = new Date();
    // const customerAddress = formData.get("customer-address");
    const additionalNote = formData.get("additional-note");
    const orderDate = formData.get("order-date");
    const orderTime = formData.get("order-time");
    const hours = String(d.getHours()).padStart(2, "0");
    const minutes = String(d.getMinutes()).padStart(2, "0");
    const time = `${hours}:${minutes}`;
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, "0"); // Months are 0-based
    const day = String(d.getDate()).padStart(2, "0");
    const date = `${year}-${month}-${day}`;
    const orderData = {
      branchId: branch![0]._id!, // Replace with actual branchId if dynamic
      branchCode: branch![0].code!, // Replace with actual branchCode if dynamic
      products: orderItems.map((item) => ({
        productId: item.productId,
        quantity: item.quantity.toString(), // Convert quantity to string
      })),
      // totalAmount: orderItems.reduce(
      //   (total, item) => total + item.price * item.quantity,
      //   0
      // ),
      totalProducts: orderItems.length,
      customerName: customerName?.toString() || "",
      customerPhone: parseInt(customerPhone!.toString()) || 0,
      // customerAddress: customerAddress?.toString() || "",
      additionalNote: additionalNote?.toString() || "",
      date: date || "", // Convert date to string and format
      time: time.toString() || "",
    };
    // const orderData = {
    //   branchId: branch!._id!, // Replace with actual branchId if dynamic
    //   branchCode: branch!.code, // Replace with actual branchCode if dynamic
    //   products: orderItems.map((item) => ({
    //     productId: item.productId,
    //     quantity: item.quantity,
    //   })),
    //   totalAmount: totalAmount,
    //   totalProducts: orderItems.length,
    //   customerName,
    //   customerPhone,
    //   customerAddress,
    //   additionalNote,
    //   date: orderDate!.toString().split("-").reverse().join("-"), // Convert YYYY-MM-DD to DD-MM-YYYY format
    //   time: orderTime,
    // };

    createOrder(orderData)
      .unwrap()
      .then((res: any) => {
        setIsDialogOpen(true);
        setOrderData(res.data);
        setOrderItems([]);
        e.target.reset();
        if (res.status) {
          return toast({
            title: res.message,
            variant: "success",
          });
        }
        return toast({
          title: res.message,
          variant: "destructive",
        });
      })
      .catch((err: any) => console.log("err", err));
    setOrderItems([]);
    e.target.reset();
  };
  const a = new Date();
  const year = a.getFullYear();
  const month = String(a.getMonth() + 1).padStart(2, "0");
  const day = String(a.getDate()).padStart(2, "0");

  const c = `${year}-${month}-${day}`;
  return (
    // <div className="container mx-auto p-4 bg-gray-100 min-h-screen">
    <div className="bg-white rounded-lg shadow-lg p-6">
      <div className="flex justify-end">
        {/* <div className="flex items-center mb-6">
          <Link href="/create-order">
            <ArrowLeft className="w-6 h-6 text-gray-500 mr-2 hover:animate-pulse hover:-translate-x-2 transition" />
          </Link>
          <h1 className="text-2xl font-bold capitalize">
            Order Creation for {params.params.slug}
          </h1>
        </div> */}
        <div className="flex items-center gap-1">
          <div className="w-full flex place-content-end ">
            <Label htmlFor="total-products">Total Products</Label>
          </div>
          <Input
            id="total-products"
            name="total-products"
            value={orderItems.length.toString()}
            readOnly
          />
        </div>
      </div>

      {/* Dropdown for dynamic product categories */}
      <div className="flex space-x-2 mb-6">
        {isProductsLoading && (
          <div className="flex items-center ml-8">
            {/* <div className="flex justify-center items-center h-[50vh]"> */}
            <CircleDashed className="animate-spin text-[#be063f]" />
            {/* </div> */}
          </div>
        )}
        {Array.from(
          new Set(
            products
              ?.filter((product) => product.quantity[0] > 0) // Filter products with quantity > 0 first
              .map((product) => product.categoryName)
          )
        ).map((category) => (
          <DropdownMenu key={category}>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" className="flex items-center">
                {category}
                <ChevronDown className="ml-2 h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent>
              {products
                ?.filter(
                  (product) =>
                    product.categoryName === category && product.quantity[0] > 0
                )
                .map((product) => (
                  <DropdownMenuItem
                    key={product._id}
                    onSelect={() => addProduct(product)}
                  >
                    {product.name}
                  </DropdownMenuItem>
                ))}
            </DropdownMenuContent>
          </DropdownMenu>
        ))}
      </div>

      {/* List of added order items */}
      <div className="grid grid-cols-1 2xl:grid-cols-2 gap-4">
        {orderItems.map((item) => (
          <div
            key={item.productId}
            className="flex items-center space-x-4 mb-4  shadow-md border rounded-md p-4"
          >
            <Avatar>
              {item.image && item.image.length > 0 ? (
                <Image src={item.image} height={200} width={200} alt="BI" />
              ) : (
                <AvatarFallback>{item.name.charAt(0)}</AvatarFallback>
              )}
            </Avatar>
            <div className="flex-grow">
              <p className="font-semibold">{item.name}</p>
            </div>
            <div className="flex items-center space-x-2">
              <Label htmlFor={`quantity-${item.productId}`}>Quantity</Label>
              <Input
                className="max-w-20"
                type="number"
                min={1}
                max={item.inventoryQuantity}
                value={item.quantity}
                onChange={(e) =>
                  updateQuantity(item.productId, parseInt(e.target.value))
                }
              />
            </div>
            <Trash2
              className="w-6 h-6 text-red-500 cursor-pointer"
              onClick={() => removeItem(item.productId)}
            />
          </div>
        ))}
      </div>
      {/* Total Amount and Products */}
      <div className="grid grid-cols-2 gap-4 mb-6">
        {/* <div>
          <Label htmlFor="total-amount">Total Amount</Label>
          <Input
            id="total-amount"
            name="total-amount"
            value={`$${totalAmount.toFixed(2)}`}
            readOnly
          />
        </div> */}
      </div>

      {/* Additional Form Fields */}
      <form onSubmit={(e) => handleCreate(e)}>
        <div className="space-y-4 mb-6">
          {/* <div>
            <Label htmlFor="customer-name">Customer Name</Label>
            <Input
              id="customer-name"
              name="customer-name"
              placeholder="Enter customer name"
              required
            />
          </div> */}
          {/* <div>
            <Label htmlFor="customer-phone">Customer Phone</Label>
            <Input
              id="customer-phone"
              name="customer-phone"
              type="text"
              maxLength={15}
              pattern="^\d{8,15}$"
              title="Phone number must be between 8 and 15 digits and contain only numbers"
              placeholder="Enter customer phone"
              required
            />
          </div> */}
          {/* <div>
            <Label htmlFor="customer-address">Customer's Address</Label>
            <Textarea
              id="customer-address"
              name="customer-address"
              placeholder="Enter customer's address"
              required
            />
          </div> */}
          <div>
            <Label htmlFor="additional-note">Additional Note</Label>
            <Textarea
              id="additional-note"
              name="additional-note"
              placeholder="Enter additional note"
            />
          </div>
        </div>

        {/* <h2 className="text-xl font-semibold mb-4">
          PickUp Date & Time Of Order
        </h2>
        <div className="grid grid-cols-2 gap-4 mb-6">
          <div>
            <Label htmlFor="order-date">Date</Label>
            <Input
              min={c}
              id="order-date"
              name="order-date"
              type="date"
              required
            />
          </div>
          <div>
            <Label htmlFor="order-time">Time</Label>
            <Input id="order-time" name="order-time" type="time" required />
          </div>
        </div> */}

        <div className="flex justify-between">
          <Button
            type="submit"
            className="w-2/6 bg-red-700 hover:bg-red-800 text-white"
          >
            {isLoading ? (
              <div className="flex items-center ">
                {/* <div className="flex justify-center items-center h-[50vh]"> */}
                <CircleDashed className="animate-spin text-white" />
                {/* </div> */}
              </div>
            ) : (
              "Create Order"
            )}
          </Button>
          {/* <div className="flex items-center">
            <Beef
              className={`text-red-800 hover:animate-pulse duration-500 ${
                isLoading ? "animate-pulse" : ""
              }`}
            />
            <Ham
              className={`text-red-900 hover:animate-pulse duration-500 ${
                isLoading ? "animate-pulse" : ""
              }`}
            />
            <Drumstick
              className={`text-red-800 hover:animate-pulse duration-500 ${
                isLoading ? "animate-pulse" : ""
              }`}
            />
          </div> */}
        </div>
      </form>

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center justify-between">
              {/* <LogoSmall /> */}
              <Image src={logo} height={80} width={200} alt="logo" />
              {/* <Button
                variant="outline"
                size="sm"
                // onClick={() => handlePrint(selectedOrder!)}
              >
                <PrinterIcon className="h-4 w-4 mr-2" />
                Print
              </Button> */}
            </DialogTitle>
          </DialogHeader>
          <ScrollArea className="max-h-[60vh] pr-4">
            <div className="space-y-4">
              <p className="text-center font-semibold">
                Order Created Successfully
              </p>
              {/* <div className="grid grid-cols-2 gap-2">
                <span className="text-gray-600">Customer Name</span>
                <span className="font-semibold flex justify-end">
                  {orderData?.customerName}
                </span>
                <span className="text-gray-600">Customer Phone</span>
                <span className="font-semibold flex justify-end">
                  {orderData?.customerPhone}
                </span>
              </div> */}
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Product</TableHead>
                    <TableHead className="text-right">Quantity</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {orderData?.products.map((product, i) => (
                    <TableRow key={i}>
                      <TableCell className="flex items-center gap-2">
                        <Avatar>
                          {product.image && product.image.length > 0 ? (
                            <Image
                              src={product.image}
                              height={200}
                              width={200}
                              alt="BI"
                            />
                          ) : (
                            <AvatarFallback>
                              {product.name.charAt(0)}
                            </AvatarFallback>
                          )}
                        </Avatar>
                        {/* <Avatar>
                          <AvatarImage
                            src={product.image}
                            alt={product.name.charAt(0)}
                          />
                          <AvatarFallback>
                            {product.name.charAt(0)}
                          </AvatarFallback>
                        </Avatar> */}
                        {product.name}
                      </TableCell>
                      <TableCell className="text-right">
                        {product.quantity}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
              <div className="grid grid-cols-2 gap-2">
                <span className="text-gray-600">Created Date</span>
                <span className="font-semibold justify-end flex">
                  {orderData?.createdAt &&
                    new Date(orderData?.createdAt).toLocaleDateString("en-US", {
                      year: "numeric",
                      month: "short",
                      day: "numeric",
                    })}
                </span>
                <span className="text-gray-600">Created Time</span>
                <span className="font-semibold mb-4 justify-end flex">
                  {orderData?.createdAt &&
                    new Date(orderData?.createdAt).toLocaleString("en-US", {
                      hour: "numeric",
                      minute: "numeric",
                      hour12: true,
                    })}
                </span>
                {/* {selectedOrder?.additionalNotes && ( */}
                <>
                  <span className="text-gray-600 mb-4">Additional Notes</span>
                  <span className="font-semibold mb-4 justify-end flex">
                    {orderData?.additionalNote}
                  </span>
                </>
                {/* )} */}
                {/* <div className="border border-dashed" />
                <div className="border border-dashed" />
                <span className="text-gray-600 mt-4">Invoice Number</span>
                <span className="font-semibold justify-end flex mt-4">
                  {orderData?.invoiceNumber}
                </span>
                <span className="text-gray-600">Order ID</span>
                <span className="font-semibold justify-end flex">
                  {orderData?.orderId}
                </span>
                <span className="text-gray-600">PickUp Date</span>
                <span className="font-semibold justify-end flex">
                  {orderData?.date && formatDateWithOrdinal(orderData.date)}
                </span>
                <span className="text-gray-600">PickUp Time</span>
                <span className="font-semibold justify-end flex">
                  {orderData?.time}
                </span>
                <span className="text-gray-600">Contact Info</span>
                <div className="font-semibold">
                  <p className="justify-end flex">
                    {orderData?.branchId.email}
                    <br />
                    {orderData?.branchId.phone}
                  </p>
                </div>
                <span className="text-gray-600">Branch Address</span>
                <span className="font-semibold flex place-content-end place-items-end">
                  {orderData?.branchId.address}
                </span> */}
              </div>
            </div>
          </ScrollArea>
        </DialogContent>
      </Dialog>
    </div>
    // </div>
  );
}
