import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Check, 
  X, 
  Zap, 
  Crown, 
  Rocket, 
  ShieldCheck, 
  ArrowLeft, 
  Sparkles, 
  Loader2,
  Star
} from 'lucide-react';
import { useAuth } from 'react-oidc-context';

interface UpgradePageProps {
  onBack?: () => void;
}

type BillingCycle = 'monthly' | 'yearly';

export const UpgradePage: React.FC<UpgradePageProps> = ({ onBack }) => {
  const auth = useAuth();
  const [billingCycle, setBillingCycle] = useState<BillingCycle>('yearly');
  const [isLoading, setIsLoading] = useState(false);
  const [statusLoading, setStatusLoading] = useState(true);
  const [hasAccess, setHasAccess] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    checkStatus();
  }, []);

  const checkStatus = async () => {
    try {
      const token = auth.user?.access_token;
      if (!token) return;

      const backendUrl = import.meta.env.VITE_BACKEND_URL || 'http://localhost:3001';
      const response = await fetch(`${backendUrl}/api/payments/status`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (response.ok) {
        const data = await response.json();
        setHasAccess(data.hasAccess);
      }
    } catch (err) {
      console.error('Failed to check status:', err);
    } finally {
      setStatusLoading(false);
    }
  };

  const handleCheckout = async () => {
    try {
      setIsLoading(true);
      setError(null);

      const token = auth.user?.access_token;
      if (!token) {
        auth.signinRedirect();
        return;
      }

      const backendUrl = import.meta.env.VITE_BACKEND_URL || 'http://localhost:3001';
      const response = await fetch(`${backendUrl}/api/payments/checkout`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          planType: billingCycle,
          successUrl: `${window.location.origin}/payment/success`,
          cancelUrl: `${window.location.origin}/payment/cancel`
        })
      });

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

      const { url } = await response.json();
      window.location.href = url;
    } catch (err) {
      setError('Something went wrong. Please try again.');
      setIsLoading(false);
    }
  };

  const containerVariants = {
    hidden: { opacity: 0 },
    visible: { 
      opacity: 1,
      transition: { 
        staggerChildren: 0.1 
      }
    }
  };

  const itemVariants = {
    hidden: { y: 20, opacity: 0 },
    visible: { 
      y: 0, 
      opacity: 1,
      transition: { type: 'spring', bounce: 0.4 }
    }
  };

  if (statusLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-50">
        <Loader2 className="w-8 h-8 animate-spin text-theme-primary" />
      </div>
    );
  }

  if (hasAccess) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
        <motion.div 
          initial={{ scale: 0.9, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          className="max-w-md w-full bg-white rounded-[2.5rem] p-8 shadow-[0_20px_50px_rgba(0,0,0,0.1)] border-4 border-white text-center relative overflow-hidden"
        >
          <div className="absolute inset-0 bg-gradient-to-br from-yellow-100/50 to-orange-100/50 pointer-events-none" />
          
          <div className="relative z-10">
            <div className="w-24 h-24 bg-gradient-to-br from-yellow-400 to-orange-500 rounded-3xl mx-auto mb-6 shadow-xl rotate-3 flex items-center justify-center">
              <Crown className="w-12 h-12 text-white" />
            </div>
            
            <h2 className="text-3xl font-black text-gray-900 mb-2">You're a Pro!</h2>
            <p className="text-gray-500 font-bold mb-8">
              You have unlocked unlimited power. Enjoy your premium features!
            </p>

            <button
              onClick={onBack}
              className="w-full bg-gray-900 text-white py-4 rounded-2xl font-black text-lg shadow-[0_6px_0_rgba(0,0,0,1)] active:shadow-none active:translate-y-[6px] transition-all hover:bg-black"
            >
              Back to Game
            </button>
          </div>

          <Sparkles className="absolute top-10 left-10 text-yellow-400 w-6 h-6 animate-pulse" />
          <Star className="absolute bottom-10 right-10 text-orange-400 w-8 h-8 animate-bounce" />
        </motion.div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 overflow-y-auto overflow-x-hidden">
      <div className="max-w-6xl mx-auto px-4 py-8 md:py-12">
        <motion.header 
          initial={{ y: -20, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          className="mb-12 relative text-center"
        >
          {onBack && (
            <button 
              onClick={onBack}
              className="absolute left-0 top-1/2 -translate-y-1/2 p-3 bg-white rounded-2xl shadow-[0_4px_0_rgba(0,0,0,0.1)] hover:shadow-[0_6px_0_rgba(0,0,0,0.1)] active:shadow-none active:translate-y-[2px] transition-all text-gray-500 hover:text-gray-900"
            >
              <ArrowLeft size={24} />
            </button>
          )}
          
          <h1 className="text-4xl md:text-6xl font-black text-gray-900 mb-4 tracking-tight">
            Unlock <span className="text-transparent bg-clip-text bg-gradient-to-r from-violet-600 to-indigo-600">Unlimited</span> Power
          </h1>
          <p className="text-gray-500 font-bold text-lg md:text-xl max-w-2xl mx-auto">
            Supercharge your quizzes with AI magic. Create more, play more, win more.
          </p>
        </motion.header>

        <div className="flex justify-center mb-12">
          <div className="bg-white p-1.5 rounded-full shadow-[0_8px_30px_rgba(0,0,0,0.05)] border border-gray-100 flex relative">
            <motion.div 
              className="absolute top-1.5 bottom-1.5 bg-gray-900 rounded-full shadow-lg"
              layoutId="toggle"
              initial={false}
              animate={{
                left: billingCycle === 'monthly' ? '6px' : '50%',
                width: 'calc(50% - 9px)',
                x: billingCycle === 'monthly' ? 0 : 3
              }}
              transition={{ type: "spring", bounce: 0.2, duration: 0.6 }}
            />
            
            <button
              onClick={() => setBillingCycle('monthly')}
              className={`relative z-10 px-8 py-3 rounded-full font-black text-sm transition-colors duration-200 ${
                billingCycle === 'monthly' ? 'text-white' : 'text-gray-500 hover:text-gray-900'
              }`}
            >
              Monthly
            </button>
            <button
              onClick={() => setBillingCycle('yearly')}
              className={`relative z-10 px-8 py-3 rounded-full font-black text-sm transition-colors duration-200 flex items-center gap-2 ${
                billingCycle === 'yearly' ? 'text-white' : 'text-gray-500 hover:text-gray-900'
              }`}
            >
              Yearly
              <span className={`text-[10px] px-2 py-0.5 rounded-full font-bold uppercase tracking-wide ${
                billingCycle === 'yearly' ? 'bg-white/20 text-white' : 'bg-green-100 text-green-700'
              }`}>
                -17%
              </span>
            </button>
          </div>
        </div>

        <motion.div 
          variants={containerVariants}
          initial="hidden"
          animate="visible"
          className="grid md:grid-cols-2 gap-8 max-w-4xl mx-auto items-start"
        >
          <motion.div 
            variants={itemVariants}
            className="bg-white p-8 rounded-[2.5rem] shadow-xl border-4 border-transparent relative group"
          >
            <div className="mb-6">
              <div className="w-16 h-16 bg-gray-100 rounded-2xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300">
                <Zap className="w-8 h-8 text-gray-400" />
              </div>
              <h3 className="text-2xl font-black text-gray-900">Starter</h3>
              <p className="text-gray-400 font-bold mt-1">For casual players</p>
            </div>

            <div className="mb-8">
              <span className="text-5xl font-black text-gray-900">$0</span>
              <span className="text-gray-400 font-bold">/forever</span>
            </div>

            <ul className="space-y-4 mb-8">
              <FeatureItem text="5 AI generations per month" included />
              <FeatureItem text="Basic quiz topics" included />
              <FeatureItem text="Host up to 10 players" included />
              <FeatureItem text="Advanced document analysis" included={false} />
              <FeatureItem text="Priority support" included={false} />
            </ul>

            <button 
              disabled
              className="w-full bg-gray-100 text-gray-400 py-4 rounded-2xl font-black text-lg cursor-not-allowed"
            >
              Current Plan
            </button>
          </motion.div>

          <motion.div 
            variants={itemVariants}
            className="bg-gray-900 p-8 rounded-[2.5rem] shadow-[0_20px_60px_rgba(79,70,229,0.3)] border-4 border-transparent relative overflow-hidden group transform md:-translate-y-4"
          >
            <div className="absolute top-0 right-0 w-64 h-64 bg-violet-600/20 blur-[80px] rounded-full pointer-events-none" />
            <div className="absolute bottom-0 left-0 w-64 h-64 bg-indigo-600/20 blur-[80px] rounded-full pointer-events-none" />
            
            <div className="relative z-10">
              <div className="flex justify-between items-start mb-6">
                <div className="w-16 h-16 bg-gradient-to-br from-violet-500 to-indigo-600 rounded-2xl flex items-center justify-center mb-4 shadow-lg group-hover:scale-110 transition-transform duration-300 group-hover:rotate-3">
                  <Rocket className="w-8 h-8 text-white" />
                </div>
                <span className="bg-white/10 backdrop-blur-md text-white px-4 py-1.5 rounded-full text-xs font-black uppercase tracking-wider border border-white/20">
                  Most Popular
                </span>
              </div>

              <h3 className="text-2xl font-black text-white">Pro Gamer</h3>
              <p className="text-gray-400 font-bold mt-1">For serious hosts</p>

              <div className="my-8">
                <div className="flex items-baseline gap-1">
                  <span className="text-6xl font-black text-white">
                    ${billingCycle === 'monthly' ? '5' : '4.17'}
                  </span>
                  <span className="text-gray-400 font-bold">/mo</span>
                </div>
                {billingCycle === 'yearly' && (
                  <p className="text-sm font-bold text-green-400 mt-2">
                    Billed $50 yearly (save $10)
                  </p>
                )}
              </div>

              <ul className="space-y-4 mb-8">
                <FeatureItem text="250 AI generations per month" included dark />
                <FeatureItem text="Unlimited document uploads" included dark />
                <FeatureItem text="Host up to 100 players" included dark />
                <FeatureItem text="Priority AI processing" included dark />
                <FeatureItem text="Early access to new features" included dark />
              </ul>

              <button
                onClick={handleCheckout}
                disabled={isLoading}
                className="w-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white py-4 rounded-2xl font-black text-lg shadow-[0_6px_0_rgba(67,56,202,1)] active:shadow-none active:translate-y-[6px] transition-all hover:brightness-110 flex items-center justify-center gap-2 disabled:opacity-70 disabled:cursor-not-allowed"
              >
                {isLoading ? (
                  <Loader2 className="animate-spin" />
                ) : (
                  <>
                    Upgrade Now <Sparkles size={20} className="text-yellow-300" />
                  </>
                )}
              </button>
              
              {error && (
                <p className="mt-3 text-red-400 text-sm font-bold text-center animate-pulse">
                  {error}
                </p>
              )}
            </div>
          </motion.div>
        </motion.div>

        <motion.div 
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.5 }}
          className="mt-16 text-center space-y-4"
        >
          <div className="flex flex-wrap justify-center gap-6 text-gray-400 font-bold text-sm">
            <span className="flex items-center gap-2">
              <ShieldCheck size={18} /> Secure payment via Stripe
            </span>
            <span className="flex items-center gap-2">
              <Check size={18} /> Cancel anytime
            </span>
            <span className="flex items-center gap-2">
              <Check size={18} /> 7-day money-back guarantee
            </span>
          </div>
        </motion.div>

      </div>
    </div>
  );
};

const FeatureItem: React.FC<{ text: string; included: boolean; dark?: boolean }> = ({ text, included, dark }) => (
  <li className="flex items-center gap-3">
    <div className={`
      flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center
      ${included 
        ? (dark ? 'bg-violet-500/20 text-violet-400' : 'bg-theme-primary/10 text-theme-primary') 
        : 'bg-gray-100 text-gray-400'}
    `}>
      {included ? <Check size={14} strokeWidth={3} /> : <X size={14} strokeWidth={3} />}
    </div>
    <span className={`font-bold ${dark ? 'text-gray-300' : (included ? 'text-gray-700' : 'text-gray-400')}`}>
      {text}
    </span>
  </li>
);
