/**
 * Checkout Flow Page
 * Multi-step checkout for marketplace products with Stripe integration
 */

import React, { useState, useEffect, useMemo } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import {
  ArrowLeft,
  ArrowRight,
  CreditCard,
  Shield,
  Check,
  Loader2,
  Tag,
  AlertCircle,
  Lock,
  Percent,
} from 'lucide-react';
import { loadStripe } from '@stripe/stripe-js';
import {
  Elements,
  CardElement,
  useStripe,
  useElements,
} from '@stripe/react-stripe-js';
import { useMarketplaceStore } from '../../../stores/marketplaceStore';
import type { MarketplaceProductListItem, SignalPackPricing } from '../../../types/marketplace.types';

// Initialize Stripe
const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY || '');

// ============================================================================
// Types
// ============================================================================

interface CheckoutStep {
  id: number;
  title: string;
  description: string;
}

interface CouponData {
  code: string;
  discountPercent: number;
  discountAmount?: number;
  isValid: boolean;
}

// ============================================================================
// Constants
// ============================================================================

const CHECKOUT_STEPS: CheckoutStep[] = [
  { id: 1, title: 'Review', description: 'Confirm your selection' },
  { id: 2, title: 'Payment', description: 'Enter payment details' },
  { id: 3, title: 'Confirm', description: 'Complete purchase' },
];

// ============================================================================
// Payment Form Component (uses Stripe Elements)
// ============================================================================

interface PaymentFormProps {
  onSubmit: (paymentMethodId: string) => Promise<void>;
  isProcessing: boolean;
  amount: number;
}

const PaymentForm: React.FC<PaymentFormProps> = ({ onSubmit, isProcessing, amount }) => {
  const stripe = useStripe();
  const elements = useElements();
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (!stripe || !elements) {
      return;
    }

    const cardElement = elements.getElement(CardElement);
    if (!cardElement) {
      return;
    }

    const { error: stripeError, paymentMethod } = await stripe.createPaymentMethod({
      type: 'card',
      card: cardElement,
    });

    if (stripeError) {
      setError(stripeError.message || 'Payment failed');
      return;
    }

    if (paymentMethod) {
      await onSubmit(paymentMethod.id);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div>
        <label className="block text-sm font-medium text-gray-400 mb-3">
          Card Details
        </label>
        <div className="bg-gray-900 border border-gray-700 rounded-lg p-4">
          <CardElement
            options={{
              style: {
                base: {
                  fontSize: '16px',
                  color: '#ffffff',
                  '::placeholder': {
                    color: '#6b7280',
                  },
                },
                invalid: {
                  color: '#ef4444',
                },
              },
            }}
          />
        </div>
      </div>

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

      <button
        type="submit"
        disabled={!stripe || isProcessing}
        className="w-full py-3 bg-blue-600 hover:bg-blue-500 text-white font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
      >
        {isProcessing ? (
          <>
            <Loader2 className="w-5 h-5 animate-spin" />
            Processing...
          </>
        ) : (
          <>
            <Lock className="w-5 h-5" />
            Pay ${amount.toFixed(2)}
          </>
        )}
      </button>
    </form>
  );
};

// ============================================================================
// Main Checkout Component
// ============================================================================

