@using Postall.Models
@model PostViewModel
@{
    ViewData["Title"] = "Gerenciar Postagens";
}

<div class="container-fluid">
    <div class="row">
        <!-- Menu lateral em desktop / Menu superior em mobile -->
        <div class="col-md-3 col-12 mb-3">
            <div class="card">
                <div class="card-header">
                    <h5>Plataformas</h5>
                </div>
                <div class="card-body">
                    <div class="d-flex flex-wrap gap-2">
                        <button type="button" class="btn btn-outline-primary platform-btn" data-platform="facebook">
                            Facebook
                        </button>
                        <button type="button" class="btn btn-outline-primary platform-btn" data-platform="instagram">
                            Instagram
                        </button>
                        <button type="button" class="btn btn-outline-primary platform-btn" data-platform="twitter">
                            Twitter/X
                        </button>
                        <button type="button" class="btn btn-outline-primary platform-btn" data-platform="whatsapp">
                            WhatsApp
                        </button>
                        <button type="button" class="btn btn-outline-primary platform-btn" data-platform="telegram">
                            Telegram
                        </button>
                    </div>
                </div>
            </div>

            <div class="card mt-3">
                <div class="card-header">
                    <h5>Agendamento</h5>
                </div>
                <div class="card-body">
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="radio" name="schedule" id="manual" checked>
                        <label class="form-check-label" for="manual">Manual</label>
                    </div>
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="radio" name="schedule" id="weekly">
                        <label class="form-check-label" for="weekly">Semanal</label>
                    </div>
                    <div id="weeklyOptions" class="d-none">
                        <div class="mb-2">
                            <div class="form-check">
                                <input class="form-check-input weekday-check" type="checkbox" value="1" id="monday">
                                <label class="form-check-label" for="monday">Segunda-feira</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input weekday-check" type="checkbox" value="2" id="tuesday">
                                <label class="form-check-label" for="tuesday">Terça-feira</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input weekday-check" type="checkbox" value="3" id="wednesday">
                                <label class="form-check-label" for="wednesday">Quarta-feira</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input weekday-check" type="checkbox" value="4" id="thursday">
                                <label class="form-check-label" for="thursday">Quinta-feira</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input weekday-check" type="checkbox" value="5" id="friday">
                                <label class="form-check-label" for="friday">Sexta-feira</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input weekday-check" type="checkbox" value="6" id="saturday">
                                <label class="form-check-label" for="saturday">Sábado</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input weekday-check" type="checkbox" value="0" id="sunday">
                                <label class="form-check-label" for="sunday">Domingo</label>
                            </div>
                        </div>
                        <input type="time" class="form-control" id="scheduleTime">
                    </div>
                </div>
            </div>
        </div>

        <!-- Preview lateral -->
        <div class="col-md-6 col-12">
            <div class="card">
                <div class="card-header">
                    <h5>Video</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Canal</label>
                        <input type="text" class="form-control" id="previewChannel" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">URL do Vídeo</label>
                        <input type="text" class="form-control" id="previewVideoUrl">
                    </div>
                    <div class="preview-content">
                        <h6>Título</h6>
                        <p id="previewTitle"></p>
                        <h6>Conteúdo</h6>
                        <p id="previewContent"></p>
                        <div id="previewImage" class="mt-2"></div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="button" class="btn btn-secondary me-2" onclick="savePlatformDraft()">Gerar com IA</button>
                </div>
            </div>
             <div class="card">
                <div class="card-header">
                    <h5>Nova Postagem</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="postTitle" class="form-label">Título</label>
                        <input type="text" class="form-control" id="postTitle">
                    </div>
                    <div class="mb-3">
                        <label for="postContent" class="form-label">Conteúdo</label>
                        <textarea class="form-control" id="postContent" rows="5"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="postImage" class="form-label">Imagem</label>
                        <input type="file" class="form-control" id="postImage" accept="image/*">
                    </div>
                    <div class="preview-image mb-3 d-none">
                        <img id="imagePreview" src="#" alt="Preview" class="img-fluid">
                    </div>
                </div>
                <div class="card-footer">
                    <button type="button" class="btn btn-secondary me-2" onclick="saveDraft()">Salvar Rascunho</button>
                    <button type="button" class="btn btn-primary" onclick="publishPost()">Publicar</button>
                </div>
            </div>
        </div>

    </div>
</div>

