'use client';

import React, { useState, useRef } from 'react';
import Barcode from 'react-barcode';
import Link from 'next/link';
import { Download, Printer, Barcode as BarcodeIcon, Sparkles, Sliders, Check, Info, Copy } from 'lucide-react';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Select } from '@/components/ui/Select';
import { showToast } from '@/components/ui/Toast';
import { cn } from '@/lib/utils';
import { toPng, toSvg, toBlob } from 'html-to-image';
import { trackEvent } from '@/components/PostHogProvider';

// Brand Colors
const BRAND = {
    paleGrey: '#EBEBDF',
    slate900: '#0f172a',
};

const BARCODE_COLORS = [
    { name: 'Classic Black', value: '#000000' },
    { name: 'Dark Blue', value: '#1A1265' },
    { name: 'Rich Indigo', value: '#4338CA' },
    { name: 'Deep Emerald', value: '#065F46' },
    { name: 'Crimson', value: '#991B1B' },
    { name: 'Slate Gray', value: '#334155' },
    { name: 'Business Navy', value: '#1E293B' },
];

const FRAME_OPTIONS = [
    { id: 'none', label: 'No Frame' },
    { id: 'scanme', label: 'Scan Me' },
    { id: 'product', label: 'Product' },
    { id: 'serial', label: 'Serial' },
];

const FORMAT_INFO: Record<string, string> = {
    'CODE128': 'High-density alphanumeric format. Best for general purpose use.',
    'EAN13': 'International retail standard for products worldwide.',
    'UPC': 'Standard retail format used primarily in North America.',
    'CODE39': 'Older industrial standard supporting uppercase letters and numbers.',
    'ITF14': 'Used on shipping containers and logistics packaging.',
    'MSI': 'Specialized format for retail shelf labeling and inventory.',
    'pharmacode': 'Pharmaceutical packaging control standard.',
};

