import { useState } from 'react';
import {
    Printer, QrCode, User, Building, Clock, Calendar, Tag,
    Download, Eye, Check, X, ChevronDown, Settings
} from 'lucide-react';

type BadgeTemplate = 'visitor' | 'contractor' | 'inspector' | 'vendor' | 'delivery';
type BadgeSize = 'standard' | 'large' | 'thermal';

interface VisitorBadgeProps {
    visitorId: string;
    name: string;
    company?: string;
    type: string;
    purpose: string;
    badgeNumber: string;
    checkInTime: string;
    expiresAt?: string;
    escort?: { name: string };
    photoUrl?: string;
    accessZones?: string[];
    showPrintButton?: boolean;
    template?: BadgeTemplate;
    onPrint?: () => void;
}

const TEMPLATE_STYLES: Record<BadgeTemplate, {
    headerBg: string;
    headerText: string;
    accent: string;
    label: string;
}> = {
    visitor: {
        headerBg: 'bg-blue-600',
        headerText: 'text-white',
        accent: 'text-blue-600',
        label: 'VISITOR'
    },
    contractor: {
        headerBg: 'bg-[var(--color-warning)]',
        headerText: 'text-white',
        accent: 'text-amber-600',
        label: 'CONTRACTOR'
    },
    inspector: {
        headerBg: 'bg-red-600',
        headerText: 'text-white',
        accent: 'text-red-600',
        label: 'INSPECTOR'
    },
    vendor: {
        headerBg: 'bg-purple-600',
        headerText: 'text-white',
        accent: 'text-purple-600',
        label: 'VENDOR'
    },
    delivery: {
        headerBg: 'bg-[var(--color-primary)]',
        headerText: 'text-white',
        accent: 'text-[var(--color-primary)]',
        label: 'DELIVERY'
    }
};