export default function CheckoutFlow() {
  const { productId } = useParams<{ productId: string }>();
  const navigate = useNavigate();

  // State
  const [currentStep, setCurrentStep] = useState(1);
  const [product, setProduct] = useState<MarketplaceProductListItem | null>(null);
  const [selectedPricing, setSelectedPricing] = useState<SignalPackPricing | null>(null);
  const [couponCode, setCouponCode] = useState('');
  const [appliedCoupon, setAppliedCoupon] = useState<CouponData | null>(null);
  const [isValidatingCoupon, setIsValidatingCoupon] = useState(false);
  const [isProcessing, setIsProcessing] = useState(false);
  const [checkoutError, setCheckoutError] = useState<string | null>(null);
  const [isComplete, setIsComplete] = useState(false);

  // Store
  const {
    currentSignalPack,
    loadingDetail,
    fetchSignalPackById,
    subscribeToSignalPack,
  } = useMarketplaceStore();

  // Fetch product data
  useEffect(() => {
    if (productId) {
      fetchSignalPackById(productId);
    }
  }, [productId, fetchSignalPackById]);

  // Set product and default pricing when data loads
  useEffect(() => {
    if (currentSignalPack) {
      setProduct({
        id: currentSignalPack.id,
        name: currentSignalPack.name,
        slug: currentSignalPack.slug,
        shortDescription: currentSignalPack.shortDescription,
        thumbnailUrl: currentSignalPack.thumbnailUrl,
        productType: 'signals',
        providerName: currentSignalPack.provider.name,
        providerAvatar: currentSignalPack.provider.avatarUrl,
        providerVerified: currentSignalPack.provider.verified,
        priceUsd: currentSignalPack.pricing[0]?.priceUsd || 0,
        hasFreeTrial: currentSignalPack.hasFreeTrial,
        rating: currentSignalPack.rating,
        totalReviews: currentSignalPack.totalReviews,
        totalSubscribers: currentSignalPack.totalSubscribers,
        tags: [],
        createdAt: currentSignalPack.createdAt,
      });
      const defaultPricing =
        currentSignalPack.pricing.find((p) => p.period === 'monthly') ||
        currentSignalPack.pricing[0];
      setSelectedPricing(defaultPricing);
    }
  }, [currentSignalPack]);

  // Calculate final price
  const finalPrice = useMemo(() => {
    if (!selectedPricing) return 0;
    let price = selectedPricing.priceUsd;
    if (appliedCoupon?.isValid) {
      if (appliedCoupon.discountAmount) {
        price -= appliedCoupon.discountAmount;
      } else if (appliedCoupon.discountPercent) {
        price -= price * (appliedCoupon.discountPercent / 100);
      }
    }
    return Math.max(0, price);
  }, [selectedPricing, appliedCoupon]);

  // Validate coupon
  const handleApplyCoupon = async () => {
    if (!couponCode.trim()) return;

    setIsValidatingCoupon(true);
    try {
      // Simulated coupon validation - replace with actual API call
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // Mock validation logic
      if (couponCode.toUpperCase() === 'SAVE20') {
        setAppliedCoupon({
          code: couponCode.toUpperCase(),
          discountPercent: 20,
          isValid: true,
        });
      } else if (couponCode.toUpperCase() === 'NEWUSER') {
        setAppliedCoupon({
          code: couponCode.toUpperCase(),
          discountPercent: 15,
          isValid: true,
        });
      } else {
        setAppliedCoupon({
          code: couponCode,
          discountPercent: 0,
          isValid: false,
        });
      }
    } finally {
      setIsValidatingCoupon(false);
    }
  };

  // Remove coupon
  const handleRemoveCoupon = () => {
    setAppliedCoupon(null);
    setCouponCode('');
  };

  // Process payment
  const handlePayment = async (paymentMethodId: string) => {
    if (!product || !selectedPricing) return;

    setIsProcessing(true);
    setCheckoutError(null);

    try {
      await subscribeToSignalPack(product.id, selectedPricing.id);
      setIsComplete(true);
      setCurrentStep(3);
    } catch (error) {
      setCheckoutError(
        error instanceof Error ? error.message : 'Payment failed. Please try again.'
      );
    } finally {
      setIsProcessing(false);
    }
  };

  // Navigate between steps
  const handleNextStep = () => {
    if (currentStep < 3) {
      setCurrentStep(currentStep + 1);
    }
  };

  const handlePreviousStep = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  // Loading state
  if (loadingDetail) {
    return (
      <div className="flex items-center justify-center min-h-96">
        <Loader2 className="w-10 h-10 text-blue-500 animate-spin" />
      </div>
    );
  }

  // Error state
  if (!product && !loadingDetail) {
    return (
      <div className="flex flex-col items-center justify-center min-h-96">
        <AlertCircle className="w-12 h-12 text-red-400 mb-4" />
        <h2 className="text-xl font-semibold text-white mb-2">Product Not Found</h2>
        <p className="text-gray-400 mb-4">The requested product does not exist.</p>
        <Link
          to="/marketplace"
          className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg"
        >
          Back to Marketplace
        </Link>
      </div>
    );
  }

  // Success state
  if (isComplete) {
    return (
      <div className="max-w-2xl mx-auto">
        <div className="bg-gray-800 rounded-xl border border-gray-700 p-8 text-center">
          <div className="w-16 h-16 bg-green-500/20 rounded-full flex items-center justify-center mx-auto mb-6">
            <Check className="w-8 h-8 text-green-400" />
          </div>
          <h1 className="text-2xl font-bold text-white mb-2">Purchase Complete!</h1>
          <p className="text-gray-400 mb-6">
            Thank you for your purchase. You now have access to {product?.name}.
          </p>
          <div className="flex flex-col sm:flex-row gap-4 justify-center">
            <Link
              to="/marketplace"
              className="px-6 py-3 bg-gray-700 hover:bg-gray-600 text-white rounded-lg transition-colors"
            >
              Continue Shopping
            </Link>
            <Link
              to="/dashboard"
              className="px-6 py-3 bg-blue-600 hover:bg-blue-500 text-white rounded-lg transition-colors"
            >
              Go to Dashboard
            </Link>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto space-y-8">
      {/* Back link */}
      <Link
        to={`/marketplace/signals/${product?.slug}`}
        className="inline-flex items-center gap-2 text-gray-400 hover:text-white transition-colors"
      >
        <ArrowLeft className="w-4 h-4" />
        Back to Product
      </Link>

      {/* Progress Steps */}
      <div className="flex items-center justify-between">
        {CHECKOUT_STEPS.map((step, index) => (
          <React.Fragment key={step.id}>
            <div className="flex items-center gap-3">
              <div
                className={`w-10 h-10 rounded-full flex items-center justify-center font-medium transition-colors ${
                  currentStep >= step.id
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-700 text-gray-400'
                }`}
              >
                {currentStep > step.id ? <Check className="w-5 h-5" /> : step.id}
              </div>
              <div className="hidden sm:block">
                <p className="font-medium text-white">{step.title}</p>
                <p className="text-xs text-gray-500">{step.description}</p>
              </div>
            </div>
            {index < CHECKOUT_STEPS.length - 1 && (
              <div
                className={`flex-1 h-1 mx-4 rounded ${
                  currentStep > step.id ? 'bg-blue-600' : 'bg-gray-700'
                }`}
              />
            )}
          </React.Fragment>
        ))}
      </div>

      {/* Main Content */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Left Column - Step Content */}
        <div className="lg:col-span-2">
          {/* Step 1: Review */}
          {currentStep === 1 && product && currentSignalPack && (
            <div className="bg-gray-800 rounded-xl border border-gray-700 p-6 space-y-6">
              <h2 className="text-xl font-semibold text-white">Review Your Selection</h2>

              {/* Product Info */}
              <div className="flex items-start gap-4 p-4 bg-gray-900/50 rounded-lg">
                <div className="w-16 h-16 rounded-lg bg-gray-700 flex items-center justify-center flex-shrink-0">
                  {product.thumbnailUrl ? (
                    <img
                      src={product.thumbnailUrl}
                      alt={product.name}
                      className="w-full h-full object-cover rounded-lg"
                    />
                  ) : (
                    <CreditCard className="w-8 h-8 text-gray-500" />
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <h3 className="font-semibold text-white">{product.name}</h3>
                  <p className="text-sm text-gray-400">{product.providerName}</p>
                  <p className="text-sm text-gray-500 mt-1 line-clamp-2">
                    {product.shortDescription}
                  </p>
                </div>
              </div>

              {/* Pricing Options */}
              <div>
                <h3 className="text-sm font-medium text-gray-400 mb-3">
                  Select Subscription Plan
                </h3>
                <div className="space-y-3">
                  {currentSignalPack.pricing.map((pricing) => (
                    <button
                      key={pricing.id}
                      onClick={() => setSelectedPricing(pricing)}
                      className={`w-full p-4 rounded-lg border-2 transition-colors text-left ${
                        selectedPricing?.id === pricing.id
                          ? 'border-blue-500 bg-blue-500/10'
                          : 'border-gray-700 hover:border-gray-600 bg-gray-900/50'
                      }`}
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <div
                            className={`w-5 h-5 rounded-full border-2 flex items-center justify-center ${
                              selectedPricing?.id === pricing.id
                                ? 'border-blue-500 bg-blue-500'
                                : 'border-gray-600'
                            }`}
                          >
                            {selectedPricing?.id === pricing.id && (
                              <Check className="w-3 h-3 text-white" />
                            )}
                          </div>
                          <div>
                            <p className="font-medium text-white capitalize">
                              {pricing.period}
                            </p>
                            {pricing.discountPercent && (
                              <p className="text-sm text-green-400">
                                Save {pricing.discountPercent}%
                              </p>
                            )}
                          </div>
                        </div>
                        <div className="text-right">
                          <p className="text-xl font-bold text-white">
                            ${pricing.priceUsd}
                          </p>
                          {pricing.originalPriceUsd && (
                            <p className="text-sm text-gray-500 line-through">
                              ${pricing.originalPriceUsd}
                            </p>
                          )}
                        </div>
                      </div>
                      {pricing.isPopular && (
                        <span className="inline-block mt-2 px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded-full">
                          Most Popular
                        </span>
                      )}
                    </button>
                  ))}
                </div>
              </div>

              {/* Coupon Code */}
              <div>
                <h3 className="text-sm font-medium text-gray-400 mb-3">
                  Have a Coupon Code?
                </h3>
                {appliedCoupon?.isValid ? (
                  <div className="flex items-center justify-between p-3 bg-green-500/10 border border-green-500/30 rounded-lg">
                    <div className="flex items-center gap-2">
                      <Percent className="w-5 h-5 text-green-400" />
                      <span className="text-green-400 font-medium">
                        {appliedCoupon.code} - {appliedCoupon.discountPercent}% off
                      </span>
                    </div>
                    <button
                      onClick={handleRemoveCoupon}
                      className="text-gray-400 hover:text-white"
                    >
                      <Tag className="w-4 h-4" />
                    </button>
                  </div>
                ) : (
                  <div className="flex gap-3">
                    <input
                      type="text"
                      value={couponCode}
                      onChange={(e) => setCouponCode(e.target.value)}
                      placeholder="Enter coupon code"
                      className="flex-1 px-4 py-2.5 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-blue-500 focus:outline-none"
                    />
                    <button
                      onClick={handleApplyCoupon}
                      disabled={isValidatingCoupon || !couponCode.trim()}
                      className="px-4 py-2.5 bg-gray-700 hover:bg-gray-600 text-white rounded-lg transition-colors disabled:opacity-50"
                    >
                      {isValidatingCoupon ? (
                        <Loader2 className="w-5 h-5 animate-spin" />
                      ) : (
                        'Apply'
                      )}
                    </button>
                  </div>
                )}
                {appliedCoupon && !appliedCoupon.isValid && (
                  <p className="mt-2 text-sm text-red-400">Invalid coupon code</p>
                )}
              </div>

              {/* Continue Button */}
              <button
                onClick={handleNextStep}
                disabled={!selectedPricing}
                className="w-full py-3 bg-blue-600 hover:bg-blue-500 text-white font-medium rounded-lg transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
              >
                Continue to Payment
                <ArrowRight className="w-5 h-5" />
              </button>
            </div>
          )}

          {/* Step 2: Payment */}
          {currentStep === 2 && (
            <div className="bg-gray-800 rounded-xl border border-gray-700 p-6 space-y-6">
              <div className="flex items-center justify-between">
                <h2 className="text-xl font-semibold text-white">Payment Details</h2>
                <button
                  onClick={handlePreviousStep}
                  className="text-gray-400 hover:text-white flex items-center gap-1"
                >
                  <ArrowLeft className="w-4 h-4" />
                  Back
                </button>
              </div>

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

              <Elements stripe={stripePromise}>
                <PaymentForm
                  onSubmit={handlePayment}
                  isProcessing={isProcessing}
                  amount={finalPrice}
                />
              </Elements>

              {/* Security Notice */}
              <div className="flex items-center gap-3 p-3 bg-gray-900/50 rounded-lg">
                <Shield className="w-5 h-5 text-green-400 flex-shrink-0" />
                <p className="text-sm text-gray-400">
                  Your payment is secured with 256-bit SSL encryption
                </p>
              </div>
            </div>
          )}
        </div>

        {/* Right Column - Order Summary */}
        <div className="lg:col-span-1">
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-6 sticky top-6">
            <h3 className="text-lg font-semibold text-white mb-4">Order Summary</h3>

            {product && (
              <>
                {/* Product */}
                <div className="flex items-start gap-3 pb-4 border-b border-gray-700">
                  <div className="w-12 h-12 rounded-lg bg-gray-700 flex-shrink-0" />
                  <div className="flex-1 min-w-0">
                    <p className="font-medium text-white text-sm truncate">
                      {product.name}
                    </p>
                    <p className="text-xs text-gray-500">
                      {selectedPricing?.period || 'Monthly'} subscription
                    </p>
                  </div>
                </div>

                {/* Price Breakdown */}
                <div className="py-4 space-y-3">
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">Subtotal</span>
                    <span className="text-white">
                      ${selectedPricing?.priceUsd.toFixed(2) || '0.00'}
                    </span>
                  </div>

                  {appliedCoupon?.isValid && (
                    <div className="flex justify-between text-sm">
                      <span className="text-green-400">
                        Discount ({appliedCoupon.discountPercent}%)
                      </span>
                      <span className="text-green-400">
                        -$
                        {(
                          (selectedPricing?.priceUsd || 0) *
                          (appliedCoupon.discountPercent / 100)
                        ).toFixed(2)}
                      </span>
                    </div>
                  )}

                  {selectedPricing?.originalPriceUsd && (
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-400">Plan Savings</span>
                      <span className="text-green-400">
                        -$
                        {(
                          selectedPricing.originalPriceUsd - selectedPricing.priceUsd
                        ).toFixed(2)}
                      </span>
                    </div>
                  )}
                </div>

                {/* Total */}
                <div className="pt-4 border-t border-gray-700">
                  <div className="flex justify-between items-center">
                    <span className="text-lg font-semibold text-white">Total</span>
                    <span className="text-2xl font-bold text-white">
                      ${finalPrice.toFixed(2)}
                    </span>
                  </div>
                  {selectedPricing?.period !== 'lifetime' && (
                    <p className="text-xs text-gray-500 mt-1">
                      Billed {selectedPricing?.period}
                    </p>
                  )}
                </div>
              </>
            )}

            {/* Trust Badges */}
            <div className="mt-6 pt-6 border-t border-gray-700 space-y-3">
              <div className="flex items-center gap-2 text-sm text-gray-400">
                <Shield className="w-4 h-4 text-green-400" />
                <span>30-day money-back guarantee</span>
              </div>
              <div className="flex items-center gap-2 text-sm text-gray-400">
                <Lock className="w-4 h-4 text-blue-400" />
                <span>Secure SSL encryption</span>
              </div>
              <div className="flex items-center gap-2 text-sm text-gray-400">
                <Check className="w-4 h-4 text-purple-400" />
                <span>Cancel anytime</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
