import { useState, useEffect } from 'react';
import { QrCode, Download, Printer, Copy, Check } from 'lucide-react';
import {
    generateQRCode,
    generatePrintableLabel,
    printLabels,
    generateBatchQRData,
    generatePlantQRData,
    generateVisitorQRData,
    generateRoomQRData
} from '../../lib/qrcode';

interface QRCodeGeneratorProps {
    type: 'batch' | 'plant' | 'visitor' | 'room' | 'custom';
    id: string;
    title: string;
    subtitle?: string;
    details?: string[];
    customData?: string;
    size?: 'sm' | 'md' | 'lg';
    showActions?: boolean;
}

export default function QRCodeGenerator({
    type,
    id,
    title,
    subtitle,
    details = [],
    customData,
    size = 'md',
    showActions = true
}: QRCodeGeneratorProps) {
    const [qrDataUrl, setQrDataUrl] = useState<string>('');
    const [loading, setLoading] = useState(true);
    const [copied, setCopied] = useState(false);

    const sizeMap = { sm: 100, md: 160, lg: 240 };
    const qrSize = sizeMap[size];

    useEffect(() => {
        const generateQR = async () => {
            setLoading(true);
            try {
                let data: string;

                switch (type) {
                    case 'batch':
                        data = generateBatchQRData(id, title);
                        break;
                    case 'plant':
                        data = generatePlantQRData(id, title, subtitle || '');
                        break;
                    case 'visitor':
                        data = generateVisitorQRData(id, title, subtitle || '');
                        break;
                    case 'room':
                        data = generateRoomQRData(id, title);
                        break;
                    case 'custom':
                    default:
                        data = customData || id;
                }

                const dataUrl = await generateQRCode(data, { width: qrSize });
                setQrDataUrl(dataUrl);
            } catch (error) {
                console.error('Failed to generate QR code:', error);
            } finally {
                setLoading(false);
            }
        };

        generateQR();
    }, [type, id, title, subtitle, customData, qrSize]);

    const handleDownload = () => {
        const link = document.createElement('a');
        link.href = qrDataUrl;
        link.download = `qr-${type}-${id}.png`;
        link.click();
    };

    const handleCopy = async () => {
        try {
            const blob = await fetch(qrDataUrl).then(r => r.blob());
            await navigator.clipboard.write([
                new ClipboardItem({ 'image/png': blob })
            ]);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        } catch {
            // Fallback: copy data URL
            navigator.clipboard.writeText(qrDataUrl);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        }
    };

    const handlePrint = async () => {
        let data: string;
        switch (type) {
            case 'batch':
                data = generateBatchQRData(id, title);
                break;
            case 'plant':
                data = generatePlantQRData(id, title, subtitle || '');
                break;
            case 'visitor':
                data = generateVisitorQRData(id, title, subtitle || '');
                break;
            case 'room':
                data = generateRoomQRData(id, title);
                break;
            default:
                data = customData || id;
        }

        const labelHtml = await generatePrintableLabel({
            type: type === 'custom' ? 'batch' : type,
            title,
            subtitle,
            details,
            qrData: data,
            size: size === 'sm' ? 'small' : size === 'lg' ? 'large' : 'medium',
        });

        printLabels([labelHtml], `${title} Label`);
    };

    if (loading) {
        return (
            <div
                className="flex items-center justify-center bg-slate-100 dark:bg-slate-800 rounded-lg animate-pulse"
                style={{ width: qrSize, height: qrSize }}
            >
                <QrCode className="text-[var(--color-text-tertiary)]" size={qrSize / 3} />
            </div>
        );
    }

    return (
        <div className="inline-flex flex-col items-center gap-2">
            <div className="bg-white p-2 rounded-lg shadow-sm">
                <img
                    src={qrDataUrl}
                    alt={`QR Code for ${title}`}
                    width={qrSize}
                    height={qrSize}
                    className="block"
                />
            </div>

            {showActions && (
                <div className="flex gap-1">
                    <button
                        onClick={handleDownload}
                        className="p-2 text-[var(--color-text-tertiary)] hover:text-[var(--color-primary)] hover:bg-slate-100 dark:hover:bg-slate-700 rounded transition-colors"
                        title="Download QR Code"
                    >
                        <Download size={16} />
                    </button>
                    <button
                        onClick={handleCopy}
                        className="p-2 text-[var(--color-text-tertiary)] hover:text-[var(--color-primary)] hover:bg-slate-100 dark:hover:bg-slate-700 rounded transition-colors"
                        title="Copy QR Code"
                    >
                        {copied ? <Check size={16} className="text-[var(--color-primary)]" /> : <Copy size={16} />}
                    </button>
                    <button
                        onClick={handlePrint}
                        className="p-2 text-[var(--color-text-tertiary)] hover:text-[var(--color-primary)] hover:bg-slate-100 dark:hover:bg-slate-700 rounded transition-colors"
                        title="Print Label"
                    >
                        <Printer size={16} />
                    </button>
                </div>
            )}
        </div>
    );
}
