/**
 * SubscriptionCard Component
 * Displays current subscription status and management options
 */

import React from 'react';
import {
  CreditCard,
  Calendar,
  AlertCircle,
  CheckCircle,
  Clock,
  XCircle,
  RefreshCw,
  Settings,
  Zap,
} from 'lucide-react';
import type { SubscriptionWithPlan, SubscriptionStatus } from '../../types/payment.types';

interface SubscriptionCardProps {
  subscription: SubscriptionWithPlan;
  onManage?: () => void;
  onCancel?: () => void;
  onReactivate?: () => void;
  onChangePlan?: () => void;
  loading?: boolean;
}

const statusStyles: Record<SubscriptionStatus, { icon: React.ReactNode; text: string; color: string }> = {
  active: {
    icon: <CheckCircle className="w-5 h-5" />,
    text: 'Activa',
    color: 'text-green-400 bg-green-500/20',
  },
  past_due: {
    icon: <AlertCircle className="w-5 h-5" />,
    text: 'Pago Pendiente',
    color: 'text-yellow-400 bg-yellow-500/20',
  },
  cancelled: {
    icon: <XCircle className="w-5 h-5" />,
    text: 'Cancelada',
    color: 'text-red-400 bg-red-500/20',
  },
  canceled: {
    icon: <XCircle className="w-5 h-5" />,
    text: 'Cancelada',
    color: 'text-red-400 bg-red-500/20',
  },
  trialing: {
    icon: <Clock className="w-5 h-5" />,
    text: 'Período de Prueba',
    color: 'text-blue-400 bg-blue-500/20',
  },
  incomplete: {
    icon: <RefreshCw className="w-5 h-5" />,
    text: 'Incompleta',
    color: 'text-orange-400 bg-orange-500/20',
  },
  unpaid: {
    icon: <AlertCircle className="w-5 h-5" />,
    text: 'Sin Pagar',
    color: 'text-red-400 bg-red-500/20',
  },
  paused: {
    icon: <Clock className="w-5 h-5" />,
    text: 'Pausada',
    color: 'text-gray-400 bg-gray-500/20',
  },
};

export const SubscriptionCard: React.FC<SubscriptionCardProps> = ({
  subscription,
  onManage,
  onCancel,
  onReactivate,
  onChangePlan,
  loading = false,
}) => {
  const statusInfo = statusStyles[subscription.status];
  const isActive = subscription.status === 'active' || subscription.status === 'trialing';
  const willCancel = subscription.cancelAtPeriodEnd;

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

  const daysUntilRenewal = () => {
    const end = new Date(subscription.currentPeriodEnd);
    const now = new Date();
    const diff = Math.ceil((end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
    return diff;
  };

  return (
    <div className="bg-gray-800 rounded-xl border border-gray-700 overflow-hidden">
      {/* Header */}
      <div className="p-6 border-b border-gray-700">
        <div className="flex items-start justify-between">
          <div>
            <div className="flex items-center gap-3 mb-2">
              <h3 className="text-xl font-bold text-white">{subscription.planName}</h3>
              <span className={`px-2 py-1 rounded-full text-xs font-medium flex items-center gap-1 ${statusInfo.color}`}>
                {statusInfo.icon}
                {statusInfo.text}
              </span>
            </div>
            <p className="text-sm text-gray-400">
              {subscription.interval === 'month' ? 'Facturación mensual' : 'Facturación anual'}
            </p>
          </div>

          <div className="text-right">
            <div className="text-2xl font-bold text-white">
              ${subscription.amount.toFixed(2)}
              <span className="text-sm text-gray-400 font-normal">
                /{subscription.interval === 'month' ? 'mes' : 'año'}
              </span>
            </div>
            <div className="text-xs text-gray-500 uppercase">
              {subscription.currency}
            </div>
          </div>
        </div>
      </div>

      {/* Details */}
      <div className="p-6 space-y-4">
        {/* Billing Period */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2 text-gray-400">
            <Calendar className="w-4 h-4" />
            <span>Período actual</span>
          </div>
          <span className="text-white">
            {formatDate(subscription.currentPeriodStart)} - {formatDate(subscription.currentPeriodEnd)}
          </span>
        </div>

        {/* Next Billing */}
        {isActive && !willCancel && (
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2 text-gray-400">
              <CreditCard className="w-4 h-4" />
              <span>Próximo cobro</span>
            </div>
            <span className="text-white">
              {formatDate(subscription.currentPeriodEnd)} ({daysUntilRenewal()} días)
            </span>
          </div>
        )}

        {/* Trial End */}
        {subscription.trialEnd && subscription.status === 'trialing' && (
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2 text-blue-400">
              <Clock className="w-4 h-4" />
              <span>Fin del período de prueba</span>
            </div>
            <span className="text-blue-400 font-medium">
              {formatDate(subscription.trialEnd)}
            </span>
          </div>
        )}

        {/* Cancellation Notice */}
        {willCancel && (
          <div className="p-4 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">
            <div className="flex items-start gap-3">
              <AlertCircle className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" />
              <div>
                <p className="text-yellow-400 font-medium">
                  Tu suscripción se cancelará el {formatDate(subscription.currentPeriodEnd)}
                </p>
                <p className="text-sm text-gray-400 mt-1">
                  Puedes reactivarla en cualquier momento antes de esa fecha.
                </p>
              </div>
            </div>
          </div>
        )}

        {/* Plan Features Summary */}
        {subscription.plan && (
          <div className="p-4 bg-gray-900/50 rounded-lg">
            <h4 className="text-sm font-medium text-gray-400 mb-3">Tu plan incluye:</h4>
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div className="flex items-center gap-2">
                <Zap className="w-4 h-4 text-yellow-400" />
                <span className="text-white">
                  {subscription.plan.limits.maxApiCalls === -1
                    ? 'API calls ilimitados'
                    : `${subscription.plan.limits.maxApiCalls.toLocaleString()} API calls/mes`}
                </span>
              </div>
              <div className="flex items-center gap-2">
                <CheckCircle className="w-4 h-4 text-green-400" />
                <span className="text-white">
                  {subscription.plan.limits.maxCourses === -1
                    ? 'Todos los cursos'
                    : `${subscription.plan.limits.maxCourses} cursos`}
                </span>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Actions */}
      <div className="p-6 bg-gray-900/30 border-t border-gray-700 flex flex-wrap gap-3">
        {onManage && (
          <button
            onClick={onManage}
            disabled={loading}
            className="flex items-center gap-2 px-4 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg transition-colors disabled:opacity-50"
          >
            <Settings className="w-4 h-4" />
            Gestionar Facturación
          </button>
        )}

        {onChangePlan && isActive && !willCancel && (
          <button
            onClick={onChangePlan}
            disabled={loading}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg transition-colors disabled:opacity-50"
          >
            <RefreshCw className="w-4 h-4" />
            Cambiar Plan
          </button>
        )}

        {onCancel && isActive && !willCancel && (
          <button
            onClick={onCancel}
            disabled={loading}
            className="flex items-center gap-2 px-4 py-2 text-red-400 hover:bg-red-500/10 rounded-lg transition-colors disabled:opacity-50"
          >
            <XCircle className="w-4 h-4" />
            Cancelar
          </button>
        )}

        {onReactivate && willCancel && (
          <button
            onClick={onReactivate}
            disabled={loading}
            className="flex items-center gap-2 px-4 py-2 bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors disabled:opacity-50"
          >
            <CheckCircle className="w-4 h-4" />
            Reactivar Suscripción
          </button>
        )}
      </div>
    </div>
  );
};

export default SubscriptionCard;
