@model QRRapidoApp.Models.User
@inject Microsoft.Extensions.Localization.IStringLocalizer<QRRapidoApp.Resources.SharedResource> Localizer
@{
    ViewData["Title"] = Localizer["UserProfileTitle"];
    var isPremium = ViewBag.IsPremium as bool? ?? false;
    var monthlyQRCount = ViewBag.MonthlyQRCount as int? ?? 0;
    var qrHistory = ViewBag.QRHistory as List<QRRapidoApp.Models.QRCodeHistory> ?? new List<QRRapidoApp.Models.QRCodeHistory>();
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container mt-4">
    <div class="row">
        <div class="col-lg-8 mx-auto">
            <!-- Header do Perfil -->
            <div class="card mb-4 border-0 shadow-sm">
                <div class="card-header bg-primary text-white d-flex align-items-center">
                    <i class="fas fa-user-circle fa-2x me-3"></i>
                    <div>
                        <h4 class="mb-0">@Model.Name</h4>
                        <small class="opacity-75">@Model.Email</small>
                    </div>
                </div>
                
                <div class="card-body">
                    <div class="row g-3">
                        <!-- Status do Plano -->
                        <div class="col-md-6">
                            <div class="d-flex align-items-center mb-2">
                                <i class="fas fa-crown me-2 @(isPremium ? "text-warning" : "text-muted")"></i>
                                <strong>Status do Plano:</strong>
                            </div>
                            @if (isPremium)
                            {
                                <span class="badge bg-warning text-dark fs-6">
                                    <i class="fas fa-star me-1"></i>Premium
                                </span>
                                @if (Model.PremiumExpiresAt.HasValue)
                                {
                                    <p class="text-muted small mt-1 mb-0">
                                        Expira em: @Model.PremiumExpiresAt.Value.ToString("dd/MM/yyyy")
                                    </p>
                                }
                                @if (!string.IsNullOrEmpty(Model.StripeSubscriptionId))
                                {
                                    var canRefund = Model.SubscriptionStartedAt.HasValue &&
                                                   (DateTime.UtcNow - Model.SubscriptionStartedAt.Value).TotalDays <= 7;
                                    var daysSinceSubscription = Model.SubscriptionStartedAt.HasValue
                                        ? Math.Round((DateTime.UtcNow - Model.SubscriptionStartedAt.Value).TotalDays, 1)
                                        : 0;

                                    <p class="mt-2 mb-0">
                                        @if (canRefund)
                                        {
                                            <button type="button" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#refundSubscriptionModal">
                                                <i class="fas fa-undo me-1"></i>Solicitar Reembolso (CDC)
                                            </button>
                                            <small class="text-muted d-block mt-1">
                                                <i class="fas fa-info-circle"></i> Você tem direito a reembolso total (7 dias)
                                            </small>
                                        }
                                        else
                                        {
                                            <button type="button" class="btn btn-sm btn-outline-danger" data-bs-toggle="modal" data-bs-target="#cancelSubscriptionModal">
                                                <i class="fas fa-times-circle me-1"></i>Cancelar Renovação
                                            </button>
                                            @if (daysSinceSubscription > 0)
                                            {
                                                <small class="text-muted d-block mt-1">
                                                    <i class="fas fa-info-circle"></i> Assinatura há @daysSinceSubscription dias (período de reembolso expirado)
                                                </small>
                                            }
                                        }
                                    </p>
                                }
                            }
                            else
                            {
                                <span class="badge bg-secondary fs-6">
                                    <i class="fas fa-user me-1"></i>Gratuito
                                </span>
                                <p class="text-muted small mt-1 mb-0">
                                    <a href="/Pagamento/SelecaoPlano" class="text-decoration-none">
                                        <i class="fas fa-arrow-up me-1"></i>Fazer upgrade
                                    </a>
                                </p>
                            }
                        </div>

                        <!-- Data de Cadastro -->
                        <div class="col-md-6">
                            <div class="d-flex align-items-center mb-2">
                                <i class="fas fa-calendar-alt me-2 text-info"></i>
                                <strong>Membro desde:</strong>
                            </div>
                            <p class="text-muted mb-0">@Model.CreatedAt.ToString("dd/MM/yyyy")</p>
                        </div>

                        <!-- Provedor de Login -->
                        <div class="col-md-6">
                            <div class="d-flex align-items-center mb-2">
                                <i class="fab fa-@(Model.Provider.ToLower()) me-2 text-primary"></i>
                                <strong>Conectado via:</strong>
                            </div>
                            <p class="text-muted mb-0">@Model.Provider</p>
                        </div>

                        <!-- Último Login -->
                        <div class="col-md-6">
                            <div class="d-flex align-items-center mb-2">
                                <i class="fas fa-sign-in-alt me-2 text-success"></i>
                                <strong>Último acesso:</strong>
                            </div>
                            <p class="text-muted mb-0">@Model.LastLoginAt.ToString("dd/MM/yyyy HH:mm")</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Estatísticas de Uso -->
            <div class="card mb-4 border-0 shadow-sm">
                <div class="card-header bg-info text-white">
                    <h5 class="mb-0">
                        <i class="fas fa-chart-bar me-2"></i>Estatísticas de Uso
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row text-center g-3">
                        <div class="col-md-4">
                            <div class="p-3 border rounded bg-light profile-stat">
                                <h3 class="text-primary mb-1">@Model.TotalQRGenerated</h3>
                                <small class="text-muted">QR Codes Criados</small>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="p-3 border rounded bg-light profile-stat">
                                <h3 class="text-success mb-1">@monthlyQRCount</h3>
                                <small class="text-muted">Este Mês</small>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="p-3 border rounded bg-light profile-stat">
                                <h3 class="text-info mb-1">@Model.DailyQRCount</h3>
                                <small class="text-muted">Hoje</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Histórico Recente -->
            @if (qrHistory.Any())
            {
                <div class="card mb-4 border-0 shadow-sm">
                    <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">
                            <i class="fas fa-history me-2"></i>Histórico Recente
                        </h5>
                        <a href="/Account/History" class="btn btn-light btn-sm">
                            <i class="fas fa-list me-1"></i>Ver Todos
                        </a>
                    </div>
                    <div class="card-body">
                        <div class="list-group list-group-flush">
                            @foreach (var qr in qrHistory.Take(5))
                            {
                                <div class="list-group-item d-flex justify-content-between align-items-center px-0">
                                    <div>
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-qrcode text-primary me-2"></i>
                                            <div>
                                                <h6 class="mb-1">@qr.Type.ToUpper()</h6>
                                                <p class="mb-0 text-muted small">
                                                    @(qr.Content.Length > 50 ? qr.Content.Substring(0, 50) + "..." : qr.Content)
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                    <small class="text-muted">@qr.CreatedAt.ToString("dd/MM HH:mm")</small>
                                </div>
                            }
                        </div>
                    </div>
                </div>
            }

            <!-- Ações do Perfil -->
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-dark text-white">
                    <h5 class="mb-0">
                        <i class="fas fa-cogs me-2"></i>Ações
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        @if (!isPremium)
                        {
                            <div class="col-md-6">
                                <a href="/Pagamento/SelecaoPlano" class="btn btn-warning w-100">
                                    <i class="fas fa-crown me-2"></i>Upgrade para Premium
                                </a>
                            </div>
                        }
                        
                        <div class="col-md-6">
                            <a href="/Account/History" class="btn btn-info w-100">
                                <i class="fas fa-history me-2"></i>Ver Histórico Completo
                            </a>
                        </div>
                        
                        <div class="col-md-6">
                            <a href="/" class="btn btn-primary w-100">
                                <i class="fas fa-qrcode me-2"></i>Criar Novo QR Code
                            </a>
                        </div>
                        
                        <div class="col-md-6">
                            <form method="post" action="/Account/Logout" class="d-inline w-100">
                                <button type="submit" class="btn btn-outline-danger w-100">
                                    <i class="fas fa-sign-out-alt me-2"></i>Sair
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal de Solicitação de Reembolso (CDC - 7 dias) -->
<div class="modal fade" id="refundSubscriptionModal" tabindex="-1" aria-labelledby="refundSubscriptionModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="refundSubscriptionModalLabel">
                    <i class="fas fa-undo me-2"></i>Solicitar Reembolso Total (CDC)
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fechar"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <i class="fas fa-shield-alt me-2"></i>
                    <strong>Direito de Arrependimento (CDC):</strong> Você está dentro do período de 7 dias e tem direito a reembolso total conforme o Código de Defesa do Consumidor.
                </div>
                <h6><strong>O que acontecerá:</strong></h6>
                <ul>
                    <li><i class="fas fa-check text-success me-2"></i>Reembolso total do valor pago</li>
                    <li><i class="fas fa-check text-success me-2"></i>Assinatura cancelada imediatamente</li>
                    <li><i class="fas fa-check text-success me-2"></i>Acesso Premium removido</li>
                    <li><i class="fas fa-check text-success me-2"></i>Dinheiro devolvido em 5-10 dias úteis</li>
                </ul>
                <p class="mb-0"><strong>Deseja continuar com o reembolso?</strong></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-arrow-left me-1"></i>Cancelar
                </button>
                <button type="button" class="btn btn-danger" id="confirmRefundBtn">
                    <i class="fas fa-undo me-1"></i>Sim, Solicitar Reembolso
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Modal de Confirmação de Cancelamento -->
<div class="modal fade" id="cancelSubscriptionModal" tabindex="-1" aria-labelledby="cancelSubscriptionModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="cancelSubscriptionModalLabel">
                    <i class="fas fa-exclamation-triangle me-2"></i>Cancelar Assinatura Premium
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fechar"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="fas fa-info-circle me-2"></i>
                    <strong>Atenção:</strong> Você manterá acesso aos recursos Premium até o final do período já pago.
                </div>
                <p><strong>Ao cancelar, você perderá:</strong></p>
                <ul>
                    <li><i class="fas fa-times text-danger me-2"></i>QR Codes ilimitados</li>
                    <li><i class="fas fa-times text-danger me-2"></i>Experiência sem anúncios</li>
                    <li><i class="fas fa-times text-danger me-2"></i>QR Codes dinâmicos (editáveis)</li>
                    <li><i class="fas fa-times text-danger me-2"></i>Estatísticas avançadas</li>
                    <li><i class="fas fa-times text-danger me-2"></i>Suporte prioritário</li>
                </ul>
                <p class="mb-0"><strong>Tem certeza que deseja cancelar?</strong></p>
                <p class="text-muted small">Você pode reativar sua assinatura a qualquer momento.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-arrow-left me-1"></i>Manter Premium
                </button>
                <button type="button" class="btn btn-danger" id="confirmCancelBtn">
                    <i class="fas fa-times-circle me-1"></i>Sim, Cancelar Assinatura
                </button>
            </div>
        </div>
    </div>
</div>

<style>
    .card {
        transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
    }
    
    .card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(0,0,0,0.1) !important;
    }
    
    .badge {
        font-size: 0.85em;
        padding: 8px 12px;
        font-weight: 500;
    }
    
    .bg-light {
        background-color: #f8f9fa !important;
        border: 1px solid #e9ecef;
    }
    
    .list-group-item {
        border: none;
        border-bottom: 1px solid #dee2e6;
        padding: 15px 0;
        transition: background-color 0.2s ease;
    }
    
    .list-group-item:hover {
        background-color: rgba(0,123,255,0.05);
    }
    
    .list-group-item:last-child {
        border-bottom: none;
    }
    
    .profile-stat {
        transition: all 0.3s ease;
    }
    
    .profile-stat:hover {
        background-color: #e3f2fd !important;
        border-color: #2196f3 !important;
    }
    
    .btn {
        transition: all 0.2s ease;
    }
    
    .card-header {
        font-weight: 600;
        border-bottom: 2px solid rgba(255,255,255,0.2);
    }
    
    @@media (max-width: 768px) {
        .container {
            padding: 0 15px;
        }
        
        .col-md-6 {
            margin-bottom: 1rem;
        }
        
        .card-body .row .col-md-4 {
            margin-bottom: 1rem;
        }
    }
