/**
 * Billing Page
 * Manage subscription, payment methods, and view invoices
 */

import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import {
  CreditCard,
  FileText,
  Download,
  Plus,
  Trash2,
  Star,
  Loader2,
  AlertCircle,
  ExternalLink,
} from 'lucide-react';
import { usePaymentStore } from '../../../stores/paymentStore';
import {
  SubscriptionCard,
  UsageProgress,
  WalletCard,
  WalletDepositModal,
  WalletWithdrawModal,
} from '../../../components/payments';

type TabType = 'overview' | 'payment-methods' | 'invoices' | 'wallet';

export default function Billing() {
  const {
    currentSubscription,
    paymentMethods,
    invoices,
    usageStats,
    wallet,
    walletTransactions,
    loadingSubscription,
    loadingPaymentMethods,
    loadingInvoices,
    loadingUsage,
    loadingWallet,
    processingPayment,
    fetchCurrentSubscription,
    fetchPaymentMethods,
    fetchInvoices,
    fetchUsageStats,
    fetchWallet,
    cancelSubscription,
    reactivateSubscription,
    setDefaultPaymentMethod,
    removePaymentMethod,
    downloadInvoice,
    openBillingPortal,
  } = usePaymentStore();

  const [activeTab, setActiveTab] = useState<TabType>('overview');
  const [showCancelConfirm, setShowCancelConfirm] = useState(false);
  const [showDepositModal, setShowDepositModal] = useState(false);
  const [showWithdrawModal, setShowWithdrawModal] = useState(false);

  useEffect(() => {
    fetchCurrentSubscription();
    fetchPaymentMethods();
    fetchInvoices(10);
    fetchUsageStats();
    fetchWallet();
  }, [
    fetchCurrentSubscription,
    fetchPaymentMethods,
    fetchInvoices,
    fetchUsageStats,
    fetchWallet,
  ]);

  const handleCancelSubscription = async () => {
    try {
      await cancelSubscription();
      setShowCancelConfirm(false);
    } catch (error) {
      console.error('Error canceling subscription:', error);
    }
  };

  const handleReactivate = async () => {
    try {
      await reactivateSubscription();
    } catch (error) {
      console.error('Error reactivating subscription:', error);
    }
  };

  const handleSetDefault = async (paymentMethodId: string) => {
    try {
      await setDefaultPaymentMethod(paymentMethodId);
    } catch (error) {
      console.error('Error setting default payment method:', error);
    }
  };

  const handleRemovePaymentMethod = async (paymentMethodId: string) => {
    if (!confirm('¿Estás seguro de eliminar este método de pago?')) return;
    try {
      await removePaymentMethod(paymentMethodId);
    } catch (error) {
      console.error('Error removing payment method:', error);
    }
  };

  const handleDownloadInvoice = async (invoiceId: string) => {
    try {
      await downloadInvoice(invoiceId);
    } catch (error) {
      console.error('Error downloading invoice:', error);
    }
  };

  const isLoading =
    loadingSubscription || loadingPaymentMethods || loadingInvoices || loadingUsage;

  const tabs = [
    { id: 'overview', label: 'Resumen' },
    { id: 'payment-methods', label: 'Métodos de Pago' },
    { id: 'invoices', label: 'Facturas' },
    { id: 'wallet', label: 'Wallet' },
  ];

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Facturación</h1>
          <p className="text-gray-400">
            Gestiona tu suscripción, métodos de pago y facturas
          </p>
        </div>
        <button
          onClick={openBillingPortal}
          className="flex items-center gap-2 px-4 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg transition-colors"
        >
          <ExternalLink className="w-4 h-4" />
          Portal de Stripe
        </button>
      </div>

      {/* Tabs */}
      <div className="flex items-center gap-1 bg-gray-800 rounded-lg p-1">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id as TabType)}
            className={`flex-1 py-2 px-4 rounded-md font-medium transition-colors ${
              activeTab === tab.id
                ? 'bg-blue-600 text-white'
                : 'text-gray-400 hover:text-white'
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {isLoading ? (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="w-10 h-10 text-blue-500 animate-spin" />
        </div>
      ) : (
        <>
          {/* Overview Tab */}
          {activeTab === 'overview' && (
            <div className="space-y-6">
              {/* Subscription */}
              {currentSubscription ? (
                <SubscriptionCard
                  subscription={currentSubscription}
                  onManage={openBillingPortal}
                  onCancel={() => setShowCancelConfirm(true)}
                  onReactivate={handleReactivate}
                  onChangePlan={() => {
                    window.location.href = '/pricing';
                  }}
                  loading={processingPayment}
                />
              ) : (
                <div className="bg-gray-800 rounded-xl border border-gray-700 p-8 text-center">
                  <h3 className="text-xl font-bold text-white mb-2">
                    No tienes una suscripción activa
                  </h3>
                  <p className="text-gray-400 mb-6">
                    Elige un plan para acceder a todas las funcionalidades
                  </p>
                  <Link
                    to="/pricing"
                    className="inline-flex items-center gap-2 px-6 py-3 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium transition-colors"
                  >
                    Ver Planes
                  </Link>
                </div>
              )}

              {/* Usage Stats */}
              {usageStats && <UsageProgress usage={usageStats} />}
            </div>
          )}

          {/* Payment Methods Tab */}
          {activeTab === 'payment-methods' && (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h2 className="text-lg font-medium text-white">
                  Métodos de Pago
                </h2>
                <button
                  onClick={openBillingPortal}
                  className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg transition-colors"
                >
                  <Plus className="w-4 h-4" />
                  Agregar
                </button>
              </div>

              {paymentMethods.length > 0 ? (
                <div className="space-y-3">
                  {paymentMethods.map((method) => (
                    <div
                      key={method.id}
                      className="flex items-center justify-between p-4 bg-gray-800 rounded-xl border border-gray-700"
                    >
                      <div className="flex items-center gap-4">
                        <div className="p-3 bg-gray-700 rounded-lg">
                          <CreditCard className="w-6 h-6 text-gray-300" />
                        </div>
                        <div>
                          <div className="flex items-center gap-2">
                            <span className="font-medium text-white">
                              {method.brand} •••• {method.last4}
                            </span>
                            {method.isDefault && (
                              <span className="px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded-full">
                                Predeterminado
                              </span>
                            )}
                          </div>
                          {method.expiryMonth && method.expiryYear && (
                            <p className="text-sm text-gray-400">
                              Expira {method.expiryMonth}/{method.expiryYear}
                            </p>
                          )}
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        {!method.isDefault && (
                          <button
                            onClick={() => handleSetDefault(method.id)}
                            className="p-2 text-gray-400 hover:text-yellow-400 transition-colors"
                            title="Establecer como predeterminado"
                          >
                            <Star className="w-5 h-5" />
                          </button>
                        )}
                        <button
                          onClick={() => handleRemovePaymentMethod(method.id)}
                          className="p-2 text-gray-400 hover:text-red-400 transition-colors"
                          title="Eliminar"
                        >
                          <Trash2 className="w-5 h-5" />
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-12 bg-gray-800 rounded-xl border border-gray-700">
                  <CreditCard className="w-12 h-12 text-gray-500 mx-auto mb-4" />
                  <h3 className="font-medium text-white mb-2">
                    No hay métodos de pago
                  </h3>
                  <p className="text-gray-400 mb-4">
                    Agrega un método de pago para suscribirte
                  </p>
                  <button
                    onClick={openBillingPortal}
                    className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg transition-colors"
                  >
                    Agregar Método de Pago
                  </button>
                </div>
              )}
            </div>
          )}

          {/* Invoices Tab */}
          {activeTab === 'invoices' && (
            <div className="space-y-4">
              <h2 className="text-lg font-medium text-white">
                Historial de Facturas
              </h2>

              {invoices.length > 0 ? (
                <div className="bg-gray-800 rounded-xl border border-gray-700 overflow-hidden">
                  <table className="w-full">
                    <thead>
                      <tr className="bg-gray-900/50">
                        <th className="text-left py-3 px-4 text-sm text-gray-400 font-medium">
                          Número
                        </th>
                        <th className="text-left py-3 px-4 text-sm text-gray-400 font-medium">
                          Fecha
                        </th>
                        <th className="text-left py-3 px-4 text-sm text-gray-400 font-medium">
                          Monto
                        </th>
                        <th className="text-left py-3 px-4 text-sm text-gray-400 font-medium">
                          Estado
                        </th>
                        <th className="text-right py-3 px-4 text-sm text-gray-400 font-medium">
                          Acciones
                        </th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-700">
                      {invoices.map((invoice) => (
                        <tr key={invoice.id} className="hover:bg-gray-700/30">
                          <td className="py-3 px-4">
                            <span className="text-white">{invoice.number}</span>
                          </td>
                          <td className="py-3 px-4 text-gray-400">
                            {new Date(invoice.createdAt).toLocaleDateString(
                              'es-ES'
                            )}
                          </td>
                          <td className="py-3 px-4 text-white font-medium">
                            ${invoice.amount.toFixed(2)} {invoice.currency}
                          </td>
                          <td className="py-3 px-4">
                            <span
                              className={`px-2 py-1 text-xs rounded-full ${
                                invoice.status === 'paid'
                                  ? 'bg-green-500/20 text-green-400'
                                  : invoice.status === 'open'
                                  ? 'bg-yellow-500/20 text-yellow-400'
                                  : 'bg-gray-500/20 text-gray-400'
                              }`}
                            >
                              {invoice.status === 'paid'
                                ? 'Pagada'
                                : invoice.status === 'open'
                                ? 'Pendiente'
                                : invoice.status}
                            </span>
                          </td>
                          <td className="py-3 px-4 text-right">
                            <div className="flex items-center justify-end gap-2">
                              {invoice.hostedInvoiceUrl && (
                                <a
                                  href={invoice.hostedInvoiceUrl}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="p-2 text-gray-400 hover:text-white transition-colors"
                                  title="Ver factura"
                                >
                                  <FileText className="w-4 h-4" />
                                </a>
                              )}
                              {invoice.pdfUrl && (
                                <button
                                  onClick={() => handleDownloadInvoice(invoice.id)}
                                  className="p-2 text-gray-400 hover:text-white transition-colors"
                                  title="Descargar PDF"
                                >
                                  <Download className="w-4 h-4" />
                                </button>
                              )}
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div className="text-center py-12 bg-gray-800 rounded-xl border border-gray-700">
                  <FileText className="w-12 h-12 text-gray-500 mx-auto mb-4" />
                  <h3 className="font-medium text-white mb-2">
                    No hay facturas
                  </h3>
                  <p className="text-gray-400">
                    Las facturas aparecerán aquí cuando realices pagos
                  </p>
                </div>
              )}
            </div>
          )}

          {/* Wallet Tab */}
          {activeTab === 'wallet' && (
            <div>
              {wallet ? (
                <WalletCard
                  wallet={wallet}
                  recentTransactions={walletTransactions}
                  onDeposit={() => setShowDepositModal(true)}
                  onWithdraw={() => setShowWithdrawModal(true)}
                  onViewHistory={() => {}}
                  loading={loadingWallet}
                />
              ) : (
                <div className="text-center py-12 bg-gray-800 rounded-xl border border-gray-700">
                  <h3 className="font-medium text-white mb-2">
                    Wallet no disponible
                  </h3>
                  <p className="text-gray-400">
                    Suscríbete a un plan para activar tu wallet
                  </p>
                </div>
              )}
            </div>
          )}
        </>
      )}

      {/* Cancel Confirmation Modal */}
      {showCancelConfirm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-gray-800 rounded-xl p-6 max-w-md mx-4">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-3 bg-red-500/20 rounded-full">
                <AlertCircle className="w-6 h-6 text-red-400" />
              </div>
              <h3 className="text-xl font-bold text-white">
                Cancelar Suscripción
              </h3>
            </div>
            <p className="text-gray-400 mb-6">
              ¿Estás seguro de que deseas cancelar tu suscripción? Mantendrás el acceso hasta el final del período actual.
            </p>
            <div className="flex gap-3">
              <button
                onClick={() => setShowCancelConfirm(false)}
                className="flex-1 py-2 px-4 bg-gray-700 hover:bg-gray-600 text-white rounded-lg transition-colors"
              >
                No, mantener
              </button>
              <button
                onClick={handleCancelSubscription}
                disabled={processingPayment}
                className="flex-1 py-2 px-4 bg-red-600 hover:bg-red-500 text-white rounded-lg transition-colors disabled:opacity-50"
              >
                {processingPayment ? 'Cancelando...' : 'Sí, cancelar'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Wallet Deposit Modal */}
      <WalletDepositModal
        isOpen={showDepositModal}
        onClose={() => setShowDepositModal(false)}
        onSuccess={() => {
          setShowDepositModal(false);
          fetchWallet();
        }}
      />

      {/* Wallet Withdraw Modal */}
      <WalletWithdrawModal
        isOpen={showWithdrawModal}
        onClose={() => setShowWithdrawModal(false)}
        onSuccess={() => {
          setShowWithdrawModal(false);
          fetchWallet();
        }}
        availableBalance={wallet?.availableBalance || 0}
      />
    </div>
  );
}
