import React, { useEffect, useRef } from 'react';
import { useParams, Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { ArrowLeft, Printer } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { InlineLoadingState } from '@/components/LoadingState';
import { ErrorCard } from '@/components/ErrorCard';
import { getPageLoadErrorMessage } from '@/lib/errorHandling';
import { __ } from '@/lib/i18n';

export default function Label() {
    const { id } = useParams<{ id: string }>();
    const qrRef = useRef<HTMLCanvasElement | null>(null);

    const q = useQuery({
        queryKey: ['order', id],
        enabled: !!id,
        queryFn: () => api.get(`/orders/${id}`),
    });

    const order = q.data;

    // Generate QR code
    useEffect(() => {
        if (!qrRef.current || !order) return;
        (async () => {
            try {
                const mod = await import('qrcode');
                const QR = (mod as any).default || (mod as any);
                const text = `ORDER:${order.number || id}`;
                await QR.toCanvas(qrRef.current, text, { width: 128, margin: 1 });
            } catch (_) {
                // QR library not available
            }
        })();
    }, [order, id]);

    const handlePrint = () => {
        window.print();
    };

    if (q.isLoading) {
        return <InlineLoadingState message={__('Loading label...')} />;
    }

    if (q.isError) {
        return (
            <ErrorCard
                title={__('Failed to load order')}
                message={getPageLoadErrorMessage(q.error)}
                onRetry={() => q.refetch()}
            />
        );
    }

    if (!order) return null;

    return (
        <div className="min-h-screen bg-gray-100">
            {/* Actions bar - hidden on print */}
            <div className="no-print bg-white border-b sticky top-0 z-10">
                <div className="max-w-2xl mx-auto px-4 py-3 flex items-center justify-between">
                    <Link to={`/orders/${id}`}>
                        <Button variant="ghost" size="sm">
                            <ArrowLeft className="w-4 h-4 mr-2" />
                            {__('Back to Order')}
                        </Button>
                    </Link>
                    <Button onClick={handlePrint} size="sm">
                        <Printer className="w-4 h-4 mr-2" />
                        {__('Print Label')}
                    </Button>
                </div>
            </div>

            {/* Label content - 4x6 inch thermal label size */}
            <div className="py-8 print:py-0 flex justify-center">
                <div
                    className="print-4x6 bg-white shadow-lg print:shadow-none"
                    style={{
                        width: '4in',
                        height: '6in',
                        padding: '0.5in',
                        boxSizing: 'border-box'
                    }}
                >
                    {/* Order Number & QR */}
                    <div className="flex justify-between items-start mb-4">
                        <div>
                            <div className="text-2xl font-bold text-gray-900">#{order.number}</div>
                            <div className="text-xs text-gray-500 mt-1">
                                {new Date((order.date_ts || 0) * 1000).toLocaleDateString()}
                            </div>
                        </div>
                        <canvas ref={qrRef} className="w-24 h-24" style={{ border: '1px solid #e5e7eb' }} />
                    </div>

                    {/* Ship To */}
                    <div className="mb-4 p-3 border-2 border-gray-900 rounded">
                        <div className="text-xs font-bold text-gray-500 uppercase tracking-wide mb-2">{__('SHIP TO')}</div>
                        <div className="text-lg font-bold text-gray-900">{order.shipping?.name || order.billing?.name || '—'}</div>
                        {(order.shipping?.phone || order.billing?.phone) && (
                            <div className="text-sm text-gray-700 mt-1">{order.shipping?.phone || order.billing?.phone}</div>
                        )}
                        <div
                            className="text-sm text-gray-700 mt-2 leading-relaxed"
                            dangerouslySetInnerHTML={{ __html: order.shipping?.address || order.billing?.address || '' }}
                        />
                    </div>

                    {/* Items */}
                    <div className="mb-4">
                        <div className="text-xs font-bold text-gray-500 uppercase tracking-wide mb-2">{__('ITEMS')}</div>
                        <ul className="text-sm space-y-1">
                            {(order.items || []).filter((it: any) => !it.virtual && !it.downloadable).map((it: any) => (
                                <li key={it.id} className="flex justify-between">
                                    <span className="truncate">{it.name}</span>
                                    <span className="font-medium ml-2">×{it.qty}</span>
                                </li>
                            ))}
                        </ul>
                    </div>

                    {/* Shipping Method */}
                    {order.shipping_method && (
                        <div className="pt-3 border-t border-gray-200">
                            <div className="text-xs font-bold text-gray-500 uppercase tracking-wide mb-1">{__('SHIPPING METHOD')}</div>
                            <div className="text-sm font-medium text-gray-900">{order.shipping_method}</div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
