import React, { useState, useEffect } from 'react';
import { Link, usePage, router } from '@inertiajs/react';
import { Card, CardContent } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { Badge } from "@/Components/ui/badge";
import { toast } from 'sonner';
import { useTranslation } from '@/hooks/useTranslation';
import {
    Drawer, DrawerClose, DrawerContent, DrawerHeader, DrawerTitle, DrawerFooter, DrawerTrigger,
} from "@/Components/ui/drawer";
import {
    DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger,
} from "@/Components/ui/dropdown-menu";
import { 
    Truck, CheckCircle2, XCircle, MoreVertical, Printer, MessageSquare, 
    MapPin, FileText, CalendarDays, PenSquare, ExternalLink, Copy, CreditCard, AlertCircle, Loader2
} from 'lucide-react';

export default function OrderCard({ 
    order, 
    setPrintModal, 
    handleMessageBuyer, 
    updateSimpleStatus, 
    openTrackingModal,
    processingId 
}) {
    const { activeCurrency, currencies } = usePage().props;
    const { t } = useTranslation();
    
    const [isDeclining, setIsDeclining] = useState(false);
    
    // --- FIX: Track exactly WHICH action is processing ---
    const [actionLoading, setActionLoading] = useState(null);

    // Reset local loading state when the global processingId clears
    useEffect(() => {
        if (processingId !== order.id) {
            setActionLoading(null);
        }
    }, [processingId, order.id]);

    const handleStatusChange = (newStatus) => {
        setActionLoading(newStatus);
        updateSimpleStatus(order, newStatus);
    };
    // ----------------------------------------------------

    const orderRate = currencies?.find(c => c.code === order.currency)?.exchange_rate || 1;
    const targetRate = activeCurrency ? parseFloat(activeCurrency.exchange_rate) : 1;
    const currencySymbol = activeCurrency?.symbol || '$';
    const displayTotal = (parseFloat(order.total_amount) / orderRate) * targetRate;

    const orderDate = new Date(order.created_at).toLocaleDateString(undefined, {
        year: 'numeric', month: 'short', day: 'numeric'
    });

    const formatGateway = (code) => {
        if (!code) return t('N/A');
        const gateways = { manual: t('Manual / Bank'), sslcommerz: 'SSLCommerz', bkash: 'bKash', stripe: 'Stripe', paypal: 'PayPal' };
        return gateways[code] || code.charAt(0).toUpperCase() + code.slice(1);
    };

    const copyToClipboard = () => {
        const addressText = `${order.buyer?.name || ''}\n${order.shipping_address || t('No address provided')}\n${order.buyer?.country?.name || ''}`.trim();
        navigator.clipboard.writeText(addressText);
        toast.success(t('Shipping address copied to clipboard!'));
    };

    const handleDeclineRefund = () => {
        setIsDeclining(true);
        router.post(route('seller.orders.decline-refund', order.id), {}, { 
            preserveScroll: true,
            onFinish: () => setIsDeclining(false)
        });
    };

    const getStatusBadge = (status) => {
        const styles = { 
            pending: 'bg-zinc-500/10 text-zinc-600 border-zinc-500/20', 
            processing: 'bg-blue-500/10 text-blue-600 border-blue-500/20', 
            shipped: 'bg-amber-500/10 text-amber-600 border-amber-500/20', 
            completed: 'bg-green-500/10 text-green-600 border-green-500/20', 
            cancelled: 'bg-red-500/10 text-red-600 border-red-500/20', 
            refunded: 'bg-purple-500/10 text-purple-600 border-purple-500/20' 
        };
        const labels = { pending: t('Pending'), processing: t('Processing'), shipped: t('Shipped'), completed: t('Completed'), cancelled: t('Cancelled'), refunded: t('Refunded') };
        return <Badge variant="outline" className={`${styles[status]} uppercase tracking-wider font-bold text-[10px]`}>{labels[status] || status}</Badge>;
    };

    return (
        <Card className="border-border/50 shadow-sm rounded-xl overflow-visible">
            
            <div className="bg-muted/20 px-4 py-3 border-b rounded-t-xl flex flex-wrap gap-4 items-center justify-between text-sm">
                <div className="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-4">
                    <span className="font-bold flex items-center gap-2">
                        {t('ID')}: <span className="text-primary">{order.order_number}</span>
                    </span>
                    <span className="hidden sm:block text-border">|</span>
                    <span className="text-muted-foreground flex items-center gap-1.5 text-xs">
                        <CalendarDays className="w-3.5 h-3.5" /> {orderDate}
                    </span>
                </div>
                
                <div className="flex items-center gap-3 whitespace-nowrap">
                    {getStatusBadge(order.status)}
                    <Button variant="ghost" size="sm" className="h-8 gap-1 text-muted-foreground hover:text-primary" onClick={() => setPrintModal({ open: true, order })}>
                        <Printer className="w-4 h-4" /> <span className="hidden sm:inline">{t('Print Slip')}</span>
                    </Button>
                </div>
            </div>

            {/* --- BUYER REFUND WARNING BANNER --- */}
            {order.is_refund_requested && order.status !== 'refunded' && order.status !== 'cancelled' && (
                <div className="bg-red-500/10 border-b border-red-500/20 p-4">
                    <div className="flex flex-col xl:flex-row xl:items-center justify-between gap-4">
                        <div>
                            <h4 className="font-bold text-red-600 flex items-center gap-2">
                                <AlertCircle className="w-5 h-5" /> {t('Buyer Requested a Refund')}
                            </h4>
                            <p className="text-sm text-red-900/80 dark:text-red-300 mt-1">
                                <strong>{t('Reason')}:</strong> {order.refund_reason}
                            </p>
                            <p className="text-xs text-muted-foreground mt-1">
                                {t('Please use the chat to discuss return addresses or issues before approving.')}
                            </p>
                        </div>
                        <div className="flex flex-wrap items-center gap-2 shrink-0">
                            <Button size="sm" variant="outline" disabled={isDeclining || processingId === order.id} className="border-red-500/30 text-red-600 bg-white dark:bg-black hover:bg-red-500/10" onClick={handleDeclineRefund}>
                                {isDeclining && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                                {t('Decline')}
                            </Button>
                            <Button size="sm" disabled={isDeclining || processingId === order.id} onClick={() => handleMessageBuyer(order.buyer_id, order.items?.[0]?.product_id)} className="bg-white dark:bg-black text-foreground border shadow-sm hover:bg-muted">
                                <MessageSquare className="w-4 h-4 mr-2" /> {t('Chat')}
                            </Button>
                            <Button size="sm" disabled={processingId === order.id || isDeclining} className="bg-red-600 hover:bg-red-700 text-white" onClick={() => handleStatusChange('refunded')}>
                                {actionLoading === 'refunded' && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                                {t('Approve Refund')}
                            </Button>
                        </div>
                    </div>
                </div>
            )}
            {/* -------------------------------------- */}

            <CardContent className="p-0">
                <div className="flex flex-col lg:flex-row">
                    <div className="flex-1 p-4 lg:border-r border-border/50 space-y-4 min-w-0">
                        {order.items?.map(item => {
                            const displayUnitPrice = (parseFloat(item.unit_price) / orderRate) * targetRate;
                            const hasVariations = item.selected_variations && Object.keys(item.selected_variations).length > 0;

                            return (
                                <div key={item.id} className="flex gap-4 min-w-0">
                                    <div className="w-16 h-16 sm:w-20 sm:h-20 border rounded-lg p-1 bg-white shrink-0 overflow-hidden">
                                        <img src={item.product?.images?.[0] ? `/storage/${item.product.images[0].path}` : '/placeholder.jpg'} alt="Product" className="w-full h-full object-contain" />
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <Link href={route('product.view', `${item.product?.slug}_${item.product?.id}`)} className="font-bold text-sm truncate block hover:text-primary transition-colors">
                                            {item.product?.title || t('Product Removed')}
                                        </Link>
                                        
                                        <div className="text-xs text-muted-foreground mt-1 font-medium">
                                            {currencySymbol}{displayUnitPrice.toFixed(2)} × {item.quantity}
                                        </div>

                                        {hasVariations && (
                                            <div className="mt-2 bg-amber-500/10 border border-amber-500/30 p-2.5 rounded-lg flex items-start justify-between gap-2 shadow-sm">
                                                <div>
                                                    <span className="flex items-center gap-1.5 text-[10px] font-black text-amber-700 dark:text-amber-500 uppercase tracking-wider mb-1.5">
                                                        <AlertCircle className="w-3.5 h-3.5" /> {t('Buyer Requested Variations')}
                                                    </span>
                                                    <div className="flex flex-wrap gap-1.5">
                                                        {Object.entries(item.selected_variations).map(([key, opt]) => (
                                                            <span key={key} className="text-xs bg-white dark:bg-black border border-amber-500/30 px-2 py-0.5 rounded font-bold text-foreground">
                                                                {t(key)}: <span className="text-amber-600">{opt.value}</span>
                                                            </span>
                                                        ))}
                                                    </div>
                                                </div>
                                                <Button 
                                                    variant="ghost" size="icon" className="h-7 w-7 text-amber-700 hover:bg-amber-500/20 shrink-0"
                                                    onClick={() => {
                                                        const text = Object.entries(item.selected_variations).map(([k, v]) => `${k}: ${v.value}`).join(', ');
                                                        navigator.clipboard.writeText(text);
                                                        toast.success(t('Variations copied to clipboard!'));
                                                    }}
                                                    title={t('Copy Variations')}
                                                >
                                                    <Copy className="w-3.5 h-3.5" />
                                                </Button>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            );
                        })}
                        
                        {order.seller_notes && (
                            <div className="mt-3 bg-muted/30 p-3 rounded-lg border text-xs">
                                <span className="font-bold text-muted-foreground">{t('Note to Buyer')}:</span> {order.seller_notes}
                            </div>
                        )}
                    </div>

                    <div className="w-full lg:w-64 p-4 lg:border-r border-border/50 text-sm space-y-4 bg-muted/5 min-w-0 flex flex-col justify-center">
                        <div className="min-w-0">
                            <div className="font-bold text-muted-foreground text-[10px] uppercase tracking-wider mb-1">{t('Buyer Details')}</div>
                            <div className="font-semibold flex items-center justify-between gap-2">
                                <span className="truncate">{order.buyer?.name}</span>
                                <Button size="icon" variant="ghost" className="h-6 w-6 rounded-full text-blue-500 hover:bg-blue-500/10 shrink-0" onClick={() => handleMessageBuyer(order.buyer_id, order.items?.[0]?.product_id)}>
                                    <MessageSquare className="w-3 h-3" />
                                </Button>
                            </div>
                            <div className="text-muted-foreground truncate text-xs">{order.buyer?.email}</div>
                        </div>
                        <div className="min-w-0 border-t border-border/50 pt-3">
                            <div className="font-bold text-muted-foreground text-[10px] uppercase tracking-wider mb-1 flex items-center justify-between">
                                <span className="flex items-center gap-1"><MapPin className="w-3 h-3" /> {t('Shipping To')}</span>
                                <Button variant="ghost" size="icon" className="h-6 w-6 text-muted-foreground hover:text-primary hover:bg-primary/10" onClick={copyToClipboard} title={t('Copy Address')}>
                                    <Copy className="w-3.5 h-3.5" />
                                </Button>
                            </div>
                            <div className="text-muted-foreground text-xs whitespace-normal leading-relaxed line-clamp-3 pr-2">
                                {order.shipping_address || t('Address not provided')}
                            </div>
                            <div className="text-muted-foreground text-xs truncate font-bold mt-1">
                                {order.buyer?.country?.name}
                            </div>
                        </div>
                    </div>

                    <div className="w-full lg:w-64 p-4 flex flex-col justify-center items-center text-center">
                        <div className="font-bold text-muted-foreground text-[10px] uppercase tracking-wider mb-1">{t('Order Total')}</div>
                        <div className="text-2xl font-black text-orange-600 mb-1">
                            {currencySymbol}{displayTotal.toFixed(2)}
                        </div>

                        <div className="flex items-center gap-1.5 text-[10px] font-bold text-muted-foreground bg-muted/50 px-2.5 py-1 rounded-md mb-3 border border-border/50">
                            <CreditCard className="w-3 h-3" />
                            {t('Paid via')}: <span className="text-foreground uppercase tracking-wide">{formatGateway(order.payment_gateway)}</span>
                        </div>

                        {order.currency !== activeCurrency?.code && (
                            <div className="text-[10px] font-bold text-muted-foreground mb-3 bg-muted/50 px-2 py-0.5 rounded">
                                {t('Original')}: {parseFloat(order.total_amount).toFixed(2)} {order.currency}
                            </div>
                        )}
                        
                        <div className="w-full space-y-2">
                            {order.status === 'pending' && (
                                <Button disabled={processingId === order.id} className="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-xl" onClick={() => handleStatusChange('processing')}>
                                    {actionLoading === 'processing' && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                                    {t('Confirm Payment')}
                                </Button>
                            )}
                            
                            {order.status === 'processing' && (
                                <Button className="w-full bg-orange-500 hover:bg-orange-600 text-white font-bold rounded-xl" onClick={() => openTrackingModal(order)}>
                                    <Truck className="w-4 h-4 mr-2" /> {t('Ship Order')}
                                </Button>
                            )}
                            
                            {order.status === 'shipped' && (
                                <div className="text-xs bg-green-500/10 text-green-700 p-2 rounded-lg border border-green-500/20 font-medium">
                                    {order.tracking_url ? (
                                        <a href={order.tracking_url} target="_blank" rel="noreferrer" className="flex items-center justify-center gap-1 hover:underline">
                                            {t('Tracking')}: <span className="font-mono font-bold truncate max-w-[100px]">{order.tracking_number}</span> <ExternalLink className="w-3 h-3"/>
                                        </a>
                                    ) : (
                                        <span>{t('Tracking')}: <span className="font-mono font-bold truncate">{order.tracking_number}</span></span>
                                    )}
                                    <div className="text-muted-foreground mt-0.5">{order.shipping_carrier}</div>
                                </div>
                            )}

                            <div className="hidden md:block">
                                <DropdownMenu>
                                    <DropdownMenuTrigger disabled={processingId === order.id} className="w-full h-10 inline-flex items-center justify-center rounded-xl border bg-background px-4 text-sm font-medium hover:bg-muted transition-colors outline-none disabled:opacity-50">
                                        {t('Actions')} <MoreVertical className="ml-2 h-4 w-4" />
                                    </DropdownMenuTrigger>
                                    <DropdownMenuContent align="end" className="w-56 z-[9999] rounded-xl shadow-xl p-1">
                                        <DropdownMenuLabel className="text-xs text-muted-foreground uppercase px-2 py-1.5">{t('Manage Order')}</DropdownMenuLabel>
                                        <DropdownMenuSeparator />
                                        <DropdownMenuItem className="cursor-pointer py-2 px-3" onClick={() => setPrintModal({ open: true, order })}><FileText className="w-4 h-4 mr-2" /> {t('View/Print Invoice')}</DropdownMenuItem>
                                        {order.status === 'processing' && <DropdownMenuItem className="cursor-pointer py-2 px-3" onClick={() => openTrackingModal(order)}><Truck className="w-4 h-4 mr-2 text-orange-500" /> {t('Ship Order')}</DropdownMenuItem>}
                                        {order.status === 'shipped' && (
                                            <>
                                                <DropdownMenuItem className="cursor-pointer py-2 px-3" onClick={() => openTrackingModal(order)}><PenSquare className="w-4 h-4 mr-2 text-muted-foreground" /> {t('Edit Tracking Info')}</DropdownMenuItem>
                                                <DropdownMenuItem 
                                                    className="cursor-pointer py-2 px-3 text-green-600 font-bold" 
                                                    onClick={(e) => { e.preventDefault(); handleStatusChange('completed'); }}
                                                >
                                                    {actionLoading === 'completed' ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <CheckCircle2 className="w-4 h-4 mr-2" />} 
                                                    {t('Mark as Completed')}
                                                </DropdownMenuItem>
                                            </>
                                        )}

                                        {order.status === 'pending' && (
                                            <>
                                                <DropdownMenuSeparator />
                                                <DropdownMenuItem 
                                                    className="cursor-pointer py-2 px-3 text-red-600 font-bold focus:bg-red-500/10 focus:text-red-700" 
                                                    onClick={(e) => { e.preventDefault(); handleStatusChange('cancelled'); }}
                                                >
                                                    {actionLoading === 'cancelled' ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <XCircle className="w-4 h-4 mr-2" />} 
                                                    {t('Cancel Order')}
                                                </DropdownMenuItem>
                                            </>
                                        )}
                                    </DropdownMenuContent>
                                </DropdownMenu>
                            </div>

                            <div className="md:hidden">
                                <Drawer>
                                    <DrawerTrigger asChild>
                                        <Button variant="outline" disabled={processingId === order.id} className="w-full rounded-xl gap-2">{t('Actions')} <MoreVertical className="w-4 h-4" /></Button>
                                    </DrawerTrigger>
                                    <DrawerContent>
                                        <div className="mx-auto w-full max-w-sm p-4">
                                            <DrawerHeader className="px-0 pt-0 pb-4"><DrawerTitle>{t('Order Actions')}</DrawerTitle></DrawerHeader>
                                            <div className="space-y-1">
                                                <DrawerClose asChild><Button variant="ghost" className="w-full justify-start h-12 rounded-lg" onClick={() => setPrintModal({ open: true, order })}><FileText className="w-5 h-5 mr-3 text-muted-foreground" /> {t('View/Print Invoice')}</Button></DrawerClose>
                                                <div className="h-px bg-border my-2"></div>
                                                {order.status === 'processing' && <DrawerClose asChild><Button variant="ghost" className="w-full justify-start h-12 rounded-lg" onClick={() => openTrackingModal(order)}><Truck className="w-5 h-5 mr-3 text-orange-500" /> {t('Ship Order')}</Button></DrawerClose>}
                                                {order.status === 'shipped' && (
                                                    <>
                                                        <DrawerClose asChild><Button variant="ghost" className="w-full justify-start h-12 rounded-lg" onClick={() => openTrackingModal(order)}><PenSquare className="w-5 h-5 mr-3 text-muted-foreground" /> {t('Edit Tracking Info')}</Button></DrawerClose>
                                                        <Button variant="ghost" className="w-full justify-start h-12 text-green-600 rounded-lg" onClick={(e) => { e.preventDefault(); handleStatusChange('completed'); }}>
                                                            {actionLoading === 'completed' ? <Loader2 className="w-5 h-5 mr-3 animate-spin" /> : <CheckCircle2 className="w-5 h-5 mr-3" />} 
                                                            {t('Mark as Completed')}
                                                        </Button>
                                                    </>
                                                )}

                                                {order.status === 'pending' && (
                                                    <Button variant="ghost" className="w-full justify-start h-12 text-red-600 rounded-lg hover:bg-red-500/10" onClick={(e) => { e.preventDefault(); handleStatusChange('cancelled'); }}>
                                                        {actionLoading === 'cancelled' ? <Loader2 className="w-5 h-5 mr-3 animate-spin" /> : <XCircle className="w-5 h-5 mr-3" />} 
                                                        {t('Cancel Order')}
                                                    </Button>
                                                )}
                                            </div>
                                            <DrawerFooter className="px-0 pt-6"><DrawerClose asChild><Button variant="outline" className="w-full rounded-xl">{t('Dismiss')}</Button></DrawerClose></DrawerFooter>
                                        </div>
                                    </DrawerContent>
                                </Drawer>
                            </div>
                        </div>
                    </div>
                </div>
            </CardContent>
        </Card>
    );
}