/**
 * Pricing Page
 * Displays pricing plans with comparison
 */

import React, { useEffect, useState } from 'react';
import { Check, Loader2 } from 'lucide-react';
import { usePaymentStore } from '../../../stores/paymentStore';
import { PricingCard } from '../../../components/payments';
import type { PlanInterval } from '../../../types/payment.types';

export default function Pricing() {
  const {
    plans,
    currentSubscription,
    loadingPlans,
    loadingSubscription,
    processingPayment,
    fetchPlans,
    fetchCurrentSubscription,
    createCheckoutSession,
  } = usePaymentStore();

  const [interval, setInterval] = useState<PlanInterval>('month');

  useEffect(() => {
    fetchPlans();
    fetchCurrentSubscription();
  }, [fetchPlans, fetchCurrentSubscription]);

  const handleSelectPlan = async (planId: string, selectedInterval: PlanInterval) => {
    try {
      const checkoutUrl = await createCheckoutSession(planId, selectedInterval);
      window.location.href = checkoutUrl;
    } catch (error) {
      console.error('Error creating checkout session:', error);
    }
  };

  const activePlans = plans.filter((plan) => plan.isActive);

  // Sort plans by price
  const sortedPlans = [...activePlans].sort((a, b) => a.priceMonthly - b.priceMonthly);

  const yearlyDiscount = sortedPlans.length > 0
    ? Math.round(
        (1 - sortedPlans[1]?.priceYearly / 12 / sortedPlans[1]?.priceMonthly) * 100
      ) || 0
    : 0;

  const isLoading = loadingPlans || loadingSubscription;

  return (
    <div className="max-w-7xl mx-auto py-12 px-4">
      {/* Header */}
      <div className="text-center mb-12">
        <h1 className="text-4xl font-bold text-white mb-4">
          Planes y Precios
        </h1>
        <p className="text-xl text-gray-400 max-w-2xl mx-auto">
          Elige el plan que mejor se adapte a tus necesidades de trading e inversión
        </p>
      </div>

      {/* Billing Toggle */}
      <div className="flex items-center justify-center gap-4 mb-12">
        <span
          className={`text-sm font-medium ${
            interval === 'month' ? 'text-white' : 'text-gray-400'
          }`}
        >
          Mensual
        </span>
        <button
          onClick={() => setInterval(interval === 'month' ? 'year' : 'month')}
          className={`relative w-14 h-7 rounded-full transition-colors ${
            interval === 'year' ? 'bg-blue-600' : 'bg-gray-600'
          }`}
        >
          <div
            className={`absolute top-1 w-5 h-5 bg-white rounded-full transition-transform ${
              interval === 'year' ? 'translate-x-8' : 'translate-x-1'
            }`}
          />
        </button>
        <span
          className={`text-sm font-medium ${
            interval === 'year' ? 'text-white' : 'text-gray-400'
          }`}
        >
          Anual
        </span>
        {yearlyDiscount > 0 && (
          <span className="px-3 py-1 bg-green-500/20 text-green-400 text-sm font-medium rounded-full">
            Ahorra {yearlyDiscount}%
          </span>
        )}
      </div>

      {/* Plans Grid */}
      {isLoading ? (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="w-10 h-10 text-blue-500 animate-spin" />
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
          {sortedPlans.map((plan) => (
            <PricingCard
              key={plan.id}
              plan={plan}
              interval={interval}
              isCurrentPlan={currentSubscription?.planId === plan.id}
              onSelect={handleSelectPlan}
              loading={processingPayment}
            />
          ))}
        </div>
      )}

      {/* Feature Comparison Table */}
      <div className="mt-20">
        <h2 className="text-2xl font-bold text-white text-center mb-8">
          Comparación de Características
        </h2>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-gray-700">
                <th className="text-left py-4 px-4 text-gray-400 font-medium">
                  Característica
                </th>
                {sortedPlans.map((plan) => (
                  <th
                    key={plan.id}
                    className={`py-4 px-4 text-center font-medium ${
                      plan.isPopular ? 'text-purple-400' : 'text-white'
                    }`}
                  >
                    {plan.name}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-800">
              {/* Limits */}
              <tr>
                <td className="py-4 px-4 text-gray-300">API Calls / mes</td>
                {sortedPlans.map((plan) => (
                  <td key={plan.id} className="py-4 px-4 text-center text-white">
                    {plan.limits.maxApiCalls === -1
                      ? 'Ilimitados'
                      : plan.limits.maxApiCalls.toLocaleString()}
                  </td>
                ))}
              </tr>
              <tr>
                <td className="py-4 px-4 text-gray-300">Cursos</td>
                {sortedPlans.map((plan) => (
                  <td key={plan.id} className="py-4 px-4 text-center text-white">
                    {plan.limits.maxCourses === -1
                      ? 'Todos'
                      : plan.limits.maxCourses}
                  </td>
                ))}
              </tr>
              <tr>
                <td className="py-4 px-4 text-gray-300">Paper Trades</td>
                {sortedPlans.map((plan) => (
                  <td key={plan.id} className="py-4 px-4 text-center text-white">
                    {plan.limits.maxPaperTrades === -1
                      ? 'Ilimitados'
                      : plan.limits.maxPaperTrades}
                  </td>
                ))}
              </tr>
              <tr>
                <td className="py-4 px-4 text-gray-300">Watchlist Símbolos</td>
                {sortedPlans.map((plan) => (
                  <td key={plan.id} className="py-4 px-4 text-center text-white">
                    {plan.limits.maxWatchlistSymbols}
                  </td>
                ))}
              </tr>
              {/* Premium Features */}
              <tr>
                <td className="py-4 px-4 text-gray-300">Señales ML Premium</td>
                {sortedPlans.map((plan) => (
                  <td key={plan.id} className="py-4 px-4 text-center">
                    {plan.limits.mlSignalsAccess ? (
                      <Check className="w-5 h-5 text-green-400 mx-auto" />
                    ) : (
                      <span className="text-gray-600">—</span>
                    )}
                  </td>
                ))}
              </tr>
              <tr>
                <td className="py-4 px-4 text-gray-300">Soporte Prioritario</td>
                {sortedPlans.map((plan) => (
                  <td key={plan.id} className="py-4 px-4 text-center">
                    {plan.limits.prioritySupport ? (
                      <Check className="w-5 h-5 text-green-400 mx-auto" />
                    ) : (
                      <span className="text-gray-600">—</span>
                    )}
                  </td>
                ))}
              </tr>
              <tr>
                <td className="py-4 px-4 text-gray-300">Agentes Personalizados</td>
                {sortedPlans.map((plan) => (
                  <td key={plan.id} className="py-4 px-4 text-center">
                    {plan.limits.customAgents ? (
                      <Check className="w-5 h-5 text-green-400 mx-auto" />
                    ) : (
                      <span className="text-gray-600">—</span>
                    )}
                  </td>
                ))}
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      {/* FAQ Section */}
      <div className="mt-20">
        <h2 className="text-2xl font-bold text-white text-center mb-8">
          Preguntas Frecuentes
        </h2>
        <div className="max-w-3xl mx-auto space-y-6">
          <div className="bg-gray-800 rounded-xl p-6">
            <h3 className="font-medium text-white mb-2">
              ¿Puedo cambiar de plan en cualquier momento?
            </h3>
            <p className="text-gray-400">
              Sí, puedes actualizar o degradar tu plan en cualquier momento. Los cambios se aplican inmediatamente y se prorratea el cobro.
            </p>
          </div>
          <div className="bg-gray-800 rounded-xl p-6">
            <h3 className="font-medium text-white mb-2">
              ¿Qué métodos de pago aceptan?
            </h3>
            <p className="text-gray-400">
              Aceptamos todas las tarjetas de crédito y débito principales (Visa, Mastercard, American Express) a través de Stripe.
            </p>
          </div>
          <div className="bg-gray-800 rounded-xl p-6">
            <h3 className="font-medium text-white mb-2">
              ¿Puedo cancelar mi suscripción?
            </h3>
            <p className="text-gray-400">
              Sí, puedes cancelar en cualquier momento. Tu suscripción permanecerá activa hasta el final del período de facturación actual.
            </p>
          </div>
          <div className="bg-gray-800 rounded-xl p-6">
            <h3 className="font-medium text-white mb-2">
              ¿Ofrecen reembolsos?
            </h3>
            <p className="text-gray-400">
              Ofrecemos un reembolso completo dentro de los primeros 14 días si no estás satisfecho con el servicio.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
