/**
 * SubscriptionUpgradeFlow Component
 * Modal for upgrading/downgrading subscription plans with preview
 */

import React, { useState, useEffect } from 'react';
import {
  X,
  ArrowRight,
  ArrowUp,
  ArrowDown,
  Check,
  AlertCircle,
  Loader2,
  Sparkles,
  Zap,
  Crown,
  CreditCard,
  Calendar,
  DollarSign,
} from 'lucide-react';
import {
  previewSubscriptionChange,
  changeSubscriptionPlan,
} from '../../services/payment.service';

interface Plan {
  id: string;
  name: string;
  price: number;
  interval: 'month' | 'year';
  features: string[];
  highlighted?: boolean;
}

interface ChangePreview {
  currentPlan: {
    name: string;
    price: number;
  };
  newPlan: {
    name: string;
    price: number;
  };
  proratedCredit: number;
  amountDue: number;
  effectiveDate: string;
  billingCycleEnd: string;
}

interface SubscriptionUpgradeFlowProps {
  currentPlanId: string;
  plans: Plan[];
  onClose: () => void;
  onSuccess?: (newPlanId: string) => void;
}

const SubscriptionUpgradeFlow: React.FC<SubscriptionUpgradeFlowProps> = ({
  currentPlanId,
  plans,
  onClose,
  onSuccess,
}) => {
  const [selectedPlanId, setSelectedPlanId] = useState<string | null>(null);
  const [preview, setPreview] = useState<ChangePreview | null>(null);
  const [loadingPreview, setLoadingPreview] = useState(false);
  const [processing, setProcessing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [step, setStep] = useState<'select' | 'preview' | 'success'>('select');

  const currentPlan = plans.find((p) => p.id === currentPlanId);
  const selectedPlan = plans.find((p) => p.id === selectedPlanId);

  const isUpgrade = selectedPlan && currentPlan && selectedPlan.price > currentPlan.price;
  const isDowngrade = selectedPlan && currentPlan && selectedPlan.price < currentPlan.price;

  const fetchPreview = async (planId: string) => {
    setLoadingPreview(true);
    setError(null);

    try {
      const plan = plans.find((p) => p.id === planId);
      const interval = plan?.interval || 'month';
      const data = await previewSubscriptionChange(planId, interval);
      // Map the API response to our local ChangePreview type
      setPreview({
        currentPlan: {
          name: currentPlan?.name || 'Current Plan',
          price: currentPlan?.price || 0,
        },
        newPlan: {
          name: plan?.name || 'New Plan',
          price: plan?.price || data.total,
        },
        proratedCredit: data.discount,
        amountDue: data.total,
        effectiveDate: new Date().toISOString(),
        billingCycleEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
      });
      setStep('preview');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to preview changes');
    } finally {
      setLoadingPreview(false);
    }
  };

  const handleSelectPlan = (planId: string) => {
    if (planId === currentPlanId) return;
    setSelectedPlanId(planId);
    fetchPreview(planId);
  };

  const handleConfirmChange = async () => {
    if (!selectedPlanId) return;

    setProcessing(true);
    setError(null);

    try {
      const interval = selectedPlan?.interval || 'month';
      await changeSubscriptionPlan(currentPlanId, selectedPlanId, interval);
      setStep('success');
      onSuccess?.(selectedPlanId);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to change plan');
    } finally {
      setProcessing(false);
    }
  };

  const getPlanIcon = (planName: string) => {
    const name = planName.toLowerCase();
    if (name.includes('pro') || name.includes('premium')) {
      return <Crown className="w-5 h-5 text-yellow-400" />;
    }
    if (name.includes('business') || name.includes('enterprise')) {
      return <Zap className="w-5 h-5 text-purple-400" />;
    }
    return <Sparkles className="w-5 h-5 text-blue-400" />;
  };

  const formatPrice = (price: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
    }).format(price);
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70">
      <div className="w-full max-w-2xl max-h-[90vh] overflow-hidden bg-gray-800 rounded-xl shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-700">
          <div>
            <h2 className="text-lg font-semibold text-white">
              {step === 'select' && 'Change Your Plan'}
              {step === 'preview' && 'Confirm Changes'}
              {step === 'success' && 'Plan Updated'}
            </h2>
            {step === 'select' && (
              <p className="text-sm text-gray-400">Select a new plan to continue</p>
            )}
          </div>
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="overflow-y-auto max-h-[calc(90vh-140px)] p-4">
          {/* Step 1: Select Plan */}
          {step === 'select' && (
            <div className="space-y-3">
              {plans.map((plan) => {
                const isCurrent = plan.id === currentPlanId;
                const isSelected = plan.id === selectedPlanId;

                return (
                  <button
                    key={plan.id}
                    onClick={() => handleSelectPlan(plan.id)}
                    disabled={isCurrent || loadingPreview}
                    className={`w-full p-4 rounded-xl border text-left transition-all ${
                      isCurrent
                        ? 'bg-blue-600/10 border-blue-500/50 cursor-default'
                        : isSelected
                        ? 'bg-gray-700 border-blue-500 ring-2 ring-blue-500/20'
                        : 'bg-gray-800/50 border-gray-700 hover:border-gray-600'
                    } ${loadingPreview ? 'opacity-50' : ''}`}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex items-center gap-3">
                        <div className="p-2 bg-gray-900 rounded-lg">
                          {getPlanIcon(plan.name)}
                        </div>
                        <div>
                          <div className="flex items-center gap-2">
                            <span className="text-white font-semibold">{plan.name}</span>
                            {isCurrent && (
                              <span className="px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded">
                                Current Plan
                              </span>
                            )}
                            {plan.highlighted && !isCurrent && (
                              <span className="px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded">
                                Popular
                              </span>
                            )}
                          </div>
                          <div className="text-gray-400 mt-1">
                            <span className="text-xl font-bold text-white">
                              {formatPrice(plan.price)}
                            </span>
                            <span className="text-sm">/{plan.interval}</span>
                          </div>
                        </div>
                      </div>

                      {!isCurrent && (
                        <div className="flex items-center gap-2">
                          {plan.price > (currentPlan?.price || 0) ? (
                            <span className="flex items-center gap-1 text-green-400 text-sm">
                              <ArrowUp className="w-4 h-4" />
                              Upgrade
                            </span>
                          ) : (
                            <span className="flex items-center gap-1 text-yellow-400 text-sm">
                              <ArrowDown className="w-4 h-4" />
                              Downgrade
                            </span>
                          )}
                        </div>
                      )}
                    </div>

                    {/* Features Preview */}
                    <div className="mt-3 pt-3 border-t border-gray-700/50">
                      <div className="grid grid-cols-2 gap-2">
                        {plan.features.slice(0, 4).map((feature, i) => (
                          <div key={i} className="flex items-center gap-2 text-sm text-gray-400">
                            <Check className="w-3 h-3 text-green-400" />
                            <span>{feature}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  </button>
                );
              })}

              {loadingPreview && (
                <div className="flex items-center justify-center py-4">
                  <Loader2 className="w-6 h-6 text-blue-400 animate-spin" />
                  <span className="ml-2 text-gray-400">Loading preview...</span>
                </div>
              )}
            </div>
          )}

          {/* Step 2: Preview Changes */}
          {step === 'preview' && preview && (
            <div className="space-y-6">
              {/* Plan Comparison */}
              <div className="flex items-center justify-center gap-4">
                <div className="text-center">
                  <p className="text-sm text-gray-500 mb-1">Current Plan</p>
                  <p className="text-white font-semibold">{preview.currentPlan.name}</p>
                  <p className="text-gray-400">{formatPrice(preview.currentPlan.price)}/mo</p>
                </div>
                <div className={`p-2 rounded-full ${isUpgrade ? 'bg-green-500/20' : 'bg-yellow-500/20'}`}>
                  <ArrowRight className={`w-5 h-5 ${isUpgrade ? 'text-green-400' : 'text-yellow-400'}`} />
                </div>
                <div className="text-center">
                  <p className="text-sm text-gray-500 mb-1">New Plan</p>
                  <p className="text-white font-semibold">{preview.newPlan.name}</p>
                  <p className="text-gray-400">{formatPrice(preview.newPlan.price)}/mo</p>
                </div>
              </div>

              {/* Billing Details */}
              <div className="bg-gray-900/50 rounded-xl p-4 space-y-4">
                <h3 className="text-sm font-medium text-gray-400 flex items-center gap-2">
                  <DollarSign className="w-4 h-4" />
                  Billing Summary
                </h3>

                <div className="space-y-3">
                  {preview.proratedCredit > 0 && (
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-400">Prorated credit for unused time</span>
                      <span className="text-green-400">-{formatPrice(preview.proratedCredit)}</span>
                    </div>
                  )}

                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">New plan price</span>
                    <span className="text-white">{formatPrice(preview.newPlan.price)}</span>
                  </div>

                  <div className="flex justify-between pt-3 border-t border-gray-700">
                    <span className="text-white font-medium">Amount due today</span>
                    <span className="text-white font-bold text-lg">
                      {formatPrice(preview.amountDue)}
                    </span>
                  </div>
                </div>
              </div>

              {/* Effective Date */}
              <div className="flex items-center gap-3 p-4 bg-blue-500/10 border border-blue-500/30 rounded-xl">
                <Calendar className="w-5 h-5 text-blue-400" />
                <div>
                  <p className="text-white text-sm">
                    {isUpgrade ? (
                      <>Your new plan takes effect <strong>immediately</strong></>
                    ) : (
                      <>Your new plan takes effect on <strong>{formatDate(preview.billingCycleEnd)}</strong></>
                    )}
                  </p>
                  <p className="text-gray-400 text-xs mt-0.5">
                    {isUpgrade
                      ? 'You\'ll have instant access to all new features'
                      : 'You\'ll keep current features until your billing cycle ends'}
                  </p>
                </div>
              </div>

              {error && (
                <div className="flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg">
                  <AlertCircle className="w-5 h-5 text-red-400" />
                  <span className="text-sm text-red-400">{error}</span>
                </div>
              )}
            </div>
          )}

          {/* Step 3: Success */}
          {step === 'success' && (
            <div className="text-center py-8">
              <div className="w-16 h-16 mx-auto mb-4 bg-green-500/20 rounded-full flex items-center justify-center">
                <Check className="w-8 h-8 text-green-400" />
              </div>
              <h3 className="text-xl font-semibold text-white mb-2">Plan Updated Successfully!</h3>
              <p className="text-gray-400 mb-6">
                You're now on the <strong className="text-white">{selectedPlan?.name}</strong> plan.
                {isUpgrade && ' Your new features are ready to use.'}
              </p>
              <button
                onClick={onClose}
                className="px-6 py-3 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium transition-colors"
              >
                Got it
              </button>
            </div>
          )}
        </div>

        {/* Footer */}
        {step === 'preview' && (
          <div className="flex items-center justify-between p-4 border-t border-gray-700 bg-gray-800/50">
            <button
              onClick={() => {
                setStep('select');
                setSelectedPlanId(null);
                setPreview(null);
                setError(null);
              }}
              disabled={processing}
              className="px-4 py-2 text-gray-400 hover:text-white transition-colors disabled:opacity-50"
            >
              Back
            </button>
            <button
              onClick={handleConfirmChange}
              disabled={processing}
              className="flex items-center gap-2 px-6 py-2.5 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium transition-colors disabled:opacity-50"
            >
              {processing ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  Processing...
                </>
              ) : (
                <>
                  <CreditCard className="w-4 h-4" />
                  Confirm {isUpgrade ? 'Upgrade' : 'Downgrade'}
                </>
              )}
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default SubscriptionUpgradeFlow;
