'use client';

import { useGlobalContext } from '@/context/Provider';
import RadioCheck from '../../assets/images/radioCheck.png';
import RadioCheckNonVeg from '../../assets/images/radioCheckNonVeg.png';
import { FileDown, Printer } from 'lucide-react';
import { toast } from 'sonner';
import apis from '@/utils/apis';
import { useSearchParams } from 'next/navigation';
import Loader from '@/components/common/loader';
import { useState } from 'react';
import { currency } from '@/lib/utils';
import { handlePrintReceipt } from '@/utils/printReceipt';

const OrderDetail = () => {
  const { orderInfo, userInfo } = useGlobalContext();
  const searchParams = useSearchParams();
  const status = searchParams.get('status');
  const [loading, setLoading] = useState(false);

  const handleDownload = async () => {
    try {
      const orderId = orderInfo?._id;

      if (!orderId) {
        console.error('Order ID not found.');
        return;
      }
      setLoading(true);
      const response = await apis.Orders.DownloadInvoice(orderId, 'vendor');

      const fileUrl = response?.url;

      if (!fileUrl) {
        console.error('File URL not found in response.');
        return;
      }

      window.open(fileUrl, '_blank');
    } catch (error) {
      toast.error('Download failed');
    } finally {
      setLoading(false);
    }
  };

  return (
    orderInfo && (
      <div className="no-scrollbar mt-3 space-y-4 pb-6">
        <div className="flex flex-col rounded-lg border border-gray-100 bg-white shadow-lg shadow-gray-500/50">
          {(() => {
            const allItems = [
              ...(orderInfo?.cart_items || []),
              ...(orderInfo?.grocery_cart_items || []),
              ...(orderInfo?.other_cart_items || []),
            ];
            return allItems.map((item: any) => {
              return (
                <div key={item?.name} className="flex flex-col border-b p-3 last:border-b-0">
                  <div className="mb-2 flex justify-between items-center">
                    <span className="text-xs font-semibold text-[#121212]">
                      Order Id: <span className="font-bold">{orderInfo?.order_id || 'N/A'}</span>
                    </span>
                    {orderInfo?.deliver_type === 'takeaway' ? (
                      <span className="bg-blue-100 text-blue-600 text-[9px] px-2 py-0.5 rounded-full font-bold uppercase tracking-wider shadow-sm">
                        Take Away
                      </span>
                    ) : orderInfo?.deliver_type === 'driver' ? (
                      <span className="bg-green-100 text-green-600 text-[9px] px-2 py-0.5 rounded-full font-bold uppercase tracking-wider shadow-sm">
                        Driver
                      </span>
                    ) : null}
                  </div>
                  <div className="flex flex-row items-center justify-between">
                    <div className="flex flex-col items-center justify-center">
                      <div className="flex flex-row gap-2">
                        <div className="mt-[5px] h-[10px] w-[10px]">
                          <img
                            src={
                              item.food_type === 'non_veg'
                                ? RadioCheckNonVeg.src
                                : RadioCheck.src
                            }
                            width={10}
                            height={10}
                            alt={item.food_type}
                          />
                        </div>
                        <div className="flex flex-col items-start">
                          <span className="text-[16px] font-[600] text-[#121212]">
                            {item.no_of_quantity} x {item.name}
                          </span>
                          <span className="text-[16px] font-[400] text-[#808080]">
                            {item?.quantity?.name || (typeof item.quantity === 'string' ? item.quantity : "")}
                          </span>

                          {item?.variant && (
                            <span className="text-[14px] font-[400] text-[#808080] mt-1">
                              Variant: {typeof item.variant === "object" ? (item.variant.title || item.variant.name) : item.variant}
                            </span>
                          )}

                          {item?.pieces && (
                            <span className="text-[14px] font-[400] text-[#808080] mt-1">
                              Pieces: {typeof item.pieces === 'object' ? (item.pieces.name || item.pieces.title) : item.pieces}
                            </span>
                          )}

                          {item?.color_code && (
                            <div className="flex items-center gap-2 mt-1">
                              <span className="text-[14px] font-[400] text-[#808080]">
                                Color:
                              </span>
                              <div
                                className="h-4 w-4 rounded-full border border-gray-300"
                                style={{ backgroundColor: item.color_code }}
                                title={item.color_code}
                              />
                            </div>
                          )}
                          {item?.size && (
                            <span className="text-[14px] font-[400] text-[#808080] mt-1">
                              Size: {typeof item.size === 'object' ? (item.size.name || item.size.title) : item.size}
                            </span>
                          )}

                          {item?.add_ons?.length > 0 && (
                            <div className="flex flex-col mt-1">
                              <span className="text-[14px] font-[500] text-[#808080]">Add-ons:</span>
                              {item.add_ons.map((addon: any, idx: number) => (
                                <span key={idx} className="text-[13px] font-[400] text-[#808080] ml-2">
                                  + {addon.name || addon.title} ({currency}{Number(addon.price || addon.additional_price || 0).toFixed(2)})
                                </span>
                              ))}
                            </div>
                          )}

                          {item?.toppings?.length > 0 && (
                            <div className="flex flex-col mt-1">
                              <span className="text-[14px] font-[500] text-[#808080]">Toppings:</span>
                              {item.toppings.map((topping: any, idx: number) => (
                                <span key={idx} className="text-[13px] font-[400] text-[#808080] ml-2">
                                  + {topping.name || topping.title} ({currency}{Number(topping.price || topping.additional_price || 0).toFixed(2)})
                                </span>
                              ))}
                            </div>
                          )}
                        </div>
                      </div>
                    </div>

                    <div className="text-[16px] font-[400] text-[#808080]">
                      {currency}
                      {(item?.price * item?.no_of_quantity).toFixed(2)}
                    </div>
                  </div>
                  {item?.cooking_req && (
                    <div className="mt-2 flex flex-col gap-2">
                      <span className="text-[14px] font-[500] text-[var(--orange-400)]">
                        Cooking Request
                      </span>
                      <span className="text-[16px] font-[400] text-[#121212]">
                        {item?.cooking_req}
                      </span>
                    </div>
                  )}
                </div>
              );
            });
          })()}
          {orderInfo?.note_for_restaurant && (
            <div className="flex flex-col gap-2 p-4">
              <span className="text-[14px] font-[500] text-[var(--orange-400)]">
                Note for vendor
              </span>
              <span className="text-[16px] font-[400] text-[#121212]">
                {orderInfo?.note_for_restaurant}
              </span>
            </div>
          )}
        </div>
        <div className="flex flex-col rounded-lg border border-gray-100 shadow-lg shadow-gray-500/50 overflow-hidden bg-white">
          <span className="px-4 pt-4 text-[18px] font-[600] text-[#121212]">
            Receiver’s Details
          </span>
          <div className="flex flex-col gap-1 p-4">
            <span className="text-[14px] font-[500] text-[var(--orange-400)]">
              {orderInfo?.add_receiver_detail?.name}
            </span>
            <span className="text-[16px] font-[400] text-[#121212]">
              {orderInfo?.delivery_address?.name}
            </span>
          </div>
        </div>
        <div className="space-y-1.5 rounded-lg bg-[var(--orange-500)] p-4 text-sm shadow-md">
          <h2 className="text-base font-bold text-white">Payment Summary</h2>

          {orderInfo?.deliver_type !== 'takeaway' && (
            <div className="flex justify-between text-white">
              <span>Distance</span>
              <span>{orderInfo?.distance ?? 'N/A'}km</span>
            </div>
          )}

          <div className="flex justify-between text-white">
            <span>Subtotal</span>
            <span>{currency}{orderInfo?.cart_amount?.toFixed(2) ?? '0.00'}</span>
          </div>

          {orderInfo?.coupon_amount > 0 && (
            <div className="flex justify-between text-white">
              <span>Discount</span>
              <span>-{currency}{orderInfo?.coupon_amount?.toFixed(2) ?? '0.00'}</span>
            </div>
          )}

          <div className="flex justify-between text-white">
            <span>Platform fee</span>
            <span>{currency}{orderInfo?.platform_fee?.toFixed(2) ?? '0.00'}</span>
          </div>

          {orderInfo?.deliver_type !== 'takeaway' && (
            <div className="flex justify-between text-white">
              <span>Delivery fee</span>
              <span>{currency}{orderInfo?.delivery_fee?.toFixed(2) ?? '0.00'}</span>
            </div>
          )}

          <div className="flex justify-between text-white">
            <span>GST</span>
            <span>{currency}{orderInfo?.tax_amount?.toFixed(2) ?? '0.00'}</span>
          </div>

          {orderInfo?.tip_amount > 0 && (
            <div className="flex justify-between text-white">
              <span>Driver Tip</span>
              <span>{currency}{orderInfo?.tip_amount?.toFixed(2) ?? '0.00'}</span>
            </div>
          )}

          {/* {orderInfo?.sales_commission !== undefined && orderInfo?.sales_commission !== null && (
            <div className="flex justify-between text-white">
              <span>Sales commission</span>
              <span>{currency}{orderInfo?.sales_commission?.toFixed(2) ?? '0.00'}</span>
            </div>
          )} */}

          {(() => {
            const subtotal = orderInfo?.cart_amount ?? 0;
            const discount = orderInfo?.coupon_amount ?? 0;
            const platformFee = orderInfo?.platform_fee ?? 0;
            const deliveryFee = (orderInfo?.deliver_type !== 'takeaway' ? orderInfo?.delivery_fee : 0) ?? 0;
            const tax = orderInfo?.tax_amount ?? 0;
            const tip = orderInfo?.tip_amount ?? 0;
            const dynamicTotal = Math.max(0, subtotal - discount + platformFee + deliveryFee + tax + tip);
            return (
              <div className="mt-2 flex justify-between border-t text-white border-dashed border-white pt-2 font-bold">
                <span>Total</span>
                <span>{currency}{dynamicTotal.toFixed(2)}</span>
              </div>
            );
          })()}
        </div>

        <div className="space-y-3 px-1 pb-4">
          <button
            className="flex w-full items-center justify-center gap-2 rounded-lg border border-[var(--orange-500)] bg-white px-4 py-2.5 font-bold text-[var(--orange-500)] transition-all hover:bg-[var(--orange-500)]/5 active:scale-95"
            onClick={() => handlePrintReceipt(orderInfo, userInfo?.restaurant_id, currency)}
          >
            <Printer className="h-5 w-5" />
            <span>Print Receipt</span>
          </button>

          {status === 'delivered' && (
            <div className="space-y-2">
              <p className="text-sm text-gray-700 dark:text-gray-200">
                You can download your order invoice below.
              </p>
              <button
                className="flex items-center gap-2 text-white rounded bg-[var(--orange-500)] px-4 py-2 font-semibold transition-all hover:bg-[var(--orange-500)] active:scale-95"
                onClick={handleDownload}
              >
                <Loader loading={loading} />
                <FileDown className="h-5 w-5" />
                <span>Download Invoice (PDF)</span>
              </button>
            </div>
          )}
        </div>
      </div>
    )
  );
};

export default OrderDetail;
