'use client';

import React, { useState, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import { Button } from '@/components/ui/Button';
import { AlertTriangle, CheckCircle, TrendingDown, ArrowRight, RefreshCcw, FileDown, X, Loader2, Mail } from 'lucide-react';
import { generateSavingsReport } from '@/lib/generateSavingsReport';

interface CalculatorResults {
    annualWaste: number;
    withQRMaster: number;
    savings: number;
    savingsPercent: number;
    monthsPaidFor: number;
}

export const ReprintSavingsCalculator: React.FC = () => {
    const [reprintCost, setReprintCost] = useState<string>('');
    const [updatesPerYear, setUpdatesPerYear] = useState<string>('');
    const [showResults, setShowResults] = useState(false);
    const [showEmailModal, setShowEmailModal] = useState(false);
    const [email, setEmail] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [submitError, setSubmitError] = useState('');

    // QR Master Pro yearly cost
    const qrMasterYearlyCost = 108; // €9/month * 12

    const results = useMemo((): CalculatorResults | null => {
        const cost = parseFloat(reprintCost);
        const updates = parseFloat(updatesPerYear);

        if (!cost || !updates || cost <= 0 || updates <= 0) {
            return null;
        }

        const annualWaste = cost * updates;
        const withQRMaster = qrMasterYearlyCost;
        const savings = annualWaste - withQRMaster;

        // Calculate percentages based on the larger value to avoid overflow bars
        const maxValue = Math.max(annualWaste, withQRMaster);
        const wastePercentOfMax = (annualWaste / maxValue) * 100;
        const costPercentOfMax = (withQRMaster / maxValue) * 100;

        const isPositiveSavings = savings > 0;
        const savingsPercent = isPositiveSavings
            ? Math.round((savings / annualWaste) * 100)
            : Math.round((Math.abs(savings) / withQRMaster) * 100);

        const monthsPaidFor = isPositiveSavings
            ? Math.round(annualWaste / (qrMasterYearlyCost / 12))
            : 0;

        return {
            annualWaste,
            withQRMaster,
            savings,
            savingsPercent,
            monthsPaidFor,
        };
    }, [reprintCost, updatesPerYear]);

    const handleCalculate = () => {
        if (results) {
            setShowResults(true);
        }
    };

    const handleReset = () => {
        setShowResults(false);
        setReprintCost('');
        setUpdatesPerYear('');
    };

    const handleDownloadReport = async () => {
        setShowEmailModal(true);
    };

    const handleEmailSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!email || !email.includes('@') || !results) return;

        setIsSubmitting(true);
        setSubmitError('');

        try {
            // Save lead to database
            const response = await fetch('/api/leads', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    email,
                    source: 'reprint-calculator',
                    reprintCost: parseFloat(reprintCost),
                    updatesPerYear: parseInt(updatesPerYear),
                    annualSavings: results.savings,
                }),
            });

            if (!response.ok) {
                throw new Error('Failed to save');
            }

            // Generate and download PDF
            generateSavingsReport({
                reprintCost: parseFloat(reprintCost),
                updatesPerYear: parseInt(updatesPerYear),
                annualWaste: results.annualWaste,
                qrMasterCost: results.withQRMaster,
                savings: results.savings,
                savingsPercent: results.savingsPercent,
            });

            // Close modal and reset
            setShowEmailModal(false);
            setEmail('');
        } catch (error) {
            setSubmitError('Something went wrong. Please try again.');
        } finally {
            setIsSubmitting(false);
        }
    };

    const formatCurrency = (value: number) => {
        return new Intl.NumberFormat('de-DE', {
            style: 'currency',
            currency: 'EUR',
            minimumFractionDigits: 0,
            maximumFractionDigits: 0,
        }).format(value);
    };

    const isPositiveSavings = results ? results.savings > 0 : false;

    return (
        <>
            <section className="py-20 bg-gradient-to-br from-slate-50 to-white relative overflow-hidden">
                {/* Background decoration */}
                <div className="absolute top-0 left-0 w-full h-full overflow-hidden pointer-events-none opacity-40">
                    <div className="absolute -top-[20%] -right-[10%] w-[600px] h-[600px] bg-primary-100/50 rounded-full blur-3xl" />
                    <div className="absolute bottom-[0%] -left-[10%] w-[500px] h-[500px] bg-indigo-50/50 rounded-full blur-3xl" />
                </div>

                <div className="container mx-auto px-4 sm:px-6 lg:px-8 max-w-4xl relative z-10">
                    <motion.div
                        initial={{ opacity: 0, y: 30 }}
                        whileInView={{ opacity: 1, y: 0 }}
                        viewport={{ once: true }}
                        transition={{ duration: 0.6 }}
                        className="bg-white rounded-3xl shadow-xl border border-slate-100 overflow-hidden"
                    >
                        <div className="grid md:grid-cols-5 h-full">

                            {/* Left Side: Form */}
                            <div className={`p-8 md:p-10 ${showResults ? 'md:col-span-2 bg-slate-50 border-r border-slate-100' : 'md:col-span-5'}`}>
                                <AnimatePresence mode="wait">
                                    {!showResults ? (
                                        <motion.div
                                            key="form-intro"
                                            initial={{ opacity: 0 }}
                                            animate={{ opacity: 1 }}
                                            exit={{ opacity: 0 }}
                                            className="max-w-2xl mx-auto md:max-w-none text-center md:text-left"
                                        >
                                            <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-red-50 text-red-600 text-sm font-medium mb-6">
                                                <AlertTriangle className="w-4 h-4" />
                                                Stop wasting budget
                                            </div>
                                            <h2 className="text-3xl font-bold text-slate-900 mb-4 leading-tight">
                                                Calculate your Reprint Waste
                                            </h2>
                                            <p className="text-slate-600 mb-8">
                                                Enter your printing costs to see exactly how much static QR codes are costing you annually.
                                            </p>
                                        </motion.div>
                                    ) : (
                                        <motion.div
                                            key="form-minimized"
                                            initial={{ opacity: 0 }}
                                            animate={{ opacity: 1 }}
                                            exit={{ opacity: 0 }}
                                        >
                                            <h3 className="font-bold text-slate-900 mb-6 flex items-center gap-2">
                                                <RefreshCcw className="w-4 h-4 text-slate-400" />
                                                Parameters
                                            </h3>
                                        </motion.div>
                                    )}
                                </AnimatePresence>

                                <div className="space-y-6">
                                    <div>
                                        <label htmlFor="reprintCost" className="block text-sm font-semibold text-slate-700 mb-2">
                                            Reprint cost per batch
                                        </label>
                                        <div className="relative group">
                                            <span className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-medium text-lg transition-colors group-hover:text-primary-600">€</span>
                                            <input
                                                type="number"
                                                id="reprintCost"
                                                value={reprintCost}
                                                onChange={(e) => setReprintCost(e.target.value)}
                                                placeholder="500"
                                                min="0"
                                                className="w-full pl-10 pr-4 py-3.5 text-lg border border-slate-200 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-primary-500 transition-all shadow-sm group-hover:border-primary-300 bg-white"
                                            />
                                        </div>
                                    </div>

                                    <div>
                                        <label htmlFor="updatesPerYear" className="block text-sm font-semibold text-slate-700 mb-2">
                                            URL updates per year
                                        </label>
                                        <input
                                            type="number"
                                            id="updatesPerYear"
                                            value={updatesPerYear}
                                            onChange={(e) => setUpdatesPerYear(e.target.value)}
                                            placeholder="3"
                                            min="0"
                                            className="w-full px-4 py-3.5 text-lg border border-slate-200 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-primary-500 transition-all shadow-sm hover:border-primary-300 bg-white"
                                        />
                                    </div>

                                    {!showResults && (
                                        <Button
                                            onClick={handleCalculate}
                                            disabled={!reprintCost || !updatesPerYear}
                                            variant="primary"
                                            size="lg"
                                            className="w-full text-lg py-4 shadow-lg shadow-primary-500/20 hover:shadow-primary-500/40 transition-all transform hover:-translate-y-0.5"
                                        >
                                            Calculate Savings <ArrowRight className="ml-2 w-5 h-5" />
                                        </Button>
                                    )}

                                    {showResults && (
                                        <button
                                            onClick={handleCalculate} // Recalculate if changed
                                            className="text-sm text-primary-600 font-medium hover:text-primary-700 underline decoration-2 decoration-transparent hover:decoration-primary-200 transition-all"
                                        >
                                            Update Calculation
                                        </button>
                                    )}
                                </div>
                            </div>

                            {/* Right Side: Results */}
                            <div className={`bg-white p-8 md:p-10 flex flex-col justify-center transition-all duration-500 ${showResults ? 'md:col-span-3 opacity-100 translate-x-0' : 'hidden md:flex md:col-span-0 opacity-0 translate-x-10 w-0 p-0 overflow-hidden'}`}>
                                {results && showResults && (
                                    <motion.div
                                        initial={{ opacity: 0, scale: 0.95 }}
                                        animate={{ opacity: 1, scale: 1 }}
                                        transition={{ duration: 0.4, delay: 0.1 }}
                                        className="h-full flex flex-col"
                                    >
                                        <div className="flex-1">
                                            {isPositiveSavings ? (
                                                <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-green-50 text-green-700 text-sm font-medium mb-6">
                                                    <TrendingDown className="w-4 h-4" />
                                                    Potential Savings Found
                                                </div>
                                            ) : (
                                                <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-blue-50 text-blue-700 text-sm font-medium mb-6">
                                                    <TrendingDown className="w-4 h-4" />
                                                    Cost Analysis
                                                </div>
                                            )}

                                            <div className="mb-8">
                                                {isPositiveSavings ? (
                                                    <>
                                                        <p className="text-slate-500 text-sm font-medium uppercase tracking-wide mb-1">Annual Waste Identified</p>
                                                        <div className="flex items-baseline gap-2">
                                                            <span className="text-5xl lg:text-6xl font-black text-slate-900 tracking-tight">
                                                                {formatCurrency(results.annualWaste)}
                                                            </span>
                                                        </div>
                                                        <p className="text-red-500 text-sm mt-2 font-medium flex items-center gap-1">
                                                            <AlertTriangle className="w-3 h-3" /> Money currently lost to static reprints
                                                        </p>
                                                    </>
                                                ) : (
                                                    <>
                                                        <p className="text-slate-500 text-sm font-medium uppercase tracking-wide mb-1">Estimated Annual Investment</p>
                                                        <div className="flex items-baseline gap-2">
                                                            <span className="text-5xl lg:text-6xl font-black text-slate-900 tracking-tight">
                                                                {formatCurrency(Math.abs(results.savings))}
                                                            </span>
                                                        </div>
                                                        <p className="text-slate-500 text-sm mt-2 font-medium">
                                                            Difference for upgrading to Dynamic QR features
                                                        </p>
                                                    </>
                                                )}
                                            </div>

                                            {/* Comparison Bars */}
                                            <div className="space-y-6 mb-10">
                                                <div className="relative">
                                                    <div className="flex justify-between text-sm mb-2">
                                                        <span className="font-semibold text-slate-700">Static QR Code Cost</span>
                                                        <span className="font-bold text-red-600">{formatCurrency(results.annualWaste)}</span>
                                                    </div>
                                                    <div className="h-3 bg-slate-100 rounded-full w-full overflow-hidden">
                                                        <motion.div
                                                            initial={{ width: 0 }}
                                                            animate={{ width: `${(results.annualWaste / Math.max(results.annualWaste, results.withQRMaster)) * 100}%` }}
                                                            transition={{ duration: 1, ease: "easeOut" }}
                                                            className="h-full bg-red-500 rounded-full"
                                                        />
                                                    </div>
                                                </div>

                                                <div className="relative">
                                                    <div className="flex justify-between text-sm mb-2">
                                                        <span className="font-semibold text-slate-700">QR Master Cost</span>
                                                        <span className={isPositiveSavings ? "font-bold text-emerald-600" : "font-bold text-blue-600"}>{formatCurrency(results.withQRMaster)}</span>
                                                    </div>
                                                    <div className="h-3 bg-slate-100 rounded-full w-full overflow-hidden">
                                                        <motion.div
                                                            initial={{ width: 0 }}
                                                            animate={{ width: `${(results.withQRMaster / Math.max(results.annualWaste, results.withQRMaster)) * 100}%` }}
                                                            transition={{ duration: 1, ease: "easeOut", delay: 0.5 }}
                                                            className={isPositiveSavings ? "h-full bg-emerald-500 rounded-full" : "h-full bg-blue-500 rounded-full"}
                                                        />
                                                    </div>
                                                </div>
                                            </div>

                                            {isPositiveSavings ? (
                                                <div className="bg-emerald-50/50 border border-emerald-100 rounded-2xl p-6 mb-8">
                                                    <div className="flex items-start gap-4">
                                                        <div className="p-3 bg-emerald-100 rounded-xl text-emerald-600 shrink-0">
                                                            <CheckCircle className="w-6 h-6" />
                                                        </div>
                                                        <div>
                                                            <h4 className="text-lg font-bold text-emerald-900 mb-1">
                                                                You save {results.savingsPercent}% instantly
                                                            </h4>
                                                            <p className="text-emerald-800/80 leading-relaxed">
                                                                That's <strong className="text-emerald-900">{formatCurrency(results.savings)}</strong> extra budget per year.
                                                                Effectively getting <strong className="text-emerald-900">{results.monthsPaidFor} months</strong> of service for free compared to just one single reprint.
                                                            </p>
                                                        </div>
                                                    </div>
                                                </div>
                                            ) : (
                                                <div className="bg-blue-50/50 border border-blue-100 rounded-2xl p-6 mb-8">
                                                    <div className="flex items-start gap-4">
                                                        <div className="p-3 bg-blue-100 rounded-xl text-blue-600 shrink-0">
                                                            <CheckCircle className="w-6 h-6" />
                                                        </div>
                                                        <div>
                                                            <h4 className="text-lg font-bold text-blue-900 mb-1">
                                                                Premium features for just {formatCurrency(Math.abs(results.savings))}/year
                                                            </h4>
                                                            <p className="text-blue-800/80 leading-relaxed">
                                                                For a small investment, you gain full control, analytics, and the ability to update destinations anytime.
                                                            </p>
                                                        </div>
                                                    </div>
                                                </div>
                                            )}
                                        </div>

                                        <div className="mt-auto space-y-3">
                                            <Link href="/signup" className="block">
                                                <Button variant="primary" size="lg" className="w-full text-lg py-4 shadow-xl shadow-primary-500/20 hover:shadow-primary-500/30">
                                                    Start Saving Now
                                                </Button>
                                            </Link>
                                            <button
                                                onClick={handleDownloadReport}
                                                className="w-full flex items-center justify-center gap-2 py-4 px-6 text-base font-bold text-white bg-gradient-to-r from-slate-800 to-slate-900 hover:from-slate-700 hover:to-slate-800 rounded-xl shadow-lg shadow-slate-900/10 hover:shadow-slate-900/20 transform hover:-translate-y-0.5 transition-all duration-200"
                                            >
                                                <FileDown className="w-5 h-5" />
                                                Get Official Savings Report PDF
                                            </button>
                                            <p className="text-center text-xs text-slate-400">
                                                Based on QR Master Pro annual plan. No credit card required to start.
                                            </p>
                                        </div>
                                    </motion.div>
                                )}
                            </div>
                        </div>
                    </motion.div>
                </div>
            </section>

            {/* Email Capture Modal */}
            <AnimatePresence>
                {showEmailModal && (
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
                        onClick={() => setShowEmailModal(false)}
                    >
                        <motion.div
                            initial={{ opacity: 0, scale: 0.95, y: 20 }}
                            animate={{ opacity: 1, scale: 1, y: 0 }}
                            exit={{ opacity: 0, scale: 0.95, y: 20 }}
                            className="bg-white rounded-2xl shadow-2xl max-w-md w-full p-8 relative"
                            onClick={(e) => e.stopPropagation()}
                        >
                            <button
                                onClick={() => setShowEmailModal(false)}
                                className="absolute top-4 right-4 p-2 text-slate-400 hover:text-slate-600 rounded-lg hover:bg-slate-100 transition-colors"
                            >
                                <X className="w-5 h-5" />
                            </button>

                            <div className="text-center mb-6">
                                <div className="w-16 h-16 bg-gradient-to-br from-primary-100 to-indigo-100 rounded-2xl flex items-center justify-center mx-auto mb-4">
                                    <FileDown className="w-8 h-8 text-primary-600" />
                                </div>
                                <h3 className="text-2xl font-bold text-slate-900 mb-2">
                                    Get Your Savings Report
                                </h3>
                                <p className="text-slate-600">
                                    Enter your email to receive your personalized PDF report with detailed cost analysis.
                                </p>
                            </div>

                            <form onSubmit={handleEmailSubmit} className="space-y-4">
                                <div>
                                    <label htmlFor="emailInput" className="block text-sm font-medium text-slate-700 mb-2">
                                        Business Email
                                    </label>
                                    <div className="relative">
                                        <Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
                                        <input
                                            type="email"
                                            id="emailInput"
                                            value={email}
                                            onChange={(e) => setEmail(e.target.value)}
                                            placeholder="you@company.com"
                                            required
                                            className="w-full pl-12 pr-4 py-3.5 text-lg border border-slate-200 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-primary-500 transition-all"
                                        />
                                    </div>
                                </div>

                                {submitError && (
                                    <p className="text-sm text-red-600">{submitError}</p>
                                )}

                                <Button
                                    type="submit"
                                    disabled={isSubmitting || !email}
                                    variant="primary"
                                    size="lg"
                                    className="w-full text-lg py-4"
                                >
                                    {isSubmitting ? (
                                        <>
                                            <Loader2 className="w-5 h-5 mr-2 animate-spin" />
                                            Generating...
                                        </>
                                    ) : (
                                        <>
                                            <FileDown className="w-5 h-5 mr-2" />
                                            Download Report
                                        </>
                                    )}
                                </Button>

                                <p className="text-xs text-slate-400 text-center">
                                    We respect your privacy. Your email will only be used for QR Master updates.
                                </p>
                            </form>
                        </motion.div>
                    </motion.div>
                )}
            </AnimatePresence>
        </>
    );
};

export default ReprintSavingsCalculator;
