'use client';

import React, { useState, useRef } from 'react';
import { QRCodeSVG } from 'qrcode.react';
import { toPng } from 'html-to-image';
import { Star, Download, AlertCircle } from 'lucide-react';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';

const QR_COLORS = [
    { name: 'Google Blue', value: '#1A73E8' },
    { name: 'Classic Black', value: '#000000' },
    { name: 'Indigo', value: '#4F46E5' },
    { name: 'Emerald', value: '#10B981' },
    { name: 'Rose', value: '#F43F5E' },
    { name: 'Violet', value: '#7C3AED' },
];

const FRAME_OPTIONS = [
    { id: 'none', label: 'No Frame' },
    { id: 'review', label: 'Leave a Review' },
    { id: 'scanme', label: 'Scan Me' },
    { id: 'feedback', label: 'Share Feedback' },
];

function isValidGoogleReviewLink(url: string): boolean {
    try {
        const parsed = new URL(url);
        return (
            parsed.hostname.includes('google.com') ||
            parsed.hostname.includes('g.page') ||
            parsed.hostname.includes('maps.app.goo.gl')
        );
    } catch {
        return false;
    }
}

export default function GoogleReviewGenerator() {
    const [reviewUrl, setReviewUrl] = useState('');
    const [qrColor, setQrColor] = useState('#1A73E8');
    const [frameType, setFrameType] = useState('review');
    const [error, setError] = useState('');

    const qrRef = useRef<HTMLDivElement>(null);

    const handleUrlChange = (value: string) => {
        setReviewUrl(value);
        if (value && !isValidGoogleReviewLink(value)) {
            setError('Please enter a valid Google Review link (google.com, g.page, or maps.app.goo.gl)');
        } else {
            setError('');
        }
    };

    const handleDownload = async (format: 'png' | 'svg') => {
        if (!qrRef.current) return;
        try {
            if (format === 'png') {
                const dataUrl = await toPng(qrRef.current, { cacheBust: true, pixelRatio: 3 });
                const link = document.createElement('a');
                link.download = 'google-review-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 url = URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = 'google-review-qr-code.svg';
                    link.click();
                }
            }
        } catch (err) {
            console.error('Download failed', err);
        }
    };

    const frameLabel = FRAME_OPTIONS.find(f => f.id === frameType && f.id !== 'none')?.label ?? null;
    const isReady = reviewUrl && !error && isValidGoogleReviewLink(reviewUrl);

    return (
        <div className="w-full max-w-5xl mx-auto px-4 md:px-6">
            <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 */}
                    <div className="p-6 md:p-8 lg:p-10 space-y-8 border-r border-slate-100">

                        <div className="space-y-4">
                            <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                                <Star className="w-5 h-5 text-yellow-500" />
                                Your Google Review Link
                            </h2>

                            <div>
                                <Input
                                    type="url"
                                    placeholder="https://g.page/r/YOUR_ID/review"
                                    value={reviewUrl}
                                    onChange={(e) => handleUrlChange(e.target.value)}
                                    className="w-full font-mono text-sm"
                                />
                                {error && (
                                    <div className="mt-2 flex items-center gap-2 text-sm text-red-600">
                                        <AlertCircle className="w-4 h-4 shrink-0" />
                                        {error}
                                    </div>
                                )}
                                {!reviewUrl && (
                                    <p className="mt-2 text-xs text-slate-500">
                                        Go to Google Maps → find your business → Share → Copy link
                                    </p>
                                )}
                            </div>
                        </div>

                        {/* Color Picker */}
                        <div className="space-y-3">
                            <h3 className="text-sm font-semibold text-slate-700">QR Color</h3>
                            <div className="flex flex-wrap gap-2">
                                {QR_COLORS.map((color) => (
                                    <button
                                        key={color.value}
                                        onClick={() => setQrColor(color.value)}
                                        className={`w-8 h-8 rounded-full border-2 transition-all ${
                                            qrColor === color.value
                                                ? 'border-slate-900 scale-110'
                                                : 'border-transparent hover:border-slate-300'
                                        }`}
                                        style={{ backgroundColor: color.value }}
                                        title={color.name}
                                    />
                                ))}
                            </div>
                        </div>

                        {/* Frame */}
                        <div className="space-y-3">
                            <h3 className="text-sm font-semibold text-slate-700">Frame Label</h3>
                            <div className="grid grid-cols-2 gap-2">
                                {FRAME_OPTIONS.map((frame) => (
                                    <button
                                        key={frame.id}
                                        onClick={() => setFrameType(frame.id)}
                                        className={`px-3 py-2 rounded-xl text-sm font-medium border transition-all ${
                                            frameType === frame.id
                                                ? 'border-blue-600 bg-blue-50 text-blue-700'
                                                : 'border-slate-200 text-slate-600 hover:border-slate-300'
                                        }`}
                                    >
                                        {frame.label}
                                    </button>
                                ))}
                            </div>
                        </div>

                        {/* Download Buttons */}
                        <div className="space-y-3">
                            <Button
                                onClick={() => handleDownload('png')}
                                disabled={!isReady}
                                className="w-full flex items-center justify-center gap-2"
                            >
                                <Download className="w-4 h-4" />
                                Download PNG
                            </Button>
                            <button
                                onClick={() => handleDownload('svg')}
                                disabled={!isReady}
                                className="w-full px-4 py-2.5 rounded-xl border border-slate-200 text-slate-700 text-sm font-medium hover:border-slate-300 hover:bg-slate-50 transition-all disabled:opacity-40 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                            >
                                <Download className="w-4 h-4" />
                                Download SVG
                            </button>
                        </div>
                    </div>

                    {/* RIGHT: Preview */}
                    <div className="p-6 md:p-8 lg:p-10 flex flex-col items-center justify-center bg-slate-50">
                        <h3 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-6">Preview</h3>

                        <div ref={qrRef} className="flex flex-col items-center bg-white p-6 rounded-2xl shadow-sm border border-slate-100">
                            <QRCodeSVG
                                value={isReady ? reviewUrl : 'https://www.qrmaster.net/tools/google-review-qr-code'}
                                size={200}
                                fgColor={qrColor}
                                level="Q"
                                includeMargin={true}
                            />
                            {frameLabel && (
                                <div
                                    className="mt-3 px-4 py-1.5 rounded-full text-sm font-semibold text-white"
                                    style={{ backgroundColor: qrColor }}
                                >
                                    {frameLabel}
                                </div>
                            )}
                        </div>

                        {!isReady && (
                            <p className="mt-4 text-xs text-slate-400 text-center max-w-[200px]">
                                Enter your Google Review link to generate your QR code
                            </p>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
}
