import React, { useState } from 'react';
import { Link, usePage, useForm } from '@inertiajs/react';
import { Card, CardContent } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { Badge } from "@/Components/ui/badge";
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 {
    Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription 
} from "@/Components/ui/dialog";
import { Label } from "@/Components/ui/label";
import { Textarea } from "@/Components/ui/textarea";
import { 
    Truck, CheckCircle2, XCircle, MoreVertical, Printer, MessageSquare, 
    FileText, Store, ShieldCheck, ExternalLink, CreditCard, AlertCircle, Loader2
} from 'lucide-react';

export default function OrderCard({ 
    order, 
    setPrintModal, 
    handleMessageSeller, 
    updateSimpleStatus, 
    handlePayNow,
    processingId 
}) {
    const { activeCurrency, currencies, appSettings } = usePage().props;
    const { t } = useTranslation();

    // Refund State & Form
    const [refundModal, setRefundModal] = useState(false);
    const { data: refundData, setData: setRefundData, post: postRefund, processing: refundProcessing, reset: resetRefund } = useForm({
        reason: ''
    });

    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 formatGateway = (code) => {
        if (!code) return t('N/A');
        if (code === 'manual') return t('Manual / Bank Transfer');
        if (code === 'sslcommerz') return t('SSLCommerz');
        if (code === 'bkash') return t('bKash');
        return code.charAt(0).toUpperCase() + code.slice(1);
    };

    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('Unpaid'), 
            processing: t('Preparing'), 
            shipped: t('To Receive'), 
            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>;
    };

    const submitRefund = (e) => {
        e.preventDefault();
        postRefund(route('buyer.orders.refund', order.id), {
            onSuccess: () => {
                setRefundModal(false);
                resetRefund();
            }
        });
    };

    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 items-center gap-4">
                        <div className="font-bold flex items-center gap-2 truncate max-w-[180px] sm:max-w-none">
                            <Store className="w-4 h-4 text-primary shrink-0" />
                            <span className="truncate">{order.seller?.company_name || order.seller?.name}</span>
                            <Button size="icon" variant="ghost" className="h-6 w-6 rounded-full text-blue-500 shrink-0" onClick={() => handleMessageSeller(order.seller_id, order.items?.[0]?.product_id)}>
                                <MessageSquare className="w-3 h-3" />
                            </Button>
                        </div>
                    </div>
                    <div className="flex items-center gap-4 text-muted-foreground text-xs whitespace-nowrap">
                        <span>{t('ID:')} <span className="font-mono text-foreground font-bold">{order.order_number}</span></span>
                    </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;
                                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="" 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>
                                            
                                            {item.selected_variations && Object.keys(item.selected_variations).length > 0 && (
                                                <div className="mt-1 flex flex-wrap gap-1">
                                                    {Object.entries(item.selected_variations).map(([key, opt]) => (
                                                        <span key={key} className="text-[10px] bg-muted border border-border/50 px-1.5 py-0.5 rounded text-muted-foreground font-medium">
                                                            {t(key)}: {opt.value}
                                                        </span>
                                                    ))}
                                                </div>
                                            )}

                                            <div className="text-xs text-muted-foreground mt-1">
                                                {currencySymbol}{displayUnitPrice.toFixed(2)} × {item.quantity}
                                            </div>
                                        </div>
                                    </div>
                                );
                            })}

                            {order.seller_notes && (
                                <div className="mt-3 bg-blue-500/5 p-3 rounded-lg border border-blue-500/20 text-xs text-blue-900 dark:text-blue-200">
                                    <span className="font-bold text-blue-600 block mb-1">{t('Message from Seller:')}</span>
                                    {order.seller_notes}
                                </div>
                            )}
                        </div>

                        <div className="w-full lg:w-48 p-4 lg:border-r border-border/50 flex flex-col justify-center items-center space-y-3 bg-muted/5 whitespace-nowrap">
                            {getStatusBadge(order.status)}
                            
                            {order.status === 'shipped' || order.status === 'completed' ? (
                                <div className="w-full bg-background border border-primary/20 p-2.5 rounded-lg text-center shadow-sm">
                                    <p className="text-[9px] font-black text-primary uppercase tracking-widest mb-1 flex items-center justify-center gap-1"><Truck className="w-3 h-3"/> {t('Tracking Info')}</p>
                                    
                                    {order.tracking_url ? (
                                        <a href={order.tracking_url} target="_blank" rel="noreferrer" className="text-blue-600 hover:text-blue-800 hover:underline font-mono font-bold text-xs truncate px-1 flex items-center justify-center gap-1">
                                            {order.tracking_number || t('Track Package')} <ExternalLink className="w-3 h-3 shrink-0" />
                                        </a>
                                    ) : (
                                        <p className="font-mono font-bold text-xs truncate px-1">{order.tracking_number || t('N/A')}</p>
                                    )}
                                    
                                    {order.shipping_carrier && (
                                        <p className="text-[10px] text-muted-foreground mt-1">{order.shipping_carrier}</p>
                                    )}
                                </div>
                            ) : (
                                <div className="flex items-center gap-1 text-[10px] font-bold text-green-600 uppercase"><ShieldCheck className="w-3.5 h-3.5" /> {t('Secured')}</div>
                            )}
                        </div>

                        <div className="w-full lg:w-64 p-4 flex flex-col justify-center items-center text-center">
                            <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-2 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.is_refund_requested && (
                                <div className="bg-orange-500/10 text-orange-600 border border-orange-500/20 text-[10px] px-2 py-1 rounded-md font-bold mb-2">
                                    {t('Refund Requested')}
                                </div>
                            )}

                            {order.currency !== activeCurrency?.code && (
                                <div className="text-[10px] font-bold text-muted-foreground mb-3">
                                    {t('Original:')} {parseFloat(order.total_amount).toFixed(2)} {order.currency}
                                </div>
                            )}
                            
                            <div className="w-full space-y-2 mt-2">
                                {order.status === 'pending' && <Button className="w-full bg-orange-500 hover:bg-orange-600 text-white font-bold rounded-xl shadow-sm" onClick={() => handlePayNow(order)}>{t('Pay Now')}</Button>}
                                {order.status === 'shipped' && (
                                    <Button disabled={processingId === order.id} className="w-full bg-green-600 hover:bg-green-700 text-white font-bold rounded-xl shadow-sm" onClick={() => updateSimpleStatus(order, 'completed')}>
                                        {processingId === order.id && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                                        {t('Confirm Receipt')}
                                    </Button>
                                )}
                                
                                <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 border-input 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 onClick={() => setPrintModal({ open: true, order })} className="cursor-pointer py-2 px-3"><FileText className="w-4 h-4 mr-2" /> {t('View Invoice')}</DropdownMenuItem>
                                            <DropdownMenuItem onClick={() => handleMessageSeller(order.seller_id, order.items?.[0]?.product_id)} className="cursor-pointer py-2 px-3"><MessageSquare className="w-4 h-4 mr-2 text-blue-500" /> {t('Contact Seller')}</DropdownMenuItem>
                                            
                                            {/* Refund System Link */}
                                            {appSettings?.enable_refund_system && ['processing', 'shipped', 'completed'].includes(order.status) && !order.is_refund_requested && (
                                                <DropdownMenuItem onClick={() => setRefundModal(true)} className="text-orange-600 font-bold cursor-pointer py-2 px-3">
                                                    <AlertCircle className="w-4 h-4 mr-2" /> {t('Request Refund')}
                                                </DropdownMenuItem>
                                            )}

                                            <DropdownMenuSeparator />
                                            {order.status === 'pending' && (
                                                <DropdownMenuItem onClick={(e) => { e.preventDefault(); updateSimpleStatus(order, 'cancelled'); }} className="text-red-600 font-bold cursor-pointer py-2 px-3">
                                                    {processingId === order.id ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
                                                    {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 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" /> {t('View Invoice')}</Button></DrawerClose>
                                                    <DrawerClose asChild><Button variant="ghost" className="w-full justify-start h-12 rounded-lg" onClick={() => handleMessageSeller(order.seller_id, order.items?.[0]?.product_id)}><MessageSquare className="w-5 h-5 mr-3 text-blue-500" /> {t('Contact Seller')}</Button></DrawerClose>
                                                    
                                                    {/* Refund System Link */}
                                                    {appSettings?.enable_refund_system && ['processing', 'shipped', 'completed'].includes(order.status) && !order.is_refund_requested && (
                                                        <DrawerClose asChild>
                                                            <Button variant="ghost" className="w-full justify-start h-12 text-orange-600 rounded-lg" onClick={() => setRefundModal(true)}>
                                                                <AlertCircle className="w-5 h-5 mr-3" /> {t('Request Refund')}
                                                            </Button>
                                                        </DrawerClose>
                                                    )}

                                                    <div className="h-px bg-border my-2"></div>
                                                    {order.status === 'pending' && (
                                                        <Button variant="ghost" className="w-full justify-start h-12 text-red-600 rounded-lg" onClick={() => updateSimpleStatus(order, 'cancelled')}>
                                                            <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>

            {/* Request Refund Modal */}
            <Dialog open={refundModal} onOpenChange={setRefundModal}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>{t('Request a Refund')}</DialogTitle>
                        <DialogDescription>
                            {t('This will notify the seller and open a chat. Please discuss the return address and process directly with them.')}
                        </DialogDescription>
                    </DialogHeader>
                    <form onSubmit={submitRefund} className="space-y-4">
                        <div className="space-y-2">
                            <Label>{t('Reason for Refund')}</Label>
                            <Textarea 
                                required 
                                value={refundData.reason} 
                                onChange={e => setRefundData('reason', e.target.value)} 
                                placeholder={t('e.g., Item arrived damaged, wrong color...')}
                                className="min-h-[100px]"
                            />
                        </div>
                        <DialogFooter>
                            <Button type="button" variant="outline" onClick={() => setRefundModal(false)}>{t('Cancel')}</Button>
                            <Button type="submit" disabled={refundProcessing} className="bg-orange-600 hover:bg-orange-700 text-white">
                                {t('Send Request to Seller')}
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>
        </>
    );
}