import React, { useState, useEffect } from 'react';
import { 
  CreditCard, CheckCircle, RefreshCw, AlertTriangle, Play, Calendar, DollarSign,
  ShieldCheck, ArrowRight, ExternalLink, QrCode
} from 'lucide-react';
import { SubscriptionStatus, SubscriptionPayment } from '../types';

interface SubscriptionViewProps {
  user: {
    name: string;
    email: string;
    subscriptionStatus: SubscriptionStatus;
  } | null;
  token: string | null;
  onStatusUpdate: (newStatus: SubscriptionStatus) => void;
}

export default function SubscriptionView({ user, token, onStatusUpdate }: SubscriptionViewProps) {
  const [payments, setPayments] = useState<SubscriptionPayment[]>([]);
  const [subStatus, setSubStatus] = useState<SubscriptionStatus | null>(user ? user.subscriptionStatus : null);
  const [isLoading, setIsLoading] = useState(true);
  
  // Checkout flow state
  const [billingType, setBillingType] = useState<'PIX' | 'CREDIT_CARD' | 'BOLETO'>('PIX');
  const [cardName, setCardName] = useState('');
  const [cardNumber, setCardNumber] = useState('');
  const [cardExpiry, setCardExpiry] = useState('');
  const [cardCvv, setCardCvv] = useState('');
  
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [successPayload, setSuccessPayload] = useState<any>(null);
  const [checkoutError, setCheckoutError] = useState<string | null>(null);

  const [enableBoleto, setEnableBoleto] = useState<boolean>(true);

  useEffect(() => {
    fetchSubscriptionDetails();
    if (token) {
      fetch('/api/settings', {
        headers: { 'Authorization': `Bearer ${token}` }
      })
        .then(res => res.json())
        .then(data => {
          if (data && data.enableBoleto === false) {
            setEnableBoleto(false);
          }
        })
        .catch(() => {});
    }
  }, []);

  const fetchSubscriptionDetails = async () => {
    setIsLoading(true);
    try {
      const res = await fetch('/api/subscription/status', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      if (res.ok) {
        const data = await res.json();
        setSubStatus(data.status);
        setPayments(data.payments);
        onStatusUpdate(data.status);
      }
    } catch (err) {
      console.error('Error fetching subscription status:', err);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCheckout = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setCheckoutError(null);
    setSuccessPayload(null);

    const creditCardInfo = billingType === 'CREDIT_CARD' ? {
      creditCard: {
        holderName: cardName,
        number: cardNumber.replace(/\s+/g, ''),
        expiryMonth: cardExpiry.split('/')[0]?.trim(),
        expiryYear: '20' + cardExpiry.split('/')[1]?.trim(),
        ccv: cardCvv
      },
      creditCardHolderInfo: {
        name: cardName,
        email: user?.email,
        cpfCnpj: '000.000.000-00',
        postalCode: '01001-000',
        addressNumber: '123',
        phone: '11999999999'
      }
    } : undefined;

    try {
      const res = await fetch('/api/subscription/subscribe', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          billingType,
          creditCardInfo
        })
      });

      const data = await res.json();
      if (!res.ok) {
        throw new Error(data.error || 'Erro ao processar assinatura');
      }

      setSuccessPayload(data);
      // Wait a moment and fetch updated profile status
      await fetchSubscriptionDetails();
    } catch (err: any) {
      setCheckoutError(err.message || 'Erro de rede. Tente novamente.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const getStatusColor = (status: SubscriptionStatus) => {
    switch (status) {
      case 'ACTIVE': return 'text-emerald-500 bg-emerald-500/10 border-emerald-500/20';
      case 'TRIAL': return 'text-amber-500 bg-amber-500/10 border-amber-500/20';
      case 'OVERDUE': return 'text-red-500 bg-red-500/10 border-red-500/20';
      case 'CANCELED': return 'text-zinc-400 bg-zinc-800 border-zinc-700';
      default: return 'text-zinc-500 bg-zinc-800 border-zinc-700';
    }
  };

  const getStatusLabel = (status: SubscriptionStatus) => {
    switch (status) {
      case 'ACTIVE': return 'Assinatura Ativa';
      case 'TRIAL': return 'Acesso de Avaliação (Trial)';
      case 'OVERDUE': return 'Fatura Vencida / Inadimplente';
      case 'CANCELED': return 'Assinatura Cancelada';
      default: return status;
    }
  };

  const getPaymentStatusTag = (status: string) => {
    switch (status) {
      case 'CONFIRMED':
      case 'RECEIVED':
        return <span className="bg-emerald-500/10 text-emerald-500 border border-emerald-500/20 px-2 py-0.5 rounded text-[10px] font-bold">✓ PAGO</span>;
      case 'PENDING':
        return <span className="bg-amber-500/10 text-amber-500 border border-amber-500/20 px-2 py-0.5 rounded text-[10px] font-bold">● AGUARDANDO</span>;
      case 'OVERDUE':
        return <span className="bg-red-500/10 text-red-500 border border-red-500/20 px-2 py-0.5 rounded text-[10px] font-bold">⚠ VENCIDO</span>;
      default:
        return <span className="bg-zinc-800 text-zinc-400 px-2 py-0.5 rounded text-[10px]">{status}</span>;
    }
  };

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[50vh] text-zinc-400 space-y-4">
        <RefreshCw className="w-8 h-8 text-[#E50914] animate-spin" />
        <p className="text-sm font-semibold">Buscando faturas e status financeiro...</p>
      </div>
    );
  }

  return (
    <div className="space-y-8 max-w-4xl mx-auto">
      {/* Top Title */}
      <div className="border-b border-white/10 pb-4">
        <h1 className="text-2xl md:text-3xl font-display font-extrabold text-white tracking-tight flex items-center space-x-2">
          <CreditCard className="w-8 h-8 text-[#E50914]" />
          <span>Gestão de Assinatura & Cobranças</span>
        </h1>
        <p className="text-xs text-zinc-500 mt-1">Veja seus comprovantes, históricos de faturamento e mude seu plano de estudos.</p>
      </div>

      {/* Main Grid: Status summary left, checkout right */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
        
        {/* Left Hand: Current Plan details & invoice history */}
        <div className="space-y-6">
          <div className="glass-card p-6 rounded-2xl space-y-5">
            <h3 className="font-display font-bold text-sm text-zinc-400 uppercase tracking-wider">Sua Conta</h3>
            
            <div className="flex items-center space-x-4">
              <div className="w-12 h-12 rounded-full glass-badge flex items-center justify-center text-zinc-300">
                <ShieldCheck className="w-6 h-6 text-[#E50914]" />
              </div>
              <div className="space-y-0.5">
                <p className="text-sm font-bold text-white">{user?.name}</p>
                <p className="text-xs text-zinc-500">{user?.email}</p>
              </div>
            </div>

            <div className="border-t border-zinc-850 pt-4 space-y-2">
              <p className="text-[10px] text-zinc-500 font-bold uppercase tracking-wider">Status Atual do Acesso</p>
              {subStatus && (
                <div className={`inline-block px-3 py-1.5 rounded-lg border text-sm font-extrabold ${getStatusColor(subStatus)}`}>
                  {getStatusLabel(subStatus)}
                </div>
              )}
              
              {subStatus === 'TRIAL' && (
                <p className="text-xs text-zinc-400 font-medium pt-1">
                  Seu período de teste está ativo. Para continuar com acesso ilimitado a todos os cursos, módulos e certificados, ative sua assinatura mensal abaixo.
                </p>
              )}
              {subStatus === 'ACTIVE' && (
                <p className="text-xs text-emerald-500/80 font-bold flex items-center space-x-1 pt-1">
                  <CheckCircle className="w-4 h-4 fill-emerald-500/10" />
                  <span>Acesso integral liberado a todos os cursos de informática, hardware e servidores!</span>
                </p>
              )}
              {subStatus === 'OVERDUE' && (
                <p className="text-xs text-red-500/80 font-semibold flex items-center space-x-1 pt-1">
                  <AlertTriangle className="w-4 h-4 fill-red-500/10" />
                  <span>Seu acesso foi bloqueado por falta de pagamento. Regularize via Pix ou Cartão para liberar.</span>
                </p>
              )}
            </div>
          </div>

          {/* Past Payments History */}
          <div className="glass-card p-6 rounded-2xl space-y-4">
            <h3 className="font-display font-bold text-sm text-zinc-400 uppercase tracking-wider">Faturas e Segunda Via</h3>
            
            <div className="space-y-3">
              {payments.length === 0 ? (
                <p className="text-xs text-zinc-500 italic">Nenhum pagamento registrado nesta conta.</p>
              ) : (
                payments.map(pay => (
                  <div 
                    key={pay.id} 
                    className="p-3.5 glass-badge rounded-xl flex items-center justify-between"
                  >
                    <div className="space-y-1">
                      <div className="flex items-center space-x-2">
                        <span className="text-white text-xs font-bold">R$ {pay.value.toFixed(2)}</span>
                        {getPaymentStatusTag(pay.status)}
                      </div>
                      <p className="text-[10px] text-zinc-500 flex items-center space-x-1 font-medium">
                        <Calendar className="w-3 h-3" />
                        <span>Vence em: {new Date(pay.dueDate).toLocaleDateString('pt-BR')}</span>
                      </p>
                    </div>

                    <a 
                      href={pay.invoiceUrl} 
                      target="_blank" 
                      rel="noreferrer" 
                      className="text-xs text-zinc-400 hover:text-[#E50914] glass-btn-secondary px-3 py-1.5 rounded-lg font-bold transition-all flex items-center space-x-1"
                    >
                      <span>Boleto / Pix / Detalhes</span>
                      <ExternalLink className="w-3 h-3" />
                    </a>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>

        {/* Right Hand: Checkout Form (Create Subscription) */}
        <div className="space-y-6">
          <div className="glass-card p-6 rounded-2xl space-y-6">
            <div className="space-y-1">
              <h3 className="font-display font-extrabold text-lg text-white tracking-tight">Assine o Plano Ilimitado</h3>
              <p className="text-xs text-zinc-500 font-semibold flex items-center space-x-1">
                <span>Trilha completa da Plataforma por apenas</span>
                <span className="text-[#E50914] font-black text-sm">R$ 49,90/mês</span>
              </p>
            </div>

            {/* Billing Types Toggle */}
            <div className={`grid ${enableBoleto ? 'grid-cols-3' : 'grid-cols-2'} gap-2 p-1 glass-badge rounded-lg`}>
              <button
                type="button"
                onClick={() => { setBillingType('PIX'); setCheckoutError(null); }}
                className={`py-2 text-xs font-bold rounded-md transition-all cursor-pointer ${billingType === 'PIX' ? 'bg-[#E50914] text-white' : 'text-zinc-400 hover:text-zinc-200'}`}
              >
                PIX
              </button>
              <button
                type="button"
                onClick={() => { setBillingType('CREDIT_CARD'); setCheckoutError(null); }}
                className={`py-2 text-xs font-bold rounded-md transition-all cursor-pointer ${billingType === 'BOLETO' && !enableBoleto ? 'bg-[#E50914] text-white' : billingType === 'CREDIT_CARD' ? 'bg-[#E50914] text-white' : 'text-zinc-400 hover:text-zinc-200'}`}
              >
                Cartão de Crédito
              </button>
              {enableBoleto && (
                <button
                  type="button"
                  onClick={() => { setBillingType('BOLETO'); setCheckoutError(null); }}
                  className={`py-2 text-xs font-bold rounded-md transition-all cursor-pointer ${billingType === 'BOLETO' ? 'bg-[#E50914] text-white' : 'text-zinc-400 hover:text-zinc-200'}`}
                >
                  Boleto
                </button>
              )}
            </div>

            {/* Error alerts */}
            {checkoutError && (
              <div className="p-3 bg-red-950/40 border border-red-900/50 rounded-lg text-xs text-red-400">
                {checkoutError}
              </div>
            )}

            {/* SUCCESS PAYLOAD (PIX QR CODE OR CREDIT CARD CLEAR) */}
            {successPayload ? (
              <div className="bg-zinc-900/60 border border-emerald-950 p-5 rounded-xl space-y-4 text-center">
                <div className="w-10 h-10 bg-emerald-500/10 text-emerald-500 rounded-full flex items-center justify-center mx-auto">
                  <CheckCircle className="w-6 h-6 fill-emerald-500/10" />
                </div>
                
                <div className="space-y-1">
                  <h4 className="text-sm font-bold text-white">Inscrição criada com sucesso!</h4>
                  <p className="text-xs text-zinc-400">
                    Sua assinatura está sendo faturada e integrada com o Asaas.
                  </p>
                </div>

                {billingType === 'PIX' && (
                  <div className="space-y-3 pt-2">
                    <p className="text-[11px] text-zinc-400 max-w-sm mx-auto">
                      Para sua segurança, os pagamentos recorrentes via PIX e Boleto são processados diretamente no ambiente seguro do Asaas. Clique no botão abaixo para escanear o QR Code oficial ou copiar a linha digitável.
                    </p>
                  </div>
                )}

                <div className="pt-2">
                  <a 
                    href={successPayload.payment?.invoiceUrl} 
                    target="_blank" 
                    rel="noreferrer"
                    className="w-full bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-bold py-2.5 px-4 rounded-lg transition-colors flex items-center justify-center space-x-1.5"
                  >
                    <span>Abrir Fatura Oficial (Asaas)</span>
                    <ExternalLink className="w-4 h-4" />
                  </a>
                </div>
              </div>
            ) : (
              /* ACTIVE CHECKOUT FORM */
              <form onSubmit={handleCheckout} className="space-y-4">
                {billingType === 'CREDIT_CARD' ? (
                  <div className="space-y-4">
                    <div className="space-y-1">
                      <label className="text-[10px] text-zinc-500 font-bold uppercase">Nome impresso no Cartão</label>
                      <input
                        type="text"
                        required
                        value={cardName}
                        onChange={(e) => setCardName(e.target.value)}
                        placeholder="Ex: SIDNEY GOMES"
                        className="w-full glass-input rounded-lg p-2.5 text-xs text-white focus:outline-none"
                      />
                    </div>

                    <div className="space-y-1">
                      <label className="text-[10px] text-zinc-500 font-bold uppercase">Número do Cartão de Crédito</label>
                      <input
                        type="text"
                        required
                        maxLength={19}
                        value={cardNumber}
                        onChange={(e) => setCardNumber(e.target.value.replace(/\s?/g, '').replace(/(\d{4})/g, '$1 ').trim())}
                        placeholder="4551 1234 5678 9012"
                        className="w-full glass-input rounded-lg p-2.5 text-xs text-white focus:outline-none"
                      />
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-1">
                        <label className="text-[10px] text-zinc-500 font-bold uppercase">Vencimento (MM/AA)</label>
                        <input
                          type="text"
                          required
                          maxLength={5}
                          placeholder="12/29"
                          value={cardExpiry}
                          onChange={(e) => setCardExpiry(e.target.value)}
                          className="w-full glass-input rounded-lg p-2.5 text-xs text-white focus:outline-none"
                        />
                      </div>
                      <div className="space-y-1">
                        <label className="text-[10px] text-zinc-500 font-bold uppercase">CVV</label>
                        <input
                          type="password"
                          required
                          maxLength={4}
                          placeholder="123"
                          value={cardCvv}
                          onChange={(e) => setCardCvv(e.target.value)}
                          className="w-full glass-input rounded-lg p-2.5 text-xs text-white focus:outline-none"
                        />
                      </div>
                    </div>
                  </div>
                ) : (
                  /* PIX or BOLETO Info */
                  <div className="p-4 glass-badge rounded-xl text-xs text-zinc-400 space-y-2 leading-relaxed">
                    <p className="font-semibold text-white">Informações da Assinatura:</p>
                    <p>
                      - Faturamento recorrente mensal (R$ 49,90) via {billingType}.
                    </p>
                    <p>
                      - O link para pagamento, Pix Copia e Cola e código de barras serão gerados dinamicamente de forma integrada com a API oficial do Asaas.
                    </p>
                  </div>
                )}

                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="w-full glass-btn-primary text-white text-xs font-bold py-3 px-4 rounded-lg flex items-center justify-center space-x-1.5 cursor-pointer disabled:opacity-50"
                >
                  {isSubmitting ? (
                    <>
                      <RefreshCw className="w-4 h-4 animate-spin" />
                      <span>Registrando no Asaas...</span>
                    </>
                  ) : (
                    <>
                      <span>Confirmar Assinatura - R$ 49,90/mês</span>
                      <ArrowRight className="w-4 h-4" />
                    </>
                  )}
                </button>
              </form>
            )}
          </div>
        </div>

      </div>
    </div>
  );
}
