'use client';

import React, { useState, useRef } from 'react';
import Link from 'next/link';
import { QRCodeSVG } from 'qrcode.react';
import {
    User,
    Download,
    Check,
    Sparkles,
    Briefcase,
    Phone,
    Mail,
    Globe,
    MapPin,
    Contact
} from 'lucide-react';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { cn } from '@/lib/utils';

// Brand Colors
const BRAND = {
    paleGrey: '#FFF1F2', // Rose-50
    primary: '#E11D48',  // Rose-600
    primaryDark: '#BE123C', // Rose-700
};

// QR Color Options
const QR_COLORS = [
    { name: 'Rose', value: '#E11D48' },
    { name: 'Pink', value: '#DB2777' },
    { name: 'Classic Black', value: '#000000' },
    { name: 'Navy', value: '#1E3A8A' },
    { name: 'Purple', value: '#7C3AED' },
    { name: 'Emerald', value: '#10B981' },
    { name: 'Rose', value: '#F43F5E' },
];

// Frame Options
const FRAME_OPTIONS = [
    { id: 'none', label: 'No Frame' },
    { id: 'scanme', label: 'Scan Me' },
    { id: 'contact', label: 'Save Contact' },
    { id: 'vcard', label: 'vCard' },
];

export default function VCardGenerator() {
    // Personal Info
    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');
    const [email, setEmail] = useState('');
    const [phone, setPhone] = useState('');
    const [website, setWebsite] = useState('');
    const [jobTitle, setJobTitle] = useState('');
    const [company, setCompany] = useState('');

    // Address
    const [street, setStreet] = useState('');
    const [city, setCity] = useState('');
    const [zip, setZip] = useState('');
    const [country, setCountry] = useState('');

    const [qrColor, setQrColor] = useState(BRAND.primary);
    const [frameType, setFrameType] = useState('none');

    const qrRef = useRef<HTMLDivElement>(null);

    // Generate VCard String
    const generateVCard = () => {
        const vcard = [
            'BEGIN:VCARD',
            'VERSION:3.0',
            `N:${lastName};${firstName};;;`,
            `FN:${firstName} ${lastName}`,
            `ORG:${company}`,
            `TITLE:${jobTitle}`,
            `TEL;TYPE=CELL:${phone}`,
            `EMAIL;TYPE=WORK:${email}`,
            `URL:${website}`,
            `ADR;TYPE=WORK:;;${street};${city};;${zip};${country}`,
            'END:VCARD'
        ].join('\n');
        return vcard;
    };

    const handleDownload = async (format: 'png' | 'svg') => {
        if (!qrRef.current) return;
        try {
            if (format === 'png') {
                const { toPng } = await import('html-to-image');
                const dataUrl = await toPng(qrRef.current, { cacheBust: true, pixelRatio: 3 });
                const link = document.createElement('a');
                link.download = `vcard-${firstName || 'contact'}.png`;
                link.href = dataUrl;
                link.click();
            } else {
                const svgData = qrRef.current.querySelector('svg')?.outerHTML;
                if (svgData) {
                    const blob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
                    const url = URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = `vcard-${firstName || 'contact'}.svg`;
                    link.click();
                }
            }
        } catch (err) {
            console.error('Download failed', err);
        }
    };

    const getFrameLabel = () => {
        const frame = FRAME_OPTIONS.find(f => f.id === frameType);
        return frame?.id !== 'none' ? frame?.label : null;
    };

    return (
        <div className="w-full max-w-6xl 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-12">

                    {/* LEFT: Input Section (Wider for VCard) */}
                    <div className="lg:col-span-7 p-6 md:p-8 lg:p-10 space-y-8 border-r border-slate-100">

                        {/* Personal Details */}
                        <div className="space-y-6">
                            <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                                <User className="w-5 h-5 text-[#E11D48]" />
                                Contact Information
                            </h2>

                            <div className="grid sm:grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-2">First Name</label>
                                    <Input placeholder="John" value={firstName} onChange={(e) => setFirstName(e.target.value)} className="h-11 rounded-xl border-slate-200 focus:border-[#E11D48] focus:ring-[#E11D48]" />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-2">Last Name</label>
                                    <Input placeholder="Doe" value={lastName} onChange={(e) => setLastName(e.target.value)} className="h-11 rounded-xl border-slate-200 focus:border-[#E11D48] focus:ring-[#E11D48]" />
                                </div>
                            </div>

                            <div className="grid sm:grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-2">Phone</label>
                                    <div className="relative">
                                        <Phone className="absolute left-3 top-3 w-5 h-5 text-slate-400" />
                                        <Input placeholder="+1 555 000 0000" value={phone} onChange={(e) => setPhone(e.target.value)} className="pl-10 h-11 rounded-xl border-slate-200 focus:border-[#E11D48] focus:ring-[#E11D48]" />
                                    </div>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-2">Email</label>
                                    <div className="relative">
                                        <Mail className="absolute left-3 top-3 w-5 h-5 text-slate-400" />
                                        <Input placeholder="john@company.com" value={email} onChange={(e) => setEmail(e.target.value)} className="pl-10 h-11 rounded-xl border-slate-200 focus:border-[#E11D48] focus:ring-[#E11D48]" />
                                    </div>
                                </div>
                            </div>

                            <div className="grid sm:grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-2">Website</label>
                                    <div className="relative">
                                        <Globe className="absolute left-3 top-3 w-5 h-5 text-slate-400" />
                                        <Input placeholder="https://..." value={website} onChange={(e) => setWebsite(e.target.value)} className="pl-10 h-11 rounded-xl border-slate-200 focus:border-[#E11D48] focus:ring-[#E11D48]" />
                                    </div>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-2">Job Title</label>
                                    <div className="relative">
                                        <Briefcase className="absolute left-3 top-3 w-5 h-5 text-slate-400" />
                                        <Input placeholder="Manager" value={jobTitle} onChange={(e) => setJobTitle(e.target.value)} className="pl-10 h-11 rounded-xl border-slate-200 focus:border-[#E11D48] focus:ring-[#E11D48]" />
                                    </div>
                                </div>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-2">Company</label>
                                <Input placeholder="Acme Corp" value={company} onChange={(e) => setCompany(e.target.value)} className="h-11 rounded-xl border-slate-200 focus:border-[#E11D48] focus:ring-[#E11D48]" />
                            </div>
                        </div>

                        {/* Address Details */}
                        <div className="space-y-6">
                            <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                                <MapPin className="w-5 h-5 text-[#E11D48]" />
                                Address
                            </h2>
                            <div className="grid sm:grid-cols-2 gap-4">
                                <div className="sm:col-span-2">
                                    <label className="block text-sm font-medium text-slate-700 mb-2">Street</label>
                                    <Input placeholder="123 Business Rd" value={street} onChange={(e) => setStreet(e.target.value)} className="h-11 rounded-xl border-slate-200 focus:border-[#E11D48] focus:ring-[#E11D48]" />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-2">City</label>
                                    <Input placeholder="New York" value={city} onChange={(e) => setCity(e.target.value)} className="h-11 rounded-xl border-slate-200 focus:border-[#E11D48] focus:ring-[#E11D48]" />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-2">Zip/Postcode</label>
                                    <Input placeholder="10001" value={zip} onChange={(e) => setZip(e.target.value)} className="h-11 rounded-xl border-slate-200 focus:border-[#E11D48] focus:ring-[#E11D48]" />
                                </div>
                                <div className="sm:col-span-2">
                                    <label className="block text-sm font-medium text-slate-700 mb-2">Country</label>
                                    <Input placeholder="USA" value={country} onChange={(e) => setCountry(e.target.value)} className="h-11 rounded-xl border-slate-200 focus:border-[#E11D48] focus:ring-[#E11D48]" />
                                </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-[#E11D48]" />
                                Design Options
                            </h2>

                            <div className="grid sm:grid-cols-2 gap-8">
                                {/* Color Picker */}
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-3">QR Color</label>
                                    <div className="flex flex-wrap gap-2">
                                        {QR_COLORS.map((c) => (
                                            <button
                                                key={c.name}
                                                onClick={() => setQrColor(c.value)}
                                                className={cn(
                                                    "w-9 h-9 rounded-full border-2 flex items-center justify-center transition-all hover:scale-110",
                                                    qrColor === c.value ? "border-slate-900 ring-2 ring-offset-2 ring-slate-200" : "border-white shadow-md"
                                                )}
                                                style={{ backgroundColor: c.value }}
                                                title={c.name}
                                            >
                                                {qrColor === c.value && <Check className="w-4 h-4 text-white" strokeWidth={3} />}
                                            </button>
                                        ))}
                                    </div>
                                </div>

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

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

                        {/* QR Card with Frame */}
                        <div
                            ref={qrRef}
                            className="bg-white rounded-3xl shadow-xl p-6 sm:p-8 flex flex-col items-center w-full max-w-[300px]"
                        >
                            {/* Frame Label */}
                            {getFrameLabel() && (
                                <div
                                    className="mb-5 px-8 py-2.5 rounded-full text-white font-bold text-sm tracking-widest uppercase shadow-md"
                                    style={{ backgroundColor: qrColor }}
                                >
                                    {getFrameLabel()}
                                </div>
                            )}

                            {/* QR Code */}
                            <div className="bg-white">
                                <QRCodeSVG
                                    value={generateVCard()}
                                    size={220}
                                    level="M"
                                    includeMargin={false}
                                    fgColor={qrColor}
                                />
                            </div>

                            {/* Info Preview */}
                            <div className="mt-6 text-center max-w-[260px]">
                                <h3 className="font-bold text-slate-900 text-lg flex items-center justify-center gap-2 truncate">
                                    <Contact className="w-4 h-4 text-slate-400 shrink-0" />
                                    <span className="truncate">{firstName || 'First'} {lastName || 'Last'}</span>
                                </h3>
                                <div className="text-xs text-slate-600 mt-1 truncate">{company || 'Company Name'}</div>
                            </div>
                        </div>

                        {/* Download Buttons */}
                        <div className="flex flex-col sm:flex-row items-center gap-3 mt-8 w-full max-w-[320px]">
                            <Button
                                onClick={() => handleDownload('png')}
                                className="bg-[#E11D48] hover:bg-[#BE123C] text-white shadow-lg w-full"
                            >
                                <Download className="w-4 h-4 mr-2" />
                                Download PNG
                            </Button>
                            <Button
                                onClick={() => handleDownload('svg')}
                                variant="outline"
                                className="border-slate-300 hover:bg-white w-full"
                            >
                                <Download className="w-4 h-4 mr-2" />
                                SVG
                            </Button>
                        </div>

                        <p className="text-xs text-slate-600 mt-4 text-center">
                            Scanning adds this contact to the address book instantly.
                        </p>
                    </div>
                </div>
            </div>

            {/* Upsell Banner */}
            <div className="mt-8 bg-gradient-to-r from-[#E11D48] to-[#BE123C] 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">Want a Digital Business Card?</h3>
                    <p className="text-white/80 text-sm mt-1">
                        Upgrade to Dynamic vCard to include a profile photo, social links, and update your info anytime.
                    </p>
                </div>
                <Link href="/signup">
                    <Button className="bg-white text-[#E11D48] hover:bg-slate-100 shrink-0 shadow-lg">
                        Create Digital Card
                    </Button>
                </Link>
            </div>
        </div>
    );
}