export default function VisitorBadge({
    visitorId,
    name,
    company,
    type,
    purpose,
    badgeNumber,
    checkInTime,
    expiresAt,
    escort,
    photoUrl,
    accessZones = [],
    showPrintButton = true,
    template = 'visitor',
    onPrint
}: VisitorBadgeProps) {
    const [isPrinting, setIsPrinting] = useState(false);
    const [showPreview, setShowPreview] = useState(false);
    const [selectedSize, setSelectedSize] = useState<BadgeSize>('standard');

    const templateStyle = TEMPLATE_STYLES[template] || TEMPLATE_STYLES.visitor;

    const checkInDate = new Date(checkInTime);
    const expiryDate = expiresAt ? new Date(expiresAt) : null;
    const isExpired = expiryDate && expiryDate < new Date();

    async function handlePrint() {
        setIsPrinting(true);

        // Create print-only container
        const printWindow = window.open('', '_blank', 'width=400,height=600');
        if (!printWindow) {
            setIsPrinting(false);
            return;
        }

        const badgeHtml = generateBadgeHtml();

        printWindow.document.write(`
            <!DOCTYPE html>
            <html>
            <head>
                <title>Visitor Badge - ${badgeNumber}</title>
                <style>
                    * { margin: 0; padding: 0; box-sizing: border-box; }
                    @page { size: ${selectedSize === 'thermal' ? '2.25in 3.5in' : '3.5in 5in'}; margin: 0; }
                    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
                    .badge { 
                        width: ${selectedSize === 'thermal' ? '2.25in' : '3.5in'}; 
                        height: ${selectedSize === 'thermal' ? '3.5in' : selectedSize === 'large' ? '6in' : '5in'}; 
                        border: 2px solid #000;
                        border-radius: 8px;
                        overflow: hidden;
                        background: white;
                    }
                    .header { 
                        padding: ${selectedSize === 'thermal' ? '8px' : '12px'}; 
                        text-align: center;
                        color: white;
                    }
                    .header.visitor { background: #2563eb; }
                    .header.contractor { background: #f59e0b; }
                    .header.inspector { background: #dc2626; }
                    .header.vendor { background: #9333ea; }
                    .header.delivery { background: #059669; }
                    .header h1 { 
                        font-size: ${selectedSize === 'thermal' ? '14px' : '18px'}; 
                        font-weight: bold; 
                        letter-spacing: 2px; 
                    }
                    .content { padding: ${selectedSize === 'thermal' ? '8px' : '16px'}; }
                    .name { 
                        font-size: ${selectedSize === 'thermal' ? '16px' : '24px'}; 
                        font-weight: bold; 
                        text-align: center; 
                        margin-bottom: 4px;
                    }
                    .company { 
                        font-size: ${selectedSize === 'thermal' ? '11px' : '14px'}; 
                        color: #666; 
                        text-align: center; 
                        margin-bottom: 12px; 
                    }
                    .info-row { 
                        display: flex; 
                        justify-content: space-between; 
                        font-size: ${selectedSize === 'thermal' ? '10px' : '12px'}; 
                        padding: 4px 0; 
                        border-bottom: 1px solid #eee; 
                    }
                    .info-label { color: #666; }
                    .info-value { font-weight: 500; }
                    .qr-container { 
                        display: flex; 
                        justify-content: center; 
                        padding: ${selectedSize === 'thermal' ? '8px' : '16px'} 0; 
                    }
                    .qr-placeholder { 
                        width: ${selectedSize === 'thermal' ? '60px' : '80px'}; 
                        height: ${selectedSize === 'thermal' ? '60px' : '80px'}; 
                        border: 2px solid #000; 
                        display: flex; 
                        align-items: center; 
                        justify-content: center; 
                        font-size: 10px; 
                    }
                    .badge-number { 
                        text-align: center; 
                        font-size: ${selectedSize === 'thermal' ? '20px' : '28px'}; 
                        font-weight: bold; 
                        font-family: monospace; 
                    }
                    .expiry { 
                        text-align: center; 
                        font-size: 11px; 
                        color: #dc2626; 
                        margin-top: 8px; 
                        padding: 4px; 
                        background: #fef2f2; 
                        border-radius: 4px; 
                    }
                    .footer { 
                        padding: 8px; 
                        text-align: center; 
                        font-size: 9px; 
                        color: #666; 
                        border-top: 1px solid #ddd; 
                    }
                    @media print {
                        body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
                    }
                </style>
            </head>
            <body>
                ${badgeHtml}
                <script>
                    window.onload = function() { 
                        window.print(); 
                        setTimeout(function() { window.close(); }, 500);
                    }
                </script>
            </body>
            </html>
        `);

        printWindow.document.close();

        setTimeout(() => {
            setIsPrinting(false);
            onPrint?.();
        }, 1000);
    }

    function generateBadgeHtml(): string {
        return `
            <div class="badge">
                <div class="header ${template}">
                    <h1>${templateStyle.label}</h1>
                </div>
                <div class="content">
                    <div class="name">${name}</div>
                    ${company ? `<div class="company">${company}</div>` : ''}
                    
                    <div class="info-row">
                        <span class="info-label">Purpose</span>
                        <span class="info-value">${purpose}</span>
                    </div>
                    ${escort ? `
                    <div class="info-row">
                        <span class="info-label">Escort</span>
                        <span class="info-value">${escort.name}</span>
                    </div>
                    ` : ''}
                    <div class="info-row">
                        <span class="info-label">Check-In</span>
                        <span class="info-value">${checkInDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>
                    </div>
                    
                    <div class="qr-container">
                        <div class="qr-placeholder">QR</div>
                    </div>
                    
                    <div class="badge-number">${badgeNumber}</div>
                    
                    ${expiryDate ? `
                    <div class="expiry">
                        EXPIRES: ${expiryDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                    </div>
                    ` : ''}
                </div>
                <div class="footer">
                    Veridian • ${checkInDate.toLocaleDateString()}
                </div>
            </div>
        `;
    }

    return (
        <div className="space-y-4">
            {/* Badge Preview Card */}
            <div className={`relative rounded-2xl overflow-hidden shadow-lg border-2 max-w-sm mx-auto ${isExpired ? 'border-red-400 opacity-75' : 'border-slate-200 dark:border-slate-600'}`}>
                {/* Header */}
                <div className={`${templateStyle.headerBg} ${templateStyle.headerText} p-4 text-center`}>
                    <p className="text-xs font-bold tracking-widest uppercase opacity-80">
                        {templateStyle.label}
                    </p>
                </div>

                {/* Content */}
                <div className="bg-[var(--color-bg-elevated)] p-6">
                    {/* Photo + Name */}
                    <div className="flex flex-col items-center mb-4">
                        <div className="w-20 h-20 rounded-full bg-[var(--color-bg-tertiary)] flex items-center justify-center mb-3 overflow-hidden">
                            {photoUrl ? (
                                <img src={photoUrl} alt={name} className="w-full h-full object-cover" />
                            ) : (
                                <User size={32} className="text-[var(--color-text-tertiary)]" />
                            )}
                        </div>
                        <h2 className="text-xl font-bold text-[var(--color-text-primary)] text-center">{name}</h2>
                        {company && (
                            <p className="text-sm text-[var(--color-text-tertiary)] flex items-center gap-1 mt-1">
                                <Building size={14} />
                                {company}
                            </p>
                        )}
                    </div>

                    {/* Info Grid */}
                    <div className="space-y-2 text-sm mb-4">
                        <div className="flex justify-between py-2 border-b border-slate-100 dark:border-slate-700">
                            <span className="text-[var(--color-text-tertiary)]">Purpose</span>
                            <span className="font-medium text-[var(--color-text-primary)]">{purpose}</span>
                        </div>
                        {escort && (
                            <div className="flex justify-between py-2 border-b border-slate-100 dark:border-slate-700">
                                <span className="text-[var(--color-text-tertiary)]">Escort</span>
                                <span className="font-medium text-[var(--color-text-primary)]">{escort.name}</span>
                            </div>
                        )}
                        <div className="flex justify-between py-2 border-b border-slate-100 dark:border-slate-700">
                            <span className="text-[var(--color-text-tertiary)] flex items-center gap-1">
                                <Clock size={12} /> Check-In
                            </span>
                            <span className="font-medium text-[var(--color-text-primary)]">
                                {checkInDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                            </span>
                        </div>
                        {accessZones.length > 0 && (
                            <div className="flex justify-between py-2 border-b border-slate-100 dark:border-slate-700">
                                <span className="text-[var(--color-text-tertiary)]">Access</span>
                                <span className="font-medium text-[var(--color-text-primary)]">
                                    {accessZones.join(', ')}
                                </span>
                            </div>
                        )}
                    </div>

                    {/* Badge Number */}
                    <div className="text-center py-4 bg-[var(--color-bg-tertiary)]/50 rounded-xl mb-4">
                        <p className="text-xs text-[var(--color-text-tertiary)] uppercase mb-1">Badge Number</p>
                        <p className={`text-3xl font-mono font-bold ${templateStyle.accent}`}>
                            {badgeNumber}
                        </p>
                    </div>

                    {/* Expiry Warning */}
                    {expiryDate && (
                        <div className={`text-center py-2 rounded-lg text-sm font-medium ${isExpired
                            ? 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
                            : 'bg-amber-50 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400'
                            }`}>
                            <Calendar size={14} className="inline mr-1" />
                            {isExpired ? 'EXPIRED' : `Expires: ${expiryDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`}
                        </div>
                    )}
                </div>

                {/* Expired Overlay */}
                {isExpired && (
                    <div className="absolute inset-0 bg-white/80 dark:bg-slate-900/80 flex items-center justify-center">
                        <div className="transform -rotate-12">
                            <span className="text-4xl font-bold text-red-500 tracking-wider">EXPIRED</span>
                        </div>
                    </div>
                )}
            </div>

            {/* Print Controls */}
            {showPrintButton && !isExpired && (
                <div className="flex justify-center gap-3 max-w-sm mx-auto">
                    {/* Size Selector */}
                    <div className="relative">
                        <select
                            value={selectedSize}
                            onChange={(e) => setSelectedSize(e.target.value as BadgeSize)}
                            className="appearance-none px-3 py-2 pr-8 rounded-lg border border-slate-200 dark:border-slate-600 bg-[var(--color-bg-elevated)] text-sm cursor-pointer"
                        >
                            <option value="standard">Standard (3.5" x 5")</option>
                            <option value="large">Large (3.5" x 6")</option>
                            <option value="thermal">Thermal (2.25" x 3.5")</option>
                        </select>
                        <ChevronDown size={14} className="absolute right-2 top-1/2 -translate-y-1/2 text-[var(--color-text-tertiary)] pointer-events-none" />
                    </div>

                    {/* Print Button */}
                    <button
                        onClick={handlePrint}
                        disabled={isPrinting}
                        className="flex-1 py-2 px-4 bg-indigo-600 text-white rounded-lg font-medium flex items-center justify-center gap-2 hover:bg-indigo-700 disabled:opacity-50 transition-colors"
                    >
                        <Printer size={18} />
                        {isPrinting ? 'Printing...' : 'Print Badge'}
                    </button>
                </div>
            )}
        </div>
    );
}

// Badge Print Queue Component for bulk printing
export function BadgePrintQueue({
    badges
}: {
    badges: VisitorBadgeProps[]
}) {
    const [queue, setQueue] = useState<Array<VisitorBadgeProps & { status: 'pending' | 'printing' | 'done' }>>(
        badges.map(b => ({ ...b, status: 'pending' as const }))
    );

    async function printAll() {
        for (let i = 0; i < queue.length; i++) {
            setQueue(prev => prev.map((b, idx) =>
                idx === i ? { ...b, status: 'printing' } : b
            ));

            // Simulate print delay
            await new Promise(resolve => setTimeout(resolve, 1000));

            setQueue(prev => prev.map((b, idx) =>
                idx === i ? { ...b, status: 'done' } : b
            ));
        }
    }

    const pendingCount = queue.filter(b => b.status === 'pending').length;
    const doneCount = queue.filter(b => b.status === 'done').length;

    return (
        <div className="bg-[var(--color-bg-elevated)] rounded-xl border border-[var(--color-border-default)] p-4">
            <div className="flex items-center justify-between mb-4">
                <div>
                    <h3 className="font-medium text-[var(--color-text-primary)]">Print Queue</h3>
                    <p className="text-sm text-[var(--color-text-tertiary)]">{doneCount}/{queue.length} printed</p>
                </div>
                <button
                    onClick={printAll}
                    disabled={pendingCount === 0}
                    className="px-4 py-2 bg-indigo-600 text-white rounded-lg text-sm font-medium flex items-center gap-2 hover:bg-indigo-700 disabled:opacity-50"
                >
                    <Printer size={16} />
                    Print All ({pendingCount})
                </button>
            </div>

            <div className="space-y-2">
                {queue.map((badge, i) => (
                    <div
                        key={badge.visitorId}
                        className={`flex items-center justify-between p-3 rounded-lg border ${badge.status === 'done'
                            ? 'bg-emerald-50 border-emerald-200 dark:bg-emerald-900/20 dark:border-emerald-800'
                            : badge.status === 'printing'
                                ? 'bg-blue-50 border-blue-200 dark:bg-blue-900/20 dark:border-blue-800 animate-pulse'
                                : 'bg-slate-50 border-slate-200 dark:bg-slate-900/50 dark:border-slate-700'
                            }`}
                    >
                        <div className="flex items-center gap-3">
                            <div className="w-8 h-8 rounded-full bg-slate-200 dark:bg-slate-700 flex items-center justify-center">
                                <User size={14} className="text-[var(--color-text-tertiary)]" />
                            </div>
                            <div>
                                <p className="font-medium text-sm text-[var(--color-text-primary)]">{badge.name}</p>
                                <p className="text-xs text-[var(--color-text-tertiary)]">{badge.badgeNumber}</p>
                            </div>
                        </div>
                        <div>
                            {badge.status === 'done' && <Check size={18} className="text-[var(--color-primary)]" />}
                            {badge.status === 'printing' && <Printer size={18} className="text-[var(--color-accent)] animate-pulse" />}
                            {badge.status === 'pending' && <Clock size={18} className="text-[var(--color-text-tertiary)]" />}
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
}
