import React from "react";
import { currency } from "@/lib/utils";
import { Minus, Plus } from "lucide-react";
import { AppDispatch } from "@/store/store";
import { useDispatch } from "react-redux";
import {
  removeCartItem,
  updateCartItem,
} from "@/store/actions/user/userAction";

export default function FoodItemsContainer({ data }: any) {
  const dispatch: AppDispatch = useDispatch();

  // ✅ Helper to compute single item total (no quantity)
  const computeTotalPrice = (item: any) => {
    // Determine the base price of the portion (portion = size, quantity, or pieces)
    const variant = item.size || item.quantity || item.pieces;

    let variantBasePrice = 0;
    if (variant?.final_price !== undefined && variant?.final_price !== null) {
      variantBasePrice = parseFloat(variant.final_price);
    } else {
      // Logic for older items or items without final_price
      const dishBasePrice = parseFloat(item.original_dish_price || item.original_price || item.base_price || 0);
      const addPrice = parseFloat(variant?.add_price || 0);
      variantBasePrice = dishBasePrice + addPrice;
    }

    // Apply discount if present
    let effectiveBasePrice = variantBasePrice;
    if (item.has_discount && item.original_price && item.price) {
      // We can infer the discount from the stored price vs expected original total if we had it,
      // but it's safer to store the discount percentage or just use the ratio of stored prices.
      // For now, let's use the ratio of item.price (single item total discounted) 
      // to the sum of original components if we can't find a better way.
      // Actually, RestroItems now saves base_price as original portion price.
      const originalPortionPrice = parseFloat(item.original_price || variantBasePrice || 0);
      const discountedItemTotal = parseFloat(item.price || 0);

      // If we don't have enough info to recalculate perfectly, 
      // we might just trust the stored 'item.price' for a single unit.
      // But we need to handle add-ons too.
    }

    // Simplest reliable way: If we are just changing quantity, 
    // we can use the stored 'item.price' which was correctly calculated in RestroItems.
    // However, if we wanted to allow adding/removing add-ons here, we'd need more.
    // Since this component only changes quantity, we can return item.price directly.
    return parseFloat(item.price || 0);
  };

  // ✅ Total with quantity
  const computeTotalWithQuantity = (item: any, quantity: number) => {
    return Number((computeTotalPrice(item) * quantity).toFixed(2));
  };

  const handleQuantityChange = (item: any, increment: boolean) => {
    if (!increment && item.no_of_quantity === 1) {
      dispatch(removeCartItem(item?.cart_item_key || item?.food_id));
      return;
    }

    const updatedQuantity = increment
      ? item.no_of_quantity + 1
      : Math.max(item.no_of_quantity - 1, 1);

    const pricePerItem = computeTotalPrice(item);
    const totalPrice = computeTotalWithQuantity(item, updatedQuantity);

    // ✅ Updated cart item structure
    const updatedItem = {
      ...item,
      no_of_quantity: updatedQuantity,
      price: pricePerItem, // single item price
      priceQuantity: totalPrice, // full quantity price
    };

    dispatch(updateCartItem(updatedItem));
  };

  return (
    <div className="w-full flex flex-wrap gap-2">
      {data?.length > 0 &&
        data.map((item: any, index: number) => {
          const variant = item.quantity || item.size || item.pieces;
          return (
            <div
              key={index}
              className="flex-1 min-w-[45%] max-sm:min-w-full bg-white rounded-lg shadow-sm p-4 border"
            >
              <div className="flex justify-between items-start mb-1">
                <div className="flex items-start">
                  <div className={`w-4 h-4 rounded-full flex items-center justify-center mr-2 mt-1 border ${item.food_type === 'veg' ? 'bg-green-500 border-green-700' : 'bg-red-500 border-red-700'}`}>
                    <div className="w-2 h-2 bg-white rounded-full"></div>
                  </div>
                  <div>
                    <h3 className="font-medium text-gray-800">{item.name}</h3>
                    <p className="text-gray-500 text-sm">{variant?.name}</p>

                    {/* Display customizations */}
                    <div className="flex flex-wrap gap-1 mt-1">
                      {item.add_ons?.map((add: any, idx: number) => (
                        <span key={idx} className="text-[10px] bg-gray-100 px-1 rounded text-gray-600">
                          {add.name}
                        </span>
                      ))}
                      {item.toppings?.map((top: any, idx: number) => (
                        <span key={idx} className="text-[10px] bg-gray-100 px-1 rounded text-gray-600">
                          {top.name}
                        </span>
                      ))}
                      {item.other_add_ons?.map((other: any, idx: number) => (
                        <span key={idx} className="text-[10px] bg-gray-100 px-1 rounded text-gray-600">
                          {other.name}
                        </span>
                      ))}
                    </div>
                  </div>
                </div>

                <div className="flex flex-col items-end">
                  <div className="flex items-center mb-2">
                    <button
                      className="w-7 h-7 border border-primary rounded-md flex items-center justify-center text-primary"
                      onClick={() => handleQuantityChange(item, false)}
                    >
                      <Minus size={16} />
                    </button>
                    <span className="mx-2 text-gray-800">
                      {item.no_of_quantity}
                    </span>
                    <button
                      className="w-7 h-7 border border-primary rounded-md flex items-center justify-center text-primary"
                      onClick={() => handleQuantityChange(item, true)}
                    >
                      <Plus size={16} />
                    </button>
                  </div>

                  {/* ✅ Show full quantity price */}
                  <span className="font-medium text-gray-800">
                    {currency}{computeTotalWithQuantity(item, item.no_of_quantity).toFixed(2)}
                  </span>
                </div>
              </div>

              {item?.cooking_req && (
                <div className="mt-4">
                  <p className="text-neutral-900 text-sm mb-1 font-semibold">
                    Cooking requests
                  </p>
                  <p className="text-gray-700 text-sm italic">
                    "{item?.cooking_req}"
                  </p>
                </div>
              )}
            </div>
          );
        })}
    </div>
  );
}
