/**
 * CheckoutSuccess Page
 * Displayed after successful Stripe checkout
 */

import React, { useEffect, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { CheckCircle, Loader2, ArrowRight, Sparkles } from 'lucide-react';
import { usePaymentStore } from '../../../stores/paymentStore';

export default function CheckoutSuccess() {
  const [searchParams] = useSearchParams();
  const [loading, setLoading] = useState(true);
  const { fetchCurrentSubscription, currentSubscription } = usePaymentStore();

  const sessionId = searchParams.get('session_id');

  useEffect(() => {
    const loadSubscription = async () => {
      try {
        await fetchCurrentSubscription();
      } catch (error) {
        console.error('Error fetching subscription:', error);
      } finally {
        setLoading(false);
      }
    };

    // Give Stripe webhook time to process
    const timer = setTimeout(loadSubscription, 2000);
    return () => clearTimeout(timer);
  }, [fetchCurrentSubscription]);

  if (loading) {
    return (
      <div className="min-h-[80vh] flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-12 h-12 text-blue-500 animate-spin mx-auto mb-4" />
          <h2 className="text-xl font-semibold text-white mb-2">
            Procesando tu pago...
          </h2>
          <p className="text-gray-400">
            Por favor espera mientras confirmamos tu suscripcion
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-[80vh] flex items-center justify-center px-4">
      <div className="max-w-md w-full text-center">
        {/* Success Icon */}
        <div className="relative mb-8">
          <div className="w-24 h-24 bg-green-500/20 rounded-full flex items-center justify-center mx-auto">
            <CheckCircle className="w-12 h-12 text-green-400" />
          </div>
          <Sparkles className="absolute top-0 right-1/4 w-6 h-6 text-yellow-400 animate-pulse" />
          <Sparkles className="absolute bottom-2 left-1/4 w-4 h-4 text-blue-400 animate-pulse delay-300" />
        </div>

        {/* Title */}
        <h1 className="text-3xl font-bold text-white mb-4">
          Pago Exitoso
        </h1>

        <p className="text-gray-400 mb-8">
          Tu suscripcion ha sido activada correctamente. Ya puedes disfrutar de todas las funcionalidades premium.
        </p>

        {/* Subscription Details */}
        {currentSubscription && (
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-6 mb-8 text-left">
            <h3 className="text-sm text-gray-400 mb-2">Detalles de tu suscripcion</h3>
            <div className="space-y-2">
              <div className="flex justify-between">
                <span className="text-gray-400">Plan</span>
                <span className="text-white font-medium">
                  {currentSubscription.plan?.name || 'Premium'}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-400">Ciclo</span>
                <span className="text-white font-medium">
                  {currentSubscription.interval === 'year' ? 'Anual' : 'Mensual'}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-400">Estado</span>
                <span className="text-green-400 font-medium">Activo</span>
              </div>
              {currentSubscription.currentPeriodEnd && (
                <div className="flex justify-between">
                  <span className="text-gray-400">Proxima factura</span>
                  <span className="text-white font-medium">
                    {new Date(currentSubscription.currentPeriodEnd).toLocaleDateString('es-ES')}
                  </span>
                </div>
              )}
            </div>
          </div>
        )}

        {/* Actions */}
        <div className="space-y-3">
          <Link
            to="/dashboard"
            className="flex items-center justify-center gap-2 w-full py-3 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium transition-colors"
          >
            Ir al Dashboard
            <ArrowRight className="w-5 h-5" />
          </Link>
          <Link
            to="/settings/billing"
            className="block w-full py-3 bg-gray-700 hover:bg-gray-600 text-white rounded-lg font-medium transition-colors"
          >
            Ver Detalles de Facturacion
          </Link>
        </div>

        {/* Session ID for debugging */}
        {sessionId && (
          <p className="mt-8 text-xs text-gray-600">
            ID de sesion: {sessionId.slice(0, 20)}...
          </p>
        )}
      </div>
    </div>
  );
}
