import React, { useRef } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/Components/ui/dialog";
import { Button } from "@/Components/ui/button";
import { Printer, Store, CreditCard, AlertCircle, CheckCircle2 } from 'lucide-react';
import { usePage } from '@inertiajs/react';
import { useReactToPrint } from 'react-to-print';
import { useTranslation } from '@/hooks/useTranslation';

export default function PrintOrderModal({ isOpen, onClose, order }) {
    const { appSettings, currencies } = usePage().props;
    const { t } = useTranslation();
    
    const contentRef = useRef(null);

    const handlePrint = useReactToPrint({
        contentRef: contentRef,
        documentTitle: `Invoice_${order?.order_number || 'Document'}`,
        pageStyle: `
            @page { size: A4 portrait; margin: 15mm; }
            body { -webkit-print-color-adjust: exact; print-color-adjust: exact; background-color: white !important; }
        `
    });

    if (!order) return null;

    const orderCurrencyObj = currencies?.find(c => c.code === order.currency);
    const orderSymbol = orderCurrencyObj?.symbol || '$';

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

    return (
        <Dialog open={isOpen} onOpenChange={onClose}>
            <DialogContent className="max-w-4xl lg:max-w-5xl w-[95vw] max-h-[90vh] overflow-y-auto p-0">
                
                <DialogHeader className="border-b pb-4 pt-6 px-6 sm:px-10 shrink-0 sticky top-0 bg-card z-10">
                    <DialogTitle className="flex items-center gap-2 text-xl">
                        <Printer className="w-5 h-5 text-primary" /> {t('Print Invoice')}
                    </DialogTitle>
                </DialogHeader>

                <div ref={contentRef} className="bg-white text-black p-8 sm:p-12 w-full min-h-[100px]">
                    
                    <div className="flex justify-between items-start">
                        <div>
                            <h2 className="text-3xl font-black text-black">{appSettings?.name || 'Marketplace'}</h2>
                            <p className="text-gray-500">{t('Official Commercial Invoice')}</p>
                        </div>
                        
                        <div className="text-right text-black">
                            <h3 className="font-bold text-xl">{t('INVOICE')}</h3>
                            <p className="font-mono text-gray-500 mb-3">{order.order_number}</p>
                            
                            <p className="text-xs">
                                <span className="text-gray-500 uppercase tracking-widest font-bold">{t('Order Date')}:</span><br/>
                                {new Date(order.created_at).toLocaleString(undefined, { 
                                    year: 'numeric', month: 'short', day: 'numeric', 
                                    hour: '2-digit', minute: '2-digit' 
                                })}
                            </p>
                            
                            {/* Exact Payment Time */}
                            {order.status !== 'pending' && order.status !== 'cancelled' && (
                                <p className="text-xs mt-2 font-medium text-green-700">
                                    <span className="text-gray-500 uppercase tracking-widest font-bold">{t('Paid On')}:</span><br/>
                                    {new Date(order.updated_at).toLocaleString(undefined, { 
                                        year: 'numeric', month: 'short', day: 'numeric', 
                                        hour: '2-digit', minute: '2-digit', second: '2-digit' 
                                    })}
                                </p>
                            )}

                            {/* Unpaid Warning */}
                            {order.status === 'pending' && (
                                <p className="text-xs mt-2 font-black text-red-600 bg-red-50 inline-block px-2 py-1 rounded border border-red-100">
                                    {t('STATUS: UNPAID')}
                                </p>
                            )}

                            {/* Refund Status Badge */}
                            {order.status === 'refunded' && (
                                <p className="text-xs mt-2 font-black text-purple-600 bg-purple-50 inline-block px-2 py-1 rounded border border-purple-100">
                                    {t('STATUS: REFUNDED')}
                                </p>
                            )}

                            <p className="mt-3 font-bold text-xs uppercase flex items-center justify-end gap-1 text-gray-700 bg-gray-100 px-2 py-1 rounded w-fit ml-auto">
                                <CreditCard className="w-4 h-4" /> {t('VIA')}: {formatGateway(order.payment_gateway)}
                            </p>
                        </div>
                    </div>

                    {/* --- REFUND DETAILS SECTION --- */}
                    {(order.is_refund_requested || order.status === 'refunded') && (
                        <div className="mt-8 p-4 border-2 border-dashed border-orange-200 bg-orange-50 rounded-xl">
                            <div className="flex items-center gap-2 mb-2">
                                {order.status === 'refunded' ? (
                                    <CheckCircle2 className="w-5 h-5 text-purple-600" />
                                ) : (
                                    <AlertCircle className="w-5 h-5 text-orange-600" />
                                )}
                                <h4 className="font-bold text-sm uppercase tracking-tight">
                                    {order.status === 'refunded' ? t('Refund Processed') : t('Refund Request Details')}
                                </h4>
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-xs">
                                <div>
                                    <span className="text-gray-500 font-bold uppercase">{t('Reason')}:</span>
                                    <p className="mt-1 text-gray-800 italic">"{order.refund_reason || t('No reason provided')}"</p>
                                </div>
                                <div className="md:text-right">
                                    <span className="text-gray-500 font-bold uppercase">
                                        {order.status === 'refunded' ? t('Refunded On') : t('Requested On')}:
                                    </span>
                                    <p className="mt-1 text-gray-800">
                                        {new Date(order.updated_at).toLocaleString()}
                                    </p>
                                </div>
                            </div>
                        </div>
                    )}

                    <div className="grid grid-cols-2 gap-8 border-t border-b border-gray-200 py-6 mt-8">
                        <div className="text-black">
                            <h4 className="font-bold text-xs uppercase tracking-widest text-gray-500 mb-2">{t('Supplier Details')}</h4>
                            <p className="font-bold flex items-center gap-1 text-base"><Store className="w-4 h-4"/> {order.seller?.company_name || order.seller?.name}</p>
                            <p className="text-gray-600 mt-1">{order.seller?.email}</p>
                            <p className="text-gray-600 mt-1">{order.seller?.phone || ''}</p>
                        </div>
                        <div className="text-black">
                            <h4 className="font-bold text-xs uppercase tracking-widest text-gray-500 mb-2">{t('Bill To / Ship To')}</h4>
                            <p className="font-bold text-base">{order.buyer?.name}</p>
                            <p className="text-gray-600 whitespace-pre-wrap mt-1 leading-relaxed">
                                {order.shipping_address || t('No Address Provided')}<br/>
                                {order.buyer?.country?.name}
                            </p>
                            <p className="text-gray-600 mt-1">{order.buyer?.email}</p>
                            <p className="text-gray-600 mt-1">{order.buyer?.phone || ''}</p>
                        </div>
                    </div>

                    <div className="mt-8">
                        <table className="w-full text-left border-collapse text-black">
                            <thead>
                                <tr className="border-b-2 border-gray-800">
                                    <th className="py-3 font-bold uppercase text-xs tracking-wider">{t('Description')}</th>
                                    <th className="py-3 font-bold uppercase text-xs tracking-wider text-center">{t('Qty')}</th>
                                    <th className="py-3 font-bold uppercase text-xs tracking-wider text-right">{t('Unit Price')}</th>
                                    <th className="py-3 font-bold uppercase text-xs tracking-wider text-right">{t('Total')}</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-200">
                                {order.items?.map(item => (
                                    <tr key={item.id} style={{ pageBreakInside: 'avoid' }}>
                                        <td className="py-4 font-medium text-base pr-4">
                                            {item.product?.title || t('Product Removed')}
                                            {item.selected_variations && Object.keys(item.selected_variations).length > 0 && (
                                                <div className="text-xs text-gray-500 mt-1 font-normal">
                                                    {Object.entries(item.selected_variations).map(([k, v]) => `${k}: ${v.value}`).join(' | ')}
                                                </div>
                                            )}
                                        </td>
                                        <td className="py-4 text-center text-base">{item.quantity}</td>
                                        <td className="py-4 text-right text-base whitespace-nowrap">{order.currency} {orderSymbol}{parseFloat(item.unit_price).toFixed(2)}</td>
                                        <td className="py-4 text-right font-bold text-base whitespace-nowrap">{order.currency} {orderSymbol}{(parseFloat(item.unit_price) * item.quantity).toFixed(2)}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>

                    <div className="flex justify-end pt-8" style={{ pageBreakInside: 'avoid' }}>
                        <div className="w-72 space-y-3 text-black">
                            <div className="flex justify-between text-base text-gray-600">
                                <span>{t('Subtotal')}</span>
                                <span>{order.currency} {orderSymbol}{parseFloat(order.total_amount).toFixed(2)}</span>
                            </div>
                            <div className="flex justify-between font-black text-2xl border-t-2 border-gray-800 pt-3">
                                <span>{order.status === 'refunded' ? t('Total Refunded') : t('Total Paid')}</span>
                                <span>{order.currency} {orderSymbol}{parseFloat(order.total_amount).toFixed(2)}</span>
                            </div>
                        </div>
                    </div>
                    
                </div>

                <DialogFooter className="border-t py-4 px-6 sm:px-10 bg-muted/10 sticky bottom-0 z-10 shrink-0">
                    <Button variant="outline" onClick={onClose} className="px-6">
                        {t('Close')}
                    </Button>
                    <Button onClick={() => handlePrint()} className="gap-2 px-8 font-bold bg-primary text-primary-foreground hover:opacity-90">
                        <Printer className="w-4 h-4" /> {t('Print Document')}
                    </Button>
                </DialogFooter>

            </DialogContent>
        </Dialog>
    );
}