'use client';

import { useGlobalContext } from '@/context/Provider';
import RadioCheck from '../../assets/images/radioCheck.png';
import RadioCheckNonVeg from '../../assets/images/radioCheckNonVeg.png';
import { Icons } from '@/components/icons';
import { FileDown, Printer, ChevronDown, ChevronUp } 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, useEffect } 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 [configTaxKeyword, setConfigTaxKeyword] = useState<string>('');
  const [surchargesExpanded, setSurchargesExpanded] = useState(true);
  const [extraChargesExpanded, setExtraChargesExpanded] = useState(true);

  useEffect(() => {
    const fetchConfig = async () => {
      try {
        const res = await apis.Configuration.getConfiguration();
        if (res?.data?.[0]?.tax?.tax_keyword) {
          setConfigTaxKeyword(res.data[0].tax.tax_keyword);
        }
      } catch (err) {
        console.error('Error fetching config for tax keyword:', err);
      }
    };
    fetchConfig();
  }, []);

  const taxLabel = configTaxKeyword || orderInfo?.tax_keyword || 'GST';

  const surchargesList = orderInfo?.surcharges?.filter(
    (item: any) => item.charge_type === 'surcharge' || item.surcharge_type === 'surcharge' || (!item.charge_type && !item.surcharge_type)
  ) || [];
  const extraChargesList = orderInfo?.surcharges?.filter(
    (item: any) => item.charge_type === 'extra_charge' || item.surcharge_type === 'extra_charge'
  ) || [];

  const surchargesTotal = surchargesList.reduce((sum: number, item: any) => sum + (item.amount || 0), 0);
  const extraChargesTotal = extraChargesList.reduce((sum: number, item: any) => sum + (item.amount || 0), 0);

  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-[14px] w-[14px] flex items-center justify-center">
                          <Icons.FoodTypeIcon type={item.food_type} className="h-[14px] w-[14px] shrink-0" />
                        </div>
                        <div className="flex flex-col items-start">
                          <span className="text-[16px] font-[600] text-[#121212]">
                            {item.no_of_quantity} x {item.name}
                          </span>
                          {(() => {
                            const qtyStr = item?.quantity?.name || (typeof item?.quantity === 'string' || typeof item?.quantity === 'number' ? item.quantity : '');
                            const unitStr = item?.unit;

                            let displayUnit = '';
                            if (unitStr) {
                              if (qtyStr && String(unitStr).toLowerCase().includes(String(qtyStr).toLowerCase())) {
                                displayUnit = unitStr;
                              } else {
                                displayUnit = `${qtyStr || ''} ${unitStr}`.trim();
                              }
                            } else {
                              displayUnit = qtyStr;
                            }

                            return displayUnit ? (
                              <span className="text-[16px] font-[400] text-[#808080]">
                                {displayUnit}
                              </span>
                            ) : null;
                          })()}

                          {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) => {
                                const addonQty = addon?.selected_quantity || addon?.quantity || addon?.no_of_quantity;
                                return (
                                  <span key={idx} className="text-[13px] font-[400] text-[#808080] ml-2">
                                    + {addon.name || addon.title}{addonQty ? ` (x${addonQty})` : ''} ({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) => {
                                const toppingQty = topping?.selected_quantity || topping?.quantity || topping?.no_of_quantity;
                                return (
                                  <span key={idx} className="text-[13px] font-[400] text-[#808080] ml-2">
                                    + {topping.name || topping.title}{toppingQty ? ` (x${toppingQty})` : ''} ({currency}{Number(topping.price || topping.additional_price || 0).toFixed(2)})
                                  </span>
                                );
                              })}
                            </div>
                          )}

                          {item?.other_add_ons?.length > 0 && (
                            <div className="flex flex-col mt-1">
                              <span className="text-[14px] font-[500] text-[#808080]">Other Add-ons:</span>
                              {item.other_add_ons.map((otherAddon: any, idx: number) => {
                                const otherQty = otherAddon?.selected_quantity || otherAddon?.quantity || otherAddon?.no_of_quantity;
                                return (
                                  <span key={idx} className="text-[13px] font-[400] text-[#808080] ml-2">
                                    + {otherAddon.name || otherAddon.title}{otherQty ? ` (x${otherQty})` : ''} ({currency}{Number(otherAddon.price || otherAddon.additional_price || 0).toFixed(2)})
                                  </span>
                                );
                              })}
                            </div>
                          )}
                        </div>
                      </div>
                    </div>

                    <div className="text-[16px] font-[400] text-[#808080]">
                      {currency}
                      {(item?.total_price !== undefined && item?.total_price !== null ? Number(item.total_price) : (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>
          )}

          {Number(orderInfo?.platform_fee || 0) > 0 && (
            <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>
          )}

          {surchargesList.length > 0 && (
            <div className="flex flex-col text-white">
              <div
                onClick={() => setSurchargesExpanded(!surchargesExpanded)}
                className="flex items-center justify-between w-full py-1 cursor-pointer select-none"
              >
                <div className="flex items-center gap-2">
                  <span>Surcharges</span>
                  {surchargesExpanded ? (
                    <ChevronUp className="h-4 w-4 text-white/80" />
                  ) : (
                    <ChevronDown className="h-4 w-4 text-white/80" />
                  )}
                </div>
                <span className="font-semibold">
                  {currency}{surchargesTotal.toFixed(2)}
                </span>
              </div>

              {surchargesExpanded && (
                <div className="mt-1 space-y-1 pl-2">
                  {surchargesList.map((charge: any) => (
                    <div
                      key={charge._id || charge.name}
                      className="flex justify-between items-center bg-white/10 border border-white/10 rounded px-3 py-1.5 text-xs text-white/90"
                    >
                      <span>{charge.name}</span>
                      <span className="font-medium">
                        {currency}{Number(charge.amount || 0).toFixed(2)}
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {extraChargesList.length > 0 && (
            <div className="flex flex-col text-white">
              <div
                onClick={() => setExtraChargesExpanded(!extraChargesExpanded)}
                className="flex items-center justify-between w-full py-1 cursor-pointer select-none"
              >
                <div className="flex items-center gap-2">
                  <span>Extra Charges</span>
                  {extraChargesExpanded ? (
                    <ChevronUp className="h-4 w-4 text-white/80" />
                  ) : (
                    <ChevronDown className="h-4 w-4 text-white/80" />
                  )}
                </div>
                <span className="font-semibold">
                  {currency}{extraChargesTotal.toFixed(2)}
                </span>
              </div>

              {extraChargesExpanded && (
                <div className="mt-1 space-y-1 pl-2">
                  {extraChargesList.map((charge: any) => (
                    <div
                      key={charge._id || charge.name}
                      className="flex justify-between items-center bg-white/10 border border-white/10 rounded px-3 py-1.5 text-xs text-white/90"
                    >
                      <span>{charge.name}</span>
                      <span className="font-medium">
                        {currency}{Number(charge.amount || 0).toFixed(2)}
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {Number(orderInfo?.tax_amount || 0) > 0 && (
            <div className="flex justify-between text-white">
              <span>{taxLabel}</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 = orderInfo?.total_amount !== undefined && orderInfo?.total_amount !== null && orderInfo?.total_amount > 0
              ? orderInfo.total_amount
              : Math.max(0, subtotal - discount + platformFee + deliveryFee + tax + tip + surchargesTotal + extraChargesTotal);
            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;