export default function BarcodeGeneratorClient() {
    const [value, setValue] = useState('123456789');
    const [format, setFormat] = useState('CODE128');
    const [width, setWidth] = useState(2);
    const [height, setHeight] = useState(100);
    const [displayValue, setDisplayValue] = useState(true);
    const [lineColor, setLineColor] = useState('#000000');
    const [frameType, setFrameType] = useState('none');
    const [error, setError] = useState<string | null>(null);

    const barcodeRef = useRef<HTMLDivElement>(null);

    // Validation Logic
    React.useEffect(() => {
        setError(null);
        if (!value) return;

        if (format === 'EAN13' && !/^\d{12,13}$/.test(value)) {
            setError('EAN-13 requires 12 or 13 digits.');
        } else if (format === 'UPC' && !/^\d{11,12}$/.test(value)) {
            setError('UPC requires 11 or 12 digits.');
        } else if (format === 'CODE39' && !/^[0-9A-Z\-\.\ \$\/\+\%]+$/.test(value)) {
            setError('Code 39 only supports numbers, uppercase letters, and - . $ / + % spaces.');
        } else if ((format === 'ITF14' || format === 'MSI') && !/^\d+$/.test(value)) {
            setError('This format only supports numbers.');
        }

        if (value && !error) {
            trackEvent('barcode_generated', {
                format: format,
                content_length: value.length,
                width: width,
                height: height,
                display_value: displayValue,
                line_color: lineColor,
                frame_type: frameType
            });
        }
    }, [value, format, width, height, displayValue, lineColor, frameType, error]);

    const downloadBarcode = async (extension: 'png' | 'svg') => {
        if (!barcodeRef.current) return;

        try {
            let dataUrl;
            if (extension === 'png') {
                dataUrl = await toPng(barcodeRef.current, {
                    backgroundColor: '#ffffff',
                    pixelRatio: 3,
                });
            } else {
                dataUrl = await toSvg(barcodeRef.current, {
                    backgroundColor: '#ffffff',
                });
            }

            const link = document.createElement('a');
            link.href = dataUrl;
            link.download = `barcode-${value || 'generator'}.${extension}`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            showToast(`Barcode downloaded as ${extension.toUpperCase()}`, 'success');
            trackEvent('barcode_downloaded', {
                format: format,
                extension: extension,
                frame_type: frameType
            });
        } catch (err) {
            console.error('Download failed', err);
            showToast('Download failed', 'error');
        }
    };

    const copyBarcode = async () => {
        if (!barcodeRef.current) return;
        try {
            // Use toBlob directly for better performance and compatibility
            const blob = await toBlob(barcodeRef.current, {
                backgroundColor: '#ffffff',
                pixelRatio: 3,
            });

            if (!blob) {
                throw new Error('Failed to generate image blob');
            }

            await navigator.clipboard.write([
                new ClipboardItem({
                    'image/png': blob,
                }),
            ]);
            showToast('Barcode copied to clipboard', 'success');
            trackEvent('barcode_copied', {
                format: format,
                frame_type: frameType
            });
        } catch (err) {
            console.error('Copy failed', err);
            showToast('Failed to copy barcode', 'error');
        }
    };

    const formats = [
        { value: 'CODE128', label: 'Code 128 (Standard)' },
        { value: 'EAN13', label: 'EAN-13 (Retail)' },
        { value: 'UPC', label: 'UPC-A (US Retail)' },
        { value: 'CODE39', label: 'Code 39' },
        { value: 'ITF14', label: 'ITF-14' },
        { value: 'MSI', label: 'MSI' },
        { value: 'pharmacode', label: 'Pharmacode' },
    ];

    return (
        <div className="w-full max-w-5xl mx-auto px-4 md:px-6">

            {/* Main Generator Card */}
            <div className="bg-white rounded-3xl shadow-2xl shadow-slate-900/10 overflow-hidden border border-slate-100">
                <div className="grid lg:grid-cols-2">

                    {/* LEFT: Input Section */}
                    <div className="p-6 md:p-8 lg:p-10 space-y-8 border-r border-slate-100">

                        {/* Configuration */}
                        <div className="space-y-6">
                            <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                                <Sliders className="w-5 h-5 text-slate-900" aria-hidden="true" />
                                Configuration
                            </h2>

                            <div className="space-y-4">
                                <div>
                                    <label htmlFor="barcode-content" className="block text-sm font-medium text-slate-700 mb-2">Content</label>
                                    <Input
                                        id="barcode-content"
                                        value={value}
                                        onChange={(e) => setValue(e.target.value)}
                                        placeholder="Enter barcode data (e.g. 12345678)"
                                        className="h-12 text-base rounded-xl border-slate-200 focus:border-slate-900 focus:ring-slate-900"
                                        aria-label="Barcode content"
                                    />
                                </div>

                                <div>
                                    <div className="flex items-center justify-between mb-2">
                                        <label className="block text-sm font-medium text-slate-700">Format</label>
                                        <div className="group relative">
                                            <Info className="w-4 h-4 text-slate-400 cursor-help" />
                                            <div className="absolute right-0 bottom-full mb-2 w-64 p-3 bg-slate-900 text-white text-[11px] rounded-xl opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none shadow-xl z-50">
                                                <p className="font-bold mb-1">Format Guide:</p>
                                                <p>{FORMAT_INFO[format]}</p>
                                            </div>
                                        </div>
                                    </div>
                                    <Select
                                        value={format}
                                        onChange={(e) => setFormat(e.target.value)}
                                        className="h-12 rounded-xl border-slate-200"
                                        options={formats}
                                        aria-label="Format"
                                    />
                                    <p className="text-[10px] text-slate-500 mt-2 px-1">
                                        {FORMAT_INFO[format]}
                                    </p>
                                </div>
                            </div>
                        </div>

                        <div className="border-t border-slate-100"></div>

                        {/* Design Options */}
                        <div className="space-y-6">
                            <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                                <Sparkles className="w-5 h-5 text-slate-900" aria-hidden="true" />
                                Design Options
                            </h2>

                            <div className="grid grid-cols-2 gap-6">
                                <div className="space-y-3">
                                    <div className="flex justify-between">
                                        <label htmlFor="width-range" className="text-sm font-medium text-slate-700">Width</label>
                                        <span className="text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-md font-bold">{width}px</span>
                                    </div>
                                    <input
                                        id="width-range"
                                        type="range"
                                        min="1"
                                        max="4"
                                        step="0.5"
                                        value={width}
                                        onChange={(e) => setWidth(parseFloat(e.target.value))}
                                        className="w-full h-2 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-slate-900"
                                        aria-label="Barcode width"
                                    />
                                </div>

                                <div className="space-y-3">
                                    <div className="flex justify-between">
                                        <label htmlFor="height-range" className="text-sm font-medium text-slate-700">Height</label>
                                        <span className="text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-md font-bold">{height}px</span>
                                    </div>
                                    <input
                                        id="height-range"
                                        type="range"
                                        min="30"
                                        max="200"
                                        step="5"
                                        value={height}
                                        onChange={(e) => setHeight(parseInt(e.target.value))}
                                        className="w-full h-2 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-slate-900"
                                        aria-label="Barcode height"
                                    />
                                </div>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-3">Line Color</label>
                                <div className="flex flex-wrap gap-2">
                                    {BARCODE_COLORS.map((c) => (
                                        <button
                                            key={c.name}
                                            onClick={() => setLineColor(c.value)}
                                            className={cn(
                                                "w-9 h-9 rounded-full border-2 flex items-center justify-center transition-all hover:scale-110",
                                                lineColor === c.value ? "border-slate-900 ring-2 ring-offset-2 ring-slate-200" : "border-white shadow-md"
                                            )}
                                            style={{ backgroundColor: c.value }}
                                            aria-label={`Select color ${c.name}`}
                                            title={c.name}
                                        >
                                            {lineColor === c.value && <Check className="w-4 h-4 text-white" strokeWidth={3} aria-hidden="true" />}
                                        </button>
                                    ))}
                                </div>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-3">Frame Label</label>
                                <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                                    {FRAME_OPTIONS.map((frame) => (
                                        <button
                                            key={frame.id}
                                            onClick={() => setFrameType(frame.id)}
                                            className={cn(
                                                "py-2.5 px-3 rounded-lg text-sm font-medium transition-all border",
                                                frameType === frame.id
                                                    ? "bg-slate-900 text-white border-slate-900"
                                                    : "bg-slate-50 text-slate-600 border-slate-200 hover:border-slate-300"
                                            )}
                                        >
                                            {frame.label}
                                        </button>
                                    ))}
                                </div>
                            </div>

                            <label className="flex items-center gap-3 cursor-pointer group p-3 border border-slate-200 rounded-xl hover:border-slate-900 transition-colors bg-slate-50/50">
                                <div className={cn(
                                    "w-5 h-5 rounded border-2 flex items-center justify-center transition-all",
                                    displayValue ? "bg-slate-900 border-slate-900" : "border-slate-300 group-hover:border-slate-400"
                                )}>
                                    {displayValue && <Check className="w-3.5 h-3.5 text-white" strokeWidth={3} />}
                                </div>
                                <input
                                    type="checkbox"
                                    checked={displayValue}
                                    onChange={(e) => setDisplayValue(e.target.checked)}
                                    className="sr-only"
                                />
                                <span className="text-sm font-medium text-slate-700">Show Value Text</span>
                            </label>

                        </div>
                    </div>

                    {/* RIGHT: Preview Section */}
                    <div className="p-6 md:p-8 lg:p-10 flex flex-col items-center justify-center" style={{ backgroundColor: BRAND.paleGrey }}>

                        {/* Barcode Card */}
                        <div
                            className="bg-white rounded-3xl shadow-xl p-8 flex flex-col items-center justify-center min-h-[300px] w-full max-w-[400px] border border-slate-100 relative"
                        >
                            <div className="absolute top-4 right-4">
                                <div className="flex items-center gap-1.5 px-2 py-1 bg-slate-100 rounded-md text-[10px] font-bold text-slate-500 uppercase tracking-wider">
                                    Live Preview
                                </div>
                            </div>

                            <div ref={barcodeRef} className="py-4 bg-white flex flex-col items-center justify-center overflow-hidden w-full">
                                {frameType !== 'none' && !error && (
                                    <div
                                        className="mb-4 px-6 py-2 rounded-full text-white font-bold text-xs tracking-widest uppercase shadow-md"
                                        style={{ backgroundColor: lineColor }}
                                    >
                                        {FRAME_OPTIONS.find(f => f.id === frameType)?.label}
                                    </div>
                                )}

                                {error ? (
                                    <div className="flex flex-col items-center text-center p-6 animate-in fade-in zoom-in duration-200">
                                        <div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mb-3">
                                            <Info className="w-6 h-6 text-red-500" />
                                        </div>
                                        <p className="text-red-500 font-bold text-sm">{error}</p>
                                        <p className="text-slate-400 text-xs mt-1">Please correct your input.</p>
                                    </div>
                                ) : value ? (
                                    <Barcode
                                        key={`${format}-${lineColor}-${value}-${width}-${height}-${displayValue}`}
                                        value={value}
                                        format={format as any}
                                        width={width}
                                        height={height}
                                        displayValue={displayValue}
                                        background="#ffffff"
                                        lineColor={lineColor}
                                        margin={10}
                                    />
                                ) : (
                                    <div className="text-center text-slate-400 p-6">
                                        <BarcodeIcon className="w-12 h-12 mx-auto mb-3 opacity-30" />
                                        <p className="text-sm font-medium">Enter data to generate</p>
                                    </div>
                                )}
                            </div>

                            {/* Info Preview */}
                            <div className="mt-6 text-center w-full">
                                <h3 className="font-bold text-slate-900 text-lg flex items-center justify-center gap-2 truncate">
                                    <span className="truncate">{formats.find(f => f.value === format)?.label}</span>
                                </h3>
                                <div className="text-xs text-slate-600 mt-1 truncate px-2 font-mono">
                                    {value || 'Barcode Value'}
                                </div>
                            </div>
                        </div>

                        {/* Download Buttons */}
                        <div className="flex flex-col gap-4 mt-8 w-full max-w-[450px]">
                            <div className="flex flex-col sm:flex-row items-center gap-3 w-full">
                                <Button
                                    onClick={() => downloadBarcode('png')}
                                    className="w-full sm:flex-1 bg-slate-900 hover:bg-black text-white shadow-lg h-12 rounded-xl"
                                    aria-label="Download barcode as PNG"
                                >
                                    <Download className="w-4 h-4 mr-2" aria-hidden="true" />
                                    Download PNG
                                </Button>
                                <div className="relative w-full sm:w-auto">
                                    <div className="absolute -top-3 left-1/2 -translate-x-1/2 bg-indigo-600 text-white text-[9px] font-bold px-2 py-0.5 rounded-full whitespace-nowrap shadow-sm z-10 pointer-events-none">
                                        BEST FOR PRINT
                                    </div>
                                    <Button
                                        onClick={() => downloadBarcode('svg')}
                                        variant="outline"
                                        className="w-full sm:w-auto px-6 border-slate-300 hover:bg-white h-12 rounded-xl font-bold"
                                        aria-label="Download barcode as SVG"
                                    >
                                        SVG
                                    </Button>
                                </div>
                                <Button
                                    onClick={copyBarcode}
                                    variant="outline"
                                    className="w-full sm:w-auto px-4 border-slate-300 hover:bg-white h-12 rounded-xl"
                                    title="Copy to Clipboard"
                                    aria-label="Copy barcode image to clipboard"
                                >
                                    <Copy className="w-4 h-4 text-slate-600" aria-hidden="true" />
                                </Button>
                                <Button
                                    onClick={() => window.print()}
                                    variant="outline"
                                    className="w-full sm:w-auto px-4 border-slate-300 hover:bg-white h-12 rounded-xl"
                                    title="Print"
                                    aria-label="Print barcode"
                                >
                                    <Printer className="w-4 h-4 text-slate-600" aria-hidden="true" />
                                </Button>
                            </div>

                            <div className="text-center">
                                <Link href="/signup" className="text-xs font-medium text-slate-400 hover:text-indigo-600 transition-colors flex items-center justify-center gap-1 group">
                                    Need bulk generation?
                                    <span className="underline decoration-slate-300 group-hover:decoration-indigo-300 underline-offset-4">Available in Pro &rarr;</span>
                                </Link>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Upsell Banner */}
            <div className="mt-8 bg-gradient-to-r from-slate-900 to-slate-700 rounded-2xl p-6 flex flex-col sm:flex-row items-center justify-between gap-4">
                <div className="text-white text-center sm:text-left">
                    <h3 className="font-bold text-lg">Need Dynamic QR Codes?</h3>
                    <p className="text-white/80 text-sm mt-1">
                        Switch to QR codes to edit content later and track your scans.
                    </p>
                </div>
                <Link href="/signup">
                    <Button className="bg-white text-slate-900 hover:bg-slate-100 shrink-0 shadow-lg px-8">
                        Get Started Free
                    </Button>
                </Link>
            </div>
        </div>
    );
}