@section Scripts {
    <script>
        let selectedPlatform = null;
        
        // Gestão das plataformas
        document.querySelectorAll('.platform-btn').forEach(btn => {
            btn.addEventListener('click', async function() {
                const platform = this.dataset.platform;
                
                // Reset outros botões
                document.querySelectorAll('.platform-btn').forEach(b => 
                    b.classList.replace('btn-primary', 'btn-outline-primary'));
                
                // Ativar botão selecionado
                this.classList.replace('btn-outline-primary', 'btn-primary');
                selectedPlatform = platform;
                
                // Carregar dados da plataforma
                await loadPlatformData(platform);
            });
        });

        async function loadPlatformData(platform) {
            try {
                const response = await fetch(`/api/socialMedia/platformData/${platform}`);
                const data = await response.json();
                
                // Atualizar preview
                document.getElementById('previewChannel').value = data.channel;
                document.getElementById('previewVideoUrl').value = data.videoUrl;
                document.getElementById('previewTitle').textContent = data.title;
                document.getElementById('previewContent').textContent = data.content;
                
                if (data.imageUrl) {
                    document.getElementById('previewImage').innerHTML = 
                        `<img src="${data.imageUrl}" class="img-fluid" alt="Preview">`;
                }
            } catch (error) {
                console.error('Erro ao carregar dados da plataforma:', error);
            }
        }

        // Mostrar/ocultar opções de agendamento semanal
        document.getElementById('weekly').addEventListener('change', function() {
            document.getElementById('weeklyOptions').classList.remove('d-none');
        });

        document.getElementById('manual').addEventListener('change', function() {
            document.getElementById('weeklyOptions').classList.add('d-none');
        });

        // Preview da imagem
        document.getElementById('postImage').addEventListener('change', function(e) {
            if (e.target.files && e.target.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('imagePreview').src = e.target.result;
                    document.querySelector('.preview-image').classList.remove('d-none');
                };
                reader.readAsDataURL(e.target.files[0]);
            }
        });

        function getSelectedPlatform() {
            return selectedPlatform;
        }

        function getSelectedWeekDays() {
            return Array.from(document.querySelectorAll('.weekday-check:checked'))
                .map(checkbox => parseInt(checkbox.value));
        }

        async function generateAIContent() {
            if (!selectedPlatform) {
                alert('Selecione uma plataforma primeiro!');
                return;
            }

            try {
                const response = await fetch('/api/socialMedia/generateContent', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        platform: selectedPlatform,
                        videoUrl: document.getElementById('previewVideoUrl').value
                    })
                });

                const data = await response.json();
                if (data.success) {
                    document.getElementById('previewTitle').textContent = data.title;
                    document.getElementById('previewContent').textContent = data.content;
                } else {
                    alert('Erro ao gerar conteúdo: ' + data.message);
                }
            } catch (error) {
                console.error('Erro ao gerar conteúdo:', error);
                alert('Erro ao gerar conteúdo');
            }
        }

        async function savePlatformDraft() {
            if (!selectedPlatform) {
                alert('Selecione uma plataforma primeiro!');
                return;
            }

            const data = {
                platform: selectedPlatform,
                title: document.getElementById('previewTitle').textContent,
                content: document.getElementById('previewContent').textContent,
                videoUrl: document.getElementById('previewVideoUrl').value
            };

            try {
                const response = await fetch('/api/socialMedia/savePlatformDraft', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();
                if (result.success) {
                    alert('Rascunho salvo com sucesso!');
                } else {
                    alert('Erro ao salvar rascunho: ' + result.message);
                }
            } catch (error) {
                console.error('Erro ao salvar rascunho:', error);
                alert('Erro ao salvar rascunho');
            }
        }

        function publishPost() {
            const isWeekly = document.getElementById('weekly').checked;
            const data = {
                title: document.getElementById('postTitle').value,
                content: document.getElementById('postContent').value,
                platform: getSelectedPlatform()
            };

            if (isWeekly) {
                data.isManual = false;
                data.weekDays = getSelectedWeekDays();
                data.time = document.getElementById('scheduleTime').value;
                
                $.ajax({
                    url: '@Url.Action("SchedulePost", "SocialMedia")',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(data),
                    success: function(response) {
                        if (response.success) {
                            alert('Post agendado com sucesso!');
                        } else {
                            alert('Erro ao agendar post: ' + response.message);
                        }
                    }
                });
            } else {
                $.ajax({
                    url: '@Url.Action("PublishPost", "SocialMedia")',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(data),
                    success: function(response) {
                        if (response.success) {
                            alert('Post publicado com sucesso!');
                        } else {
                            alert('Erro ao publicar post: ' + response.message);
                        }
                    }
                });
            }
        }
    </script>
}

<style>
    .platform-btn {
        min-width: 120px;
        margin-bottom: 8px;
    }

    .preview-image img {
        max-height: 300px;
        object-fit: contain;
    }

    @@media (max-width: 768px) {
        .container-fluid {
            padding: 10px;
        }
    }

    .card {
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }
</style>