'use client';

import React, { useState, useRef } from 'react';
import Link from 'next/link';
import { QRCodeSVG } from 'qrcode.react';
import {
    CreditCard,
    Download,
    Check,
    Sparkles,
    DollarSign
} from 'lucide-react';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Select } from '@/components/ui/Select';
import { cn } from '@/lib/utils';

// Brand Colors - PayPal Blue
const BRAND = {
    paleGrey: '#EFF6FF', // Blue-50
    primary: '#003087',  // PayPal Dark Blue
    primaryDark: '#001F5C',
    accent: '#0070BA',   // PayPal Light Blue
};

// QR Color Options
const QR_COLORS = [
    { name: 'PayPal Blue', value: '#003087' },
    { name: 'PayPal Light', value: '#0070BA' },
    { name: 'Classic Black', value: '#000000' },
    { name: 'Indigo', value: '#4F46E5' },
    { name: 'Violet', 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: 'pay', label: 'Pay Now' },
    { id: 'donate', label: 'Donate' },
    { id: 'tip', label: 'Tip Me' },
];

// Currency Options
const CURRENCIES = [
    { value: 'EUR', label: 'EUR (€)' },
    { value: 'USD', label: 'USD ($)' },
    { value: 'GBP', label: 'GBP (£)' },
    { value: 'CHF', label: 'CHF' },
];

// Input type options
const INPUT_TYPES = [
    { id: 'username', label: 'PayPal.me Username' },
    { id: 'email', label: 'PayPal Email' },
];

export default function PayPalGenerator() {
    const [inputType, setInputType] = useState('email');
    const [paypalId, setPaypalId] = useState('');
    const [amount, setAmount] = useState('');
    const [currency, setCurrency] = useState('EUR');
    const [qrColor, setQrColor] = useState(BRAND.primary);
    const [frameType, setFrameType] = useState('none');

    const qrRef = useRef<HTMLDivElement>(null);

    // Generate PayPal payment link
    const generatePayPalLink = () => {
        if (!paypalId.trim()) return 'https://paypal.com';

        if (inputType === 'username') {
            // PayPal.me link
            let link = `https://paypal.me/${paypalId.trim()}`;
            if (amount && parseFloat(amount) > 0) {
                link += `/${amount}`;
            }
            return link;
        } else {
            // PayPal email payment link (donation/payment format)
            const params = new URLSearchParams({
                cmd: '_donations',
                business: paypalId.trim(),
                currency_code: currency,
                ...(amount && parseFloat(amount) > 0 ? { amount } : {}),
            });
            return `https://www.paypal.com/cgi-bin/webscr?${params.toString()}`;
        }
    };

    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 = `paypal-qr-${paypalId || '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 url = URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = `paypal-qr-${paypalId || '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;
    };

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

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

                            <div className="space-y-4">
                                {/* Input Type Toggle */}
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-2">Payment Method</label>
                                    <div className="grid grid-cols-2 gap-2">
                                        {INPUT_TYPES.map((type) => (
                                            <button
                                                key={type.id}
                                                onClick={() => setInputType(type.id)}
                                                className={cn(
                                                    "py-2.5 px-3 rounded-lg text-sm font-medium transition-all border",
                                                    inputType === type.id
                                                        ? "bg-[#003087] text-white border-[#003087]"
                                                        : "bg-slate-50 text-slate-600 border-slate-200 hover:border-slate-300"
                                                )}
                                            >
                                                {type.label}
                                            </button>
                                        ))}
                                    </div>
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-slate-700 mb-2">
                                        {inputType === 'username' ? 'PayPal.me Username' : 'PayPal Email Address'}
                                    </label>
                                    <Input
                                        type={inputType === 'email' ? 'email' : 'text'}
                                        placeholder={inputType === 'username' ? 'e.g. johndoe' : 'e.g. mail@example.com'}
                                        value={paypalId}
                                        onChange={(e) => setPaypalId(e.target.value)}
                                        className="h-12 text-base rounded-xl border-slate-200 focus:border-[#003087] focus:ring-[#003087]"
                                    />
                                    <p className="text-xs text-slate-600 mt-2">
                                        {inputType === 'username'
                                            ? <>Find yours at <a href="https://paypal.me" target="_blank" rel="noopener noreferrer" className="text-[#003087] underline">paypal.me</a></>
                                            : 'The email address linked to your PayPal account'
                                        }
                                    </p>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <label className="block text-sm font-medium text-slate-700 mb-2">Amount (Optional)</label>
                                        <Input
                                            type="number"
                                            placeholder="25.00"
                                            value={amount}
                                            onChange={(e) => setAmount(e.target.value)}
                                            className="h-12 text-base rounded-xl border-slate-200 focus:border-[#003087] focus:ring-[#003087]"
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-slate-700 mb-2">Currency</label>
                                        <Select
                                            value={currency}
                                            onChange={(e) => setCurrency(e.target.value)}
                                            className="h-12 rounded-xl border-slate-200"
                                            aria-label="Currency"
                                            options={CURRENCIES}
                                        />
                                    </div>
                                </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-[#003087]" />
                                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-5 gap-2">
                                    {FRAME_OPTIONS.map((frame) => (
                                        <button
                                            key={frame.id}
                                            onClick={() => setFrameType(frame.id)}
                                            className={cn(
                                                "py-2.5 px-2 rounded-lg text-xs font-medium transition-all border",
                                                frameType === frame.id
                                                    ? "bg-[#003087] text-white border-[#003087]"
                                                    : "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={generatePayPalLink()}
                                    size={240}
                                    level="M"
                                    includeMargin={false}
                                    fgColor={qrColor}
                                />
                            </div>

                            {/* PayPal Info */}
                            <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">
                                    <DollarSign className="w-4 h-4 text-[#003087] shrink-0" />
                                    <span className="truncate">{paypalId || 'Your PayPal'}</span>
                                </h3>
                                {amount && (
                                    <p className="text-sm text-slate-600 mt-1">{amount} {currency}</p>
                                )}
                            </div>
                        </div>

                        {/* Download Buttons */}
                        <div className="flex items-center gap-3 mt-8">
                            <Button
                                onClick={() => handleDownload('png')}
                                className="bg-[#003087] hover:bg-[#001F5C] 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-600 mt-4 text-center">
                            Your PayPal link is encoded directly. Static and forever free.
                        </p>
                    </div>
                </div>
            </div>

            {/* Upsell Banner */}
            <div className="mt-8 bg-gradient-to-r from-[#003087] to-[#0070BA] 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 payment analytics?</h3>
                    <p className="text-white/80 text-sm mt-1">Track how many people scan your payment QR code with Dynamic QR Codes.</p>
                </div>
                <Link href="/signup">
                    <Button className="bg-white text-[#003087] hover:bg-slate-100 shrink-0 shadow-lg">
                        Get Analytics
                    </Button>
                </Link>
            </div>
        </div>
    );
}
