import React, { useState } from 'react';
import { Star, Clock, ExternalLink, Heart, LifeBuoy, X, CheckCircle2 } from 'lucide-react';
import { useToast } from './Toast';
import { sendReviewAction } from '../api/pdfs';

/**
 * ReviewNotice Component
 *
 * Displays a friendly, respectful review prompt to active users who have
 * spent meaningful time with PDF Rack.
 *
 * Compliant with WordPress.org guidelines:
 * - Neutral invitation for a review (does not directly ask for a 5-star rating).
 * - Links directly to the review creation form without pre-selected rating filters.
 *
 * Anti-irritation features:
 * - Only rendered if user qualifies (time active + real PDFs + visits).
 * - Never blocks work (clean inline banner).
 * - 1-click permanent dismissal ("I already did" / "Don't ask again").
 * - 14-day snooze ("Remind me later" or 'X' button).
 * - Friendly escape hatch linking directly to support for anyone facing an issue.
 */
const ReviewNotice = () => {
    const reviewData = window.pdfRack?.review;
    const { toast } = useToast();

    // Check if review prompt should be visible
    const [visible, setVisible] = useState(() => Boolean(reviewData?.show));
    const [thanked, setThanked] = useState(false);
    const [loadingAction, setLoadingAction] = useState(false);

    if (!visible) {
        return null;
    }

    const userName = window.pdfRack?.userName || '';
    const reviewUrl = reviewData?.reviewUrl || 'https://wordpress.org/support/plugin/pdf-rack/reviews/#new-post';
    const supportUrl = reviewData?.supportUrl || 'https://wordpress.org/support/plugin/pdf-rack/';
    const daysActive = reviewData?.daysActive || 0;
    const pdfCount = reviewData?.pdfCount || 0;

    const handleRate = async () => {
        // Open WordPress.org reviews in new tab
        window.open(reviewUrl, '_blank', 'noopener,noreferrer');
        setThanked(true);

        try {
            await sendReviewAction('rate');
        } catch (err) {
            console.error('Failed to save review action:', err);
        }

        // Keep thank you message visible for a moment then close
        setTimeout(() => {
            setVisible(false);
        }, 4000);
    };

    const handleSnooze = async () => {
        setLoadingAction(true);
        try {
            await sendReviewAction('snooze');
            toast("No problem! We'll remind you in 2 weeks. 😊", { type: 'info' });
        } catch (err) {
            console.error('Failed to snooze review:', err);
        } finally {
            setVisible(false);
        }
    };

    const handleDismiss = async () => {
        setLoadingAction(true);
        try {
            await sendReviewAction('dismiss');
            toast('Got it! We won’t ask you again. Thank you for using PDF Rack!', { type: 'success' });
        } catch (err) {
            console.error('Failed to dismiss review:', err);
        } finally {
            setVisible(false);
        }
    };

    if (thanked) {
        return (
            <div className="relative overflow-hidden rounded-2xl border border-emerald-200 bg-gradient-to-r from-emerald-50 via-white to-teal-50 p-5 shadow-sm animate-fade-up">
                <div className="flex items-center gap-4">
                    <span className="flex size-11 shrink-0 items-center justify-center rounded-2xl bg-emerald-100 text-emerald-600 shadow-sm">
                        <Heart className="size-6 fill-rose-500 text-rose-500 animate-pulse" />
                    </span>
                    <div className="min-w-0 flex-1">
                        <h4 className="text-base font-bold text-slate-900 flex items-center gap-2">
                            <span>Thank you so much!</span>
                            <span className="inline-flex items-center gap-1 text-xs font-semibold text-emerald-700 bg-emerald-100/70 px-2 py-0.5 rounded-full">
                                <CheckCircle2 className="size-3.5" /> Feedback recorded
                            </span>
                        </h4>
                        <p className="mt-0.5 text-sm text-slate-600">
                            Your feedback helps more WordPress creators discover PDF Rack and motivates us to keep making it better! ❤️
                        </p>
                    </div>
                    <button
                        type="button"
                        onClick={() => setVisible(false)}
                        className="rounded-lg p-1.5 text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition-colors"
                        aria-label="Close"
                    >
                        <X className="size-4" />
                    </button>
                </div>
            </div>
        );
    }

    return (
        <div className="relative overflow-hidden rounded-2xl border border-amber-200/90 bg-gradient-to-br from-amber-50/70 via-white to-orange-50/40 p-5 sm:p-6 shadow-sm transition-all duration-300 animate-fade-up">
            {/* Background decorative flair */}
            <div className="pointer-events-none absolute -right-6 -bottom-6 size-32 rounded-full bg-amber-100/40 blur-2xl" />
            <div className="pointer-events-none absolute right-20 top-0 size-20 rounded-full bg-orange-100/30 blur-xl" />

            <button
                type="button"
                onClick={handleSnooze}
                disabled={loadingAction}
                className="absolute top-3.5 right-3.5 p-1.5 text-slate-400 hover:text-slate-700 hover:bg-amber-100/60 rounded-lg transition-colors"
                title="Remind me later"
                aria-label="Close"
            >
                <X className="size-4" />
            </button>

            <div className="flex flex-col sm:flex-row sm:items-start gap-4 sm:gap-5">
                {/* Visual Badge */}
                <div className="flex sm:flex-col items-center gap-2 shrink-0">
                    <span className="flex size-12 shrink-0 items-center justify-center rounded-2xl bg-gradient-to-tr from-amber-400 to-orange-400 text-white shadow-md shadow-amber-500/20">
                        <Star className="size-6 fill-white text-white" />
                    </span>
                </div>

                {/* Content */}
                <div className="flex-1 min-w-0 pr-6 sm:pr-8">
                    <div className="flex flex-wrap items-center gap-2">
                        <h3 className="text-base font-bold text-slate-900">
                            {userName ? `Enjoying PDF Rack, ${userName}?` : 'Enjoying PDF Rack?'}
                        </h3>
                        <span className="inline-flex items-center gap-1 rounded-full bg-amber-100/80 px-2.5 py-0.5 text-[11px] font-semibold text-amber-800">
                            User feedback
                        </span>
                    </div>

                    <p className="mt-1 text-sm text-slate-600 leading-relaxed">
                        {daysActive > 0 && pdfCount > 0 ? (
                            <>
                                You’ve been managing <strong className="font-semibold text-slate-800">{pdfCount} document{pdfCount === 1 ? '' : 's'}</strong> with PDF Rack over the past <strong className="font-semibold text-slate-800">{daysActive} day{daysActive === 1 ? '' : 's'}</strong>!
                            </>
                        ) : (
                            <>We hope PDF Rack is making your PDFs and flipbooks look fantastic!</>
                        )}{' '}
                        If the plugin has been valuable for your site, could you take a moment to leave a review on WordPress.org? Your honest feedback helps others and means the world to our team.
                    </p>

                    {/* Action buttons */}
                    <div className="mt-4 flex flex-wrap items-center gap-2.5">
                        <button
                            type="button"
                            onClick={handleRate}
                            disabled={loadingAction}
                            className="inline-flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 text-white font-semibold text-sm rounded-xl shadow-sm hover:shadow transition-all duration-150 active:scale-98"
                        >
                            <Star className="size-4 fill-white text-white" />
                            <span>Leave a Review</span>
                            <ExternalLink className="size-3.5 opacity-90" />
                        </button>

                        <button
                            type="button"
                            onClick={handleSnooze}
                            disabled={loadingAction}
                            className="inline-flex items-center gap-1.5 px-3.5 py-2 bg-white hover:bg-slate-50 text-slate-700 font-medium text-sm rounded-xl border border-slate-200 shadow-xs transition-colors"
                        >
                            <Clock className="size-3.5 text-slate-400" />
                            <span>Remind me later</span>
                        </button>

                        <button
                            type="button"
                            onClick={handleDismiss}
                            disabled={loadingAction}
                            className="inline-flex items-center px-3 py-2 text-slate-400 hover:text-slate-600 font-medium text-xs rounded-lg transition-colors"
                        >
                            I already did / Don’t show again
                        </button>
                    </div>

                    {/* Support escape hatch to prevent bad reviews & uninstalls */}
                    <div className="mt-3.5 pt-3 border-t border-amber-200/50 flex flex-wrap items-center justify-between text-xs text-slate-500 gap-2">
                        <span className="inline-flex items-center gap-1.5">
                            <LifeBuoy className="size-3.5 text-amber-600/80" />
                            <span>Having an issue or need a feature?</span>
                            <a
                                href={supportUrl}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="font-semibold text-indigo-600 hover:text-indigo-800 underline decoration-indigo-300 underline-offset-2"
                            >
                                Contact Free Support →
                            </a>
                        </span>
                        <span className="text-[11px] text-slate-400">
                            We never show this notice again once reviewed or dismissed.
                        </span>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default ReviewNotice;
