"use client";

import React from "react";
import { useLocale, useTranslations } from "next-intl";

interface CartItem {
    id: number;
    quantity: number;
    product: {
        id: number;
        name: string;
        price: number | string;
        special_price?: number | string | null;
        base_image?: { original_image_url?: string };
    };
}

interface CartTotal {
    title: string;
    value: number | string;
    formattedValue?: string;
    unformattedValue?: number | string;
}

interface OrderSidebarProps {
    items?: CartItem[];
    totals?: CartTotal[];
    isLoading?: boolean;
}

/** Translate Markatty total titles using next-intl keys */
function translateTitle(title: string, t: (key: string) => string): string {
    const keyMap: Record<string, string> = {
        "Subtotal": "subtotal",
        "Shipping & Handling": "shipping-handling",
        "Tax": "tax",
        "Discount": "discount",
        "Grand Total": "grand-total",
    };

    const key = keyMap[title];
    return key ? t(key) : title;
}

/**
 * Order sidebar — shows cart items, totals breakdown, and coupon input.
 * Accepts real data from the cartdetails API.
 */
export default function OrderSidebar({ items = [], totals = [], isLoading = false }: OrderSidebarProps) {
    const t = useTranslations("cart");
    const locale = useLocale();
    const isRtl = locale === "ar";
    const grandTotal = totals.find(t => t.title === "Grand Total");
    const subtotal = totals.find(t => t.title === "Subtotal");

    if (isLoading) {
        return (
            <div className="flex flex-col gap-6 animate-pulse">
                <div className="h-6 bg-gray-200 dark:bg-gray-700 rounded w-24" />
                <div className="space-y-3">
                    {[1, 2].map(i => (
                        <div key={i} className="flex gap-3">
                            <div className="w-14 h-14 bg-gray-200 dark:bg-gray-700 rounded-lg" />
                            <div className="flex-1 space-y-2">
                                <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-3/4" />
                                <div className="h-3 bg-gray-200 dark:bg-gray-700 rounded w-1/2" />
                            </div>
                        </div>
                    ))}
                </div>
                <div className="h-24 bg-gray-200 dark:bg-gray-700 rounded-lg" />
            </div>
        );
    }
    return (
        <div className="flex flex-col gap-6" dir={isRtl ? "rtl" : "ltr"}>
            {/* Payment Method Placeholder */}
            <div className={isRtl ? "text-right" : "text-left"}>
                <h4 className="font-bold mb-3">{t("payment-method") || "Payment Method"}</h4>
                <div className="relative">
                    <input
                        className="w-full bg-gray-50 dark:bg-gray-800 border border-border-light dark:border-border-dark rounded-lg py-3 px-4 text-sm text-gray-500 cursor-not-allowed"
                        disabled
                        placeholder={t("please-choose-shipping-address") || "Please choose shipping address"}
                        type="text"
                    />
                </div>
            </div>

            {/* Cart Items */}
            {items.length > 0 && (
                <div className="space-y-3">
                    <h4 className="font-bold text-start text-sm text-gray-700 dark:text-gray-200">
                        {t("products")} ({items.length})
                    </h4>
                    {items.map((item) => (
                        <div key={item.id} className="flex items-center gap-3 p-2 bg-gray-50 dark:bg-gray-800 rounded-lg">
                            {item.product.base_image?.original_image_url && (
                                <img
                                    src={item.product.base_image.original_image_url}
                                    alt={item.product.name}
                                    className="w-12 h-12 object-cover rounded-md border border-gray-200"
                                />
                            )}
                            <div className="flex-1 min-w-0">
                                <p className="text-xs font-medium text-gray-800 dark:text-gray-200 truncate">
                                    {item.product.name}
                                </p>
                                <p className="text-[10px] text-gray-400 mt-0.5">
                                    {t("qty")}: {Number(item.quantity) || 0}
                                </p>
                            </div>
                            <span className="text-xs font-semibold text-gray-800 dark:text-white whitespace-nowrap">
                                {item.product.special_price || item.product.price}
                            </span>
                        </div>
                    ))}
                </div>
            )}

            {/* Order Summary Box */}
            <div className="border border-border-light dark:border-border-dark rounded-lg p-5 bg-gray-50 dark:bg-gray-800/50 text-start">
                {/* Totals breakdown */}
                {totals.length > 0 ? (
                    <div className="space-y-3">
                        {totals.map((total, i) => {
                            const isGrand = total.title === "Grand Total";
                            return (
                                <div
                                    key={i}
                                    className={`flex justify-between items-center ${isGrand ? "pt-3 mt-2 border-t border-gray-200 dark:border-gray-700" : ""}`}
                                >
                                    <span className={`text-sm ${isGrand ? "font-bold text-gray-900 dark:text-white" : "text-gray-500 dark:text-gray-400"}`}>
                                        {translateTitle(total.title, t)}
                                    </span>
                                    <span className={`text-sm ${isGrand ? "font-bold text-black dark:text-white text-base" : "text-gray-700 dark:text-gray-300"}`}>
                                        {total.formattedValue || total.value}
                                    </span>
                                </div>
                            );
                        })}
                    </div>
                ) : (
                    /* Fallback when no totals available */
                    <>
                        <div className="flex justify-between items-center mb-4 pb-4 border-b border-gray-200 dark:border-gray-700">
                            <span className="text-sm font-bold text-gray-700 dark:text-gray-200">المجموع</span>
                            <span className="font-bold text-xl text-black dark:text-white">—</span>
                        </div>
                        <div className="flex justify-between items-center">
                            <span className="text-sm font-bold text-gray-700 dark:text-gray-200">المجموع الكلي</span>
                            <span className="font-bold text-xl text-black dark:text-white">—</span>
                        </div>
                    </>
                )}
            </div>

            {/* Coupon Input */}
            <div className="flex gap-2">
                <input
                    className="flex-1 border border-border-light dark:border-border-dark rounded-lg px-4 py-2 text-sm bg-white dark:bg-gray-800 focus:ring-black dark:focus:ring-gray-500 focus:border-black text-start min-h-[44px]"
                    placeholder={t("enter-coupon-code")}
                    type="text"
                />
                <button className="bg-black text-white px-6 py-2 rounded-lg font-bold hover:opacity-90 transition min-w-[80px]">
                    {t("apply")}
                </button>
            </div>
        </div>
    );
}
