import React, { useState } from 'react';
import { useNavigate, useOutletContext } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Check, Loader2, CreditCard, Shield, Zap, Users, ArrowLeft } from 'lucide-react';
import { User, Business } from '../types';

type BillingPeriod = 'monthly' | 'annual';
type PlanTier = 'Professional' | 'Business' | 'Enterprise';

interface PlanFeature {
  text: string;
  included: boolean;
}

interface PlanDetails {
  name: string;
  description: string;
  monthlyPrice: number;
  annualPrice: number;
  features: PlanFeature[];
  popular?: boolean;
}

/**
 * Upgrade Page
 * Allows businesses to upgrade from trial/free to a paid plan
 */
const Upgrade: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { user, business } = useOutletContext<{ user: User; business: Business }>();

  const [billingPeriod, setBillingPeriod] = useState<BillingPeriod>('monthly');
  const [selectedPlan, setSelectedPlan] = useState<PlanTier>('Professional');
  const [isProcessing, setIsProcessing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Plan configurations
  const plans: Record<PlanTier, PlanDetails> = {
    Professional: {
      name: t('marketing.pricing.tiers.professional.name'),
      description: t('marketing.pricing.tiers.professional.description'),
      monthlyPrice: 29,
      annualPrice: 290,
      features: [
        { text: t('upgrade.features.resources', { count: 10 }), included: true },
        { text: t('upgrade.features.customDomain'), included: true },
        { text: t('upgrade.features.stripeConnect'), included: true },
        { text: t('upgrade.features.whitelabel'), included: true },
        { text: t('upgrade.features.emailReminders'), included: true },
        { text: t('upgrade.features.prioritySupport'), included: true },
        { text: t('upgrade.features.apiAccess'), included: false },
      ],
    },
    Business: {
      name: t('marketing.pricing.tiers.business.name'),
      description: t('marketing.pricing.tiers.business.description'),
      monthlyPrice: 79,
      annualPrice: 790,
      popular: true,
      features: [
        { text: t('upgrade.features.unlimitedResources'), included: true },
        { text: t('upgrade.features.customDomain'), included: true },
        { text: t('upgrade.features.stripeConnect'), included: true },
        { text: t('upgrade.features.whitelabel'), included: true },
        { text: t('upgrade.features.teamManagement'), included: true },
        { text: t('upgrade.features.advancedAnalytics'), included: true },
        { text: t('upgrade.features.apiAccess'), included: true },
        { text: t('upgrade.features.phoneSupport'), included: true },
      ],
    },
    Enterprise: {
      name: t('marketing.pricing.tiers.enterprise.name'),
      description: t('marketing.pricing.tiers.enterprise.description'),
      monthlyPrice: 0,
      annualPrice: 0,
      features: [
        { text: t('upgrade.features.everything'), included: true },
        { text: t('upgrade.features.customIntegrations'), included: true },
        { text: t('upgrade.features.dedicatedManager'), included: true },
        { text: t('upgrade.features.sla'), included: true },
        { text: t('upgrade.features.customContracts'), included: true },
        { text: t('upgrade.features.onPremise'), included: true },
      ],
    },
  };

  const currentPlan = plans[selectedPlan];
  const price = billingPeriod === 'monthly' ? currentPlan.monthlyPrice : currentPlan.annualPrice;
  const isEnterprise = selectedPlan === 'Enterprise';

  const handleUpgrade = async () => {
    if (isEnterprise) {
      // For Enterprise, redirect to contact page
      window.location.href = 'mailto:sales@smoothschedule.com?subject=Enterprise Plan Inquiry';
      return;
    }

    setIsProcessing(true);
    setError(null);

    try {
      // TODO: Integrate with Stripe Checkout or dj-stripe subscription creation
      // This is a placeholder for the actual Stripe integration

      // Example flow:
      // 1. Call backend API to create Stripe Checkout session
      // 2. Redirect to Stripe Checkout
      // 3. Handle success/cancel callbacks

      await new Promise(resolve => setTimeout(resolve, 2000)); // Simulate API call

      // For now, just show a message
      alert(`Upgrading to ${selectedPlan} (${billingPeriod})\nThis would redirect to Stripe Checkout.`);

      // After successful payment, redirect to dashboard
      navigate('/');
    } catch (err) {
      setError(t('upgrade.errors.processingFailed'));
      console.error('Upgrade error:', err);
    } finally {
      setIsProcessing(false);
    }
  };

  const calculateSavings = () => {
    if (billingPeriod === 'annual') {
      const monthlyCost = currentPlan.monthlyPrice * 12;
      const annualCost = currentPlan.annualPrice;
      return monthlyCost - annualCost;
    }
    return 0;
  };

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-12 px-4">
      <div className="max-w-6xl mx-auto">
        {/* Back Button */}
        <button
          onClick={() => navigate(-1)}
          className="flex items-center gap-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white mb-8"
        >
          <ArrowLeft size={20} />
          {t('common.back')}
        </button>

        {/* Header */}
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-4">
            {t('upgrade.title')}
          </h1>
          <p className="text-xl text-gray-600 dark:text-gray-400 max-w-2xl mx-auto">
            {t('upgrade.subtitle', { businessName: business.name })}
          </p>
        </div>

        {/* Billing Period Toggle */}
        <div className="flex justify-center mb-12">
          <div className="inline-flex items-center gap-4 bg-white dark:bg-gray-800 rounded-full p-1.5 shadow-sm border border-gray-200 dark:border-gray-700">
            <button
              onClick={() => setBillingPeriod('monthly')}
              className={`px-6 py-2.5 rounded-full font-medium transition-all ${
                billingPeriod === 'monthly'
                  ? 'bg-brand-600 text-white shadow-sm'
                  : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
              }`}
            >
              {t('upgrade.billing.monthly')}
            </button>
            <button
              onClick={() => setBillingPeriod('annual')}
              className={`px-6 py-2.5 rounded-full font-medium transition-all relative ${
                billingPeriod === 'annual'
                  ? 'bg-brand-600 text-white shadow-sm'
                  : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
              }`}
            >
              {t('upgrade.billing.annual')}
              <span className="absolute -top-2 -right-2 px-2 py-0.5 bg-green-500 text-white text-xs font-bold rounded-full">
                {t('upgrade.billing.save20')}
              </span>
            </button>
          </div>
        </div>

        {/* Plan Cards */}
        <div className="grid md:grid-cols-3 gap-8 mb-12">
          {(Object.entries(plans) as [PlanTier, PlanDetails][]).map(([tier, plan]) => {
            const isSelected = selectedPlan === tier;
            const tierPrice = billingPeriod === 'monthly' ? plan.monthlyPrice : plan.annualPrice;
            const isEnterprisePlan = tier === 'Enterprise';

            return (
              <div
                key={tier}
                onClick={() => setSelectedPlan(tier)}
                className={`relative bg-white dark:bg-gray-800 rounded-2xl shadow-lg border-2 transition-all cursor-pointer ${
                  isSelected
                    ? 'border-brand-600 shadow-brand-500/20 scale-105'
                    : 'border-gray-200 dark:border-gray-700 hover:border-brand-300'
                } ${plan.popular ? 'ring-2 ring-brand-500' : ''}`}
              >
                {plan.popular && (
                  <div className="absolute -top-4 left-1/2 -translate-x-1/2">
                    <span className="px-4 py-1.5 bg-brand-600 text-white text-sm font-bold rounded-full shadow-lg">
                      {t('upgrade.mostPopular')}
                    </span>
                  </div>
                )}

                <div className="p-8">
                  <h3 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
                    {plan.name}
                  </h3>
                  <p className="text-gray-600 dark:text-gray-400 mb-6">
                    {plan.description}
                  </p>

                  <div className="mb-6">
                    {isEnterprisePlan ? (
                      <div className="text-4xl font-bold text-gray-900 dark:text-white">
                        {t('upgrade.custom')}
                      </div>
                    ) : (
                      <>
                        <div className="text-4xl font-bold text-gray-900 dark:text-white">
                          ${tierPrice}
                          <span className="text-lg font-normal text-gray-500">
                            /{billingPeriod === 'monthly' ? t('upgrade.month') : t('upgrade.year')}
                          </span>
                        </div>
                        {billingPeriod === 'annual' && (
                          <div className="text-sm text-green-600 dark:text-green-400 mt-1">
                            {t('upgrade.billing.saveAmount', { amount: (plan.monthlyPrice * 12 - plan.annualPrice) })}
                          </div>
                        )}
                      </>
                    )}
                  </div>

                  <ul className="space-y-3 mb-8">
                    {plan.features.map((feature, idx) => (
                      <li key={idx} className="flex items-start gap-3">
                        <div
                          className={`p-1 rounded-full mt-0.5 ${
                            feature.included
                              ? 'bg-green-100 dark:bg-green-900/30'
                              : 'bg-gray-100 dark:bg-gray-700'
                          }`}
                        >
                          <Check
                            className={
                              feature.included
                                ? 'text-green-600 dark:text-green-400'
                                : 'text-gray-400'
                            }
                            size={16}
                          />
                        </div>
                        <span
                          className={`text-sm ${
                            feature.included
                              ? 'text-gray-700 dark:text-gray-300'
                              : 'text-gray-400 dark:text-gray-500'
                          }`}
                        >
                          {feature.text}
                        </span>
                      </li>
                    ))}
                  </ul>

                  <div
                    className={`w-full py-3 rounded-xl font-semibold text-center transition-all ${
                      isSelected
                        ? 'bg-brand-600 text-white shadow-lg'
                        : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
                    }`}
                  >
                    {isSelected ? t('upgrade.selected') : t('upgrade.selectPlan')}
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Summary & Checkout */}
        <div className="max-w-2xl mx-auto bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-8">
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-6">
            {t('upgrade.orderSummary')}
          </h2>

          <div className="space-y-4 mb-8">
            <div className="flex justify-between items-center pb-4 border-b border-gray-200 dark:border-gray-700">
              <div>
                <div className="font-semibold text-gray-900 dark:text-white">
                  {currentPlan.name} {t('upgrade.plan')}
                </div>
                <div className="text-sm text-gray-500">
                  {billingPeriod === 'monthly' ? t('upgrade.billedMonthly') : t('upgrade.billedAnnually')}
                </div>
              </div>
              {!isEnterprise && (
                <div className="text-xl font-bold text-gray-900 dark:text-white">
                  ${price}
                </div>
              )}
            </div>

            {billingPeriod === 'annual' && !isEnterprise && calculateSavings() > 0 && (
              <div className="flex justify-between items-center text-green-600 dark:text-green-400">
                <div className="font-medium">{t('upgrade.annualSavings')}</div>
                <div className="font-bold">-${calculateSavings()}</div>
              </div>
            )}
          </div>

          {/* Trust Indicators */}
          <div className="grid grid-cols-3 gap-4 mb-8 p-6 bg-gray-50 dark:bg-gray-900 rounded-xl">
            <div className="text-center">
              <Shield className="mx-auto mb-2 text-brand-600" size={24} />
              <div className="text-xs font-medium text-gray-700 dark:text-gray-300">
                {t('upgrade.trust.secure')}
              </div>
            </div>
            <div className="text-center">
              <Zap className="mx-auto mb-2 text-brand-600" size={24} />
              <div className="text-xs font-medium text-gray-700 dark:text-gray-300">
                {t('upgrade.trust.instant')}
              </div>
            </div>
            <div className="text-center">
              <Users className="mx-auto mb-2 text-brand-600" size={24} />
              <div className="text-xs font-medium text-gray-700 dark:text-gray-300">
                {t('upgrade.trust.support')}
              </div>
            </div>
          </div>

          {/* Error Message */}
          {error && (
            <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
              <p className="text-red-800 dark:text-red-200 text-sm">{error}</p>
            </div>
          )}

          {/* Upgrade Button */}
          <button
            onClick={handleUpgrade}
            disabled={isProcessing}
            className="w-full flex items-center justify-center gap-3 py-4 bg-gradient-to-r from-brand-600 to-brand-700 text-white font-bold rounded-xl hover:from-brand-700 hover:to-brand-800 transition-all shadow-lg shadow-brand-500/30 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isProcessing ? (
              <>
                <Loader2 className="animate-spin" size={20} />
                {t('upgrade.processing')}
              </>
            ) : (
              <>
                <CreditCard size={20} />
                {isEnterprise ? t('upgrade.contactSales') : t('upgrade.continueToPayment')}
              </>
            )}
          </button>

          <p className="text-center text-xs text-gray-500 dark:text-gray-400 mt-4">
            {t('upgrade.secureCheckout')}
          </p>
        </div>

        {/* FAQ or Additional Info */}
        <div className="max-w-2xl mx-auto mt-12 text-center">
          <p className="text-gray-600 dark:text-gray-400">
            {t('upgrade.questions')}{' '}
            <a
              href="mailto:support@smoothschedule.com"
              className="text-brand-600 hover:text-brand-700 font-medium"
            >
              {t('upgrade.contactUs')}
            </a>
          </p>
        </div>
      </div>
    </div>
  );
};

export default Upgrade;
