'use client';

import React, { useState, useRef } from 'react';
import Link from 'next/link';
import { QRCodeSVG } from 'qrcode.react';
import {
    Mail,
    Download,
    Check,
    Sparkles,
    Type,
    FileText
} 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: '#EBEBDF',
    richRed: '#dc2626',
};

// QR Color Options
const QR_COLORS = [
    { name: 'Classic Black', value: '#000000' },
    { name: 'Email Red', value: '#dc2626' },
    { name: 'Deep Blue', value: '#1E40AF' },
    { name: 'Violet', value: '#7C3AED' },
    { name: 'Teal', value: '#0D9488' },
    { name: 'Coral', value: '#F43F5E' },
    { name: 'Emerald', value: '#10B981' },
    { name: 'Rose', value: '#F43F5E' },
];

// Frame Options
const FRAME_OPTIONS = [
    { id: 'none', label: 'No Frame' },
    { id: 'email', label: 'Email Me' },
    { id: 'contact', label: 'Contact' },
    { id: 'send', label: 'Send Mail' },
];

export default function EmailGenerator() {
    const [formData, setFormData] = useState({
        email: '',
        subject: '',
        body: ''
    });

    const [qrColor, setQrColor] = useState('#dc2626');
    const [frameType, setFrameType] = useState('none');

    const qrRef = useRef<HTMLDivElement>(null);

    // Generate Mailto Link
    // Format: mailto:email?subject=...&body=...
    const getMailtoUrl = () => {
        const params = new URLSearchParams();
        if (formData.subject) params.append('subject', formData.subject);
        if (formData.body) params.append('body', formData.body);

        const queryString = params.toString();
        return `mailto:${formData.email}${queryString ? `?${queryString}` : ''}`;
    };

    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 = `email-qr-code.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 urlBlob = URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = urlBlob;
                    link.download = `email-qr-code.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;
    };

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    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">

                        {/* Input Fields */}
                        <div className="space-y-6">
                            <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                                <Mail className="w-5 h-5 text-red-600" />
                                Email Details
                            </h2>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-2">Recipient Email</label>
                                <div className="relative">
                                    <Mail className="absolute left-3 top-3 w-4 h-4 text-slate-400" />
                                    <Input
                                        name="email"
                                        placeholder="recipient@example.com"
                                        value={formData.email}
                                        onChange={handleChange}
                                        className="h-11 rounded-xl pl-9"
                                        type="email"
                                    />
                                </div>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-2">Subject Line</label>
                                <div className="relative">
                                    <Type className="absolute left-3 top-3 w-4 h-4 text-slate-400" />
                                    <Input
                                        name="subject"
                                        placeholder="e.g. Inquiry about services"
                                        value={formData.subject}
                                        onChange={handleChange}
                                        className="h-11 rounded-xl pl-9"
                                    />
                                </div>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-2">Body Message (Optional)</label>
                                <textarea
                                    name="body"
                                    placeholder="Hi there, I would like to know more about..."
                                    value={formData.body}
                                    onChange={handleChange}
                                    className="w-full h-32 p-3 rounded-xl border border-slate-200 focus:border-red-600 focus:ring-1 focus:ring-red-600 focus:outline-none resize-none text-base"
                                />
                            </div>
                        </div>

                        {/* Divider */}
                        <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-red-600" />
                                Design Options
                            </h2>

                            {/* Color Picker */}
                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-3">QR Code 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 }}
                                            aria-label={`Select ${c.name}`}
                                            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 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-red-600 text-white border-red-600"
                                                    : "bg-slate-50 text-slate-600 border-slate-200 hover:border-slate-300"
                                            )}
                                        >
                                            {frame.label}
                                        </button>
                                    ))}
                                </div>
                            </div>
                        </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 }}>

                        {/* 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-[320px]"
                        >
                            {/* 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={getMailtoUrl() || 'mailto:hello@example.com'}
                                    size={240}
                                    level="M"
                                    includeMargin={false}
                                    fgColor={qrColor}
                                />
                            </div>

                            {/* Info */}
                            <div className="mt-6 text-center">
                                <div className="flex items-center justify-center w-12 h-12 rounded-full bg-red-50 mx-auto mb-3">
                                    <Mail className="w-6 h-6 text-red-600" />
                                </div>
                                <h3 className="font-bold text-slate-900 text-lg truncate max-w-[260px] mx-auto">
                                    {formData.email || 'Email QR Code'}
                                </h3>

                            </div>
                        </div>

                        {/* Download Buttons */}
                        <div className="flex items-center gap-3 mt-8">
                            <Button
                                onClick={() => handleDownload('png')}
                                className="bg-red-600 hover:bg-red-700 text-white shadow-lg"
                            >
                                <Download className="w-4 h-4 mr-2" />
                                Download PNG
                            </Button>
                            <Button
                                onClick={() => handleDownload('svg')}
                                variant="outline"
                                className="border-slate-300 hover:bg-white"
                            >
                                <Download className="w-4 h-4 mr-2" />
                                SVG
                            </Button>
                        </div>

                        <p className="text-xs text-slate-500 mt-4 text-center">
                            100% free. No signup required.
                        </p>
                    </div>
                </div>
            </div>

            {/* Upsell Banner */}
            <div className="mt-8 bg-gradient-to-r from-red-600 to-rose-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">Change your email address often?</h3>
                    <p className="text-white/80 text-sm mt-1">Dynamic QR Codes allow you to update the recipient without reprinting.</p>
                </div>
                <Link href="/signup">
                    <Button className="bg-white text-red-700 hover:bg-slate-100 shrink-0 shadow-lg">
                        Go Dynamic
                    </Button>
                </Link>
            </div>
        </div>
    );
}