</style>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Handler para reembolso (CDC - 7 dias)
        const confirmRefundBtn = document.getElementById('confirmRefundBtn');
        const refundModal = document.getElementById('refundSubscriptionModal');

        if (confirmRefundBtn) {
            confirmRefundBtn.addEventListener('click', async function() {
                // Desabilita o botão durante o processamento
                confirmRefundBtn.disabled = true;
                confirmRefundBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Processando...';

                try {
                    const response = await fetch('/Premium/RequestRefund', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });

                    const result = await response.json();

                    if (result.success) {
                        // Fecha o modal
                        const modalInstance = bootstrap.Modal.getInstance(refundModal);
                        if (modalInstance) {
                            modalInstance.hide();
                        }

                        // Mostra mensagem de sucesso
                        alert('✅ ' + result.message);

                        // Recarrega a página após 2 segundos
                        setTimeout(() => {
                            window.location.reload();
                        }, 2000);
                    } else {
                        alert('❌ ' + result.error);
                        confirmRefundBtn.disabled = false;
                        confirmRefundBtn.innerHTML = '<i class="fas fa-undo me-1"></i>Sim, Solicitar Reembolso';
                    }
                } catch (error) {
                    console.error('Erro ao solicitar reembolso:', error);
                    alert('❌ Erro de conexão. Tente novamente mais tarde.');
                    confirmRefundBtn.disabled = false;
                    confirmRefundBtn.innerHTML = '<i class="fas fa-undo me-1"></i>Sim, Solicitar Reembolso';
                }
            });
        }

        // Handler para cancelamento (sem reembolso)
        const confirmCancelBtn = document.getElementById('confirmCancelBtn');
        const cancelModal = document.getElementById('cancelSubscriptionModal');

        if (confirmCancelBtn) {
            confirmCancelBtn.addEventListener('click', async function() {
                // Desabilita o botão durante o processamento
                confirmCancelBtn.disabled = true;
                confirmCancelBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Cancelando...';

                try {
                    const response = await fetch('/Premium/CancelSubscription', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });

                    const result = await response.json();

                    if (result.success) {
                        // Fecha o modal
                        const modalInstance = bootstrap.Modal.getInstance(cancelModal);
                        if (modalInstance) {
                            modalInstance.hide();
                        }

                        // Mostra mensagem de sucesso
                        alert('✅ Assinatura cancelada com sucesso!\n\nVocê manterá acesso Premium até o final do período pago.\n\nA página será recarregada.');

                        // Recarrega a página após 2 segundos
                        setTimeout(() => {
                            window.location.reload();
                        }, 2000);
                    } else {
                        alert('❌ Erro ao cancelar assinatura: ' + (result.error || 'Erro desconhecido'));
                        confirmCancelBtn.disabled = false;
                        confirmCancelBtn.innerHTML = '<i class="fas fa-times-circle me-1"></i>Sim, Cancelar Assinatura';
                    }
                } catch (error) {
                    console.error('Erro ao cancelar assinatura:', error);
                    alert('❌ Erro de conexão. Tente novamente mais tarde.');
                    confirmCancelBtn.disabled = false;
                    confirmCancelBtn.innerHTML = '<i class="fas fa-times-circle me-1"></i>Sim, Cancelar Assinatura';
                }
            });
        }
    });
</script>