import React from 'react';
import { usePage } from '@inertiajs/react';
import { Button } from "@/Components/ui/button";
import { Badge } from "@/Components/ui/badge";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/Components/ui/tooltip";
import { Minus, Plus, Tag, Info } from "lucide-react";
import { useTranslation } from '@/hooks/useTranslation';

export default function PricingAndQuantity({ product, quantity, setQuantity, selectedVariations, setSelectedVariations, isOwner }) {
    const { activeCurrency, currencies } = usePage().props;
    const { t } = useTranslation();
    
    const currentQuantity = Number(quantity);
    const minQty = Number(product.moq || 1);
    const maxQty = Number(product.stock || 0);

    const productRate = parseFloat(currencies?.find(c => c.code === (product.currency_code || 'USD'))?.exchange_rate || 1);
    
    let baseUsdPrice = parseFloat(product.price || 0);
    
    if (product.variations) {
        Object.values(selectedVariations).forEach(opt => {
            if (opt && opt.additional_price) {
                baseUsdPrice += (parseFloat(opt.additional_price) / productRate);
            }
        });
    }

    const targetRate = activeCurrency ? parseFloat(activeCurrency.exchange_rate) : 1;
    const currencySymbol = activeCurrency?.symbol || '$';
    const activeDisplayPrice = baseUsdPrice * targetRate;
    
    const productDiscount = parseFloat(product.discount_percentage) || 0;
    const sellerDiscount = parseFloat(product.seller?.flash_sale_percentage) || 0;
    const discountPercent = Math.max(productDiscount, sellerDiscount);

    const minOrderOriginal = parseFloat(product.original_min_order_amount || product.min_order_amount_for_discount) || 0;
    const minOrderQtyThreshold = minOrderOriginal > 0 ? Math.ceil((minOrderOriginal / productRate) / baseUsdPrice) : 1;
    const isDiscountActive = discountPercent > 0 && currentQuantity >= minOrderQtyThreshold;
    
    const discountedPrice = activeDisplayPrice - (activeDisplayPrice * discountPercent / 100);
    const finalUnitPrice = isDiscountActive ? discountedPrice : activeDisplayPrice;
    const subtotal = finalUnitPrice * currentQuantity;

    const hasVariations = product.variations && product.variations.length > 0;

    return (
        <>
            <div className="bg-orange-500/5 border border-orange-500/20 rounded-xl p-5 mb-6 relative mt-2">
                {product.original_price && product.currency_code !== activeCurrency?.code && (
                    <div className="absolute top-4 right-4">
                        <TooltipProvider>
                            <Tooltip>
                                <TooltipTrigger type="button">
                                    <Info className="w-4 h-4 text-muted-foreground hover:text-foreground cursor-help" />
                                </TooltipTrigger>
                                <TooltipContent>
                                    <p className="text-xs">
                                        {t('Original Base Price: :price :currency', { 
                                            price: product.original_price, 
                                            currency: product.currency_code 
                                        })}
                                    </p>
                                </TooltipContent>
                            </Tooltip>
                        </TooltipProvider>
                    </div>
                )}

                <div className="flex flex-col sm:flex-row sm:items-end gap-2 mb-2">
                    {isDiscountActive && (
                        <p className="text-muted-foreground text-lg line-through font-medium">
                            {currencySymbol}{activeDisplayPrice.toFixed(2)}
                        </p>
                    )}
                    <p className="text-orange-600 text-3xl md:text-4xl font-extrabold tracking-tight">
                        {currencySymbol}{finalUnitPrice.toFixed(2)}
                    </p>
                    <p className="text-sm text-muted-foreground sm:mb-1">{t('/ unit')}</p>
                    
                    {isDiscountActive && (
                        <Badge className="bg-red-500 hover:bg-red-600 text-white ml-2 mb-1">
                            {t(':percent% OFF', { percent: discountPercent })}
                        </Badge>
                    )}
                </div>
                
                {product.coupon_code && (
                    <div className="mt-2 mb-3 inline-flex items-center gap-2 bg-green-500/10 border border-green-500/20 text-green-700 px-3 py-1 rounded-md text-xs font-bold">
                        <Tag className="w-3 h-3" /> {t('Use Coupon:')} <span className="font-mono uppercase tracking-wider">{product.coupon_code}</span>
                    </div>
                )}
                
                <p className="text-xs font-medium text-orange-600/80 mt-1">
                    {t('Minimum Order Quantity: :moq units', { moq: minQty })}
                </p>
            </div>

            {hasVariations && (
                <div className="space-y-5 mb-6 bg-muted/10 border border-border/50 rounded-xl p-4 sm:p-5">
                    {product.variations.map((v, i) => {
                        const isImageVariation = v.options.some(opt => opt.image_path);
                        return (
                            <div key={i} className="space-y-2">
                                <p className="text-sm font-bold text-foreground">
                                    {t(v.name)}: <span className="text-muted-foreground font-normal ml-1">{selectedVariations[v.name]?.value || t('Select Option')}</span>
                                </p>
                                
                                <div className="flex flex-wrap gap-2.5">
                                    {v.options.map((opt, j) => {
                                        const isSelected = selectedVariations[v.name]?.value === opt.value;
                                        const extraPrice = (parseFloat(opt.additional_price || 0) / productRate) * targetRate;
                                        
                                        if (isImageVariation) {
                                            return (
                                                <button
                                                    key={j}
                                                    onClick={() => setSelectedVariations(prev => ({...prev, [v.name]: opt}))}
                                                    title={opt.value}
                                                    className={`relative w-12 h-12 sm:w-14 sm:h-14 rounded-md overflow-hidden border-2 transition-all p-0.5 bg-white ${
                                                        isSelected ? 'border-primary ring-2 ring-primary/20' : 'border-border hover:border-primary/50'
                                                    }`}
                                                >
                                                    {opt.image_path ? (
                                                        <img src={`/storage/${opt.image_path}`} className="w-full h-full object-cover rounded-sm" alt={opt.value}/>
                                                    ) : (
                                                        <div className="w-full h-full bg-muted flex items-center justify-center text-[9px] font-medium text-muted-foreground leading-tight text-center">{opt.value}</div>
                                                    )}
                                                </button>
                                            );
                                        }

                                        return (
                                            <button
                                                key={j}
                                                onClick={() => setSelectedVariations(prev => ({...prev, [v.name]: opt}))}
                                                className={`relative flex items-center gap-1.5 border transition-all px-3 py-1.5 rounded-lg text-sm font-semibold ${
                                                    isSelected 
                                                        ? 'border-primary bg-primary/10 text-primary shadow-sm' 
                                                        : 'border-border/60 hover:border-primary/50 bg-background text-foreground'
                                                }`}
                                            >
                                                <span>{opt.value}</span>
                                                {extraPrice > 0 && <span className="text-[10px] text-muted-foreground ml-1">+{currencySymbol}{extraPrice.toFixed(2)}</span>}
                                            </button>
                                        );
                                    })}
                                </div>
                            </div>
                        );
                    })}
                </div>
            )}

            {!isOwner && (
                <div className="mb-6 flex flex-col sm:flex-row sm:items-center justify-between gap-4 p-4 border border-border/50 rounded-xl bg-card shadow-sm">
                    <div className="flex items-center gap-4">
                        <span className="text-sm font-semibold text-muted-foreground w-16">{t('Quantity')}</span>
                        <div className="flex items-center gap-1 border border-border/60 rounded-lg p-1 bg-muted/20">
                            <Button 
                                variant="ghost" size="icon" className="h-8 w-8 rounded-md hover:bg-muted" 
                                onClick={() => setQuantity(Math.max(minQty, currentQuantity - 1))} 
                                disabled={currentQuantity <= minQty}
                            >
                                <Minus className="w-4 h-4" />
                            </Button>
                            <span className="w-12 text-center font-bold text-base">{currentQuantity}</span>
                            <Button 
                                variant="ghost" size="icon" className="h-8 w-8 rounded-md hover:bg-muted" 
                                onClick={() => setQuantity(Math.min(maxQty, currentQuantity + 1))} 
                                disabled={currentQuantity >= maxQty}
                            >
                                <Plus className="w-4 h-4" />
                            </Button>
                        </div>
                        <span className="text-xs text-muted-foreground">
                            {currentQuantity >= maxQty && <span className="text-orange-500 font-bold">{t('Max stock')}</span>}
                        </span>
                    </div>

                    <div className="text-right border-t sm:border-t-0 sm:border-l pt-3 sm:pt-0 sm:pl-4">
                        <p className="text-xs text-muted-foreground font-semibold uppercase tracking-wider">{t('Subtotal')}</p>
                        <p className="text-xl font-black text-foreground">{currencySymbol}{subtotal.toFixed(2)}</p>
                    </div>
                </div>
            )}
        </>
    );
}