@{
    ViewData["Title"] = "Adicionar Canal";
}

<div class="container mt-4">
    <h2>Adicionar Canal</h2>

    <div class="row mt-4">
        <div class="col-md-8">
            @if (TempData["Error"] != null)
            {
                <div class="alert alert-danger">
                    @TempData["Error"]
                </div>
            }

            <div class="card">
                <div class="card-header">
                    <ul class="nav nav-tabs card-header-tabs" id="channelAddTabs" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active" id="search-tab" data-toggle="tab" href="#search" role="tab" aria-controls="search" aria-selected="true">
                                Buscar Canal
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="id-tab" data-toggle="tab" href="#id" role="tab" aria-controls="id" aria-selected="false">
                                Inserir ID do Canal
                            </a>
                        </li>
                    </ul>
                </div>
                <div class="card-body">
                    <div class="tab-content" id="channelAddTabsContent">
                        <div class="tab-pane fade show active" id="search" role="tabpanel" aria-labelledby="search-tab">
                            <div class="form-group">
                                <label for="channelSearch">Buscar Canal</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="channelSearch" placeholder="Digite o nome do canal..." minlength="3">
                                    <div class="input-group-append">
                                        <button class="btn btn-primary" type="button" id="searchButton">
                                            <i class="bi bi-search"></i> Buscar
                                        </button>
                                    </div>
                                </div>
                                <small class="form-text text-muted">Insira pelo menos 3 caracteres para buscar.</small>
                            </div>

                            <div id="searchResults" class="mt-4"></div>
                        </div>
                        <div class="tab-pane fade" id="id" role="tabpanel" aria-labelledby="id-tab">
                            <form asp-action="Add" method="post">
                                <div class="form-group">
                                    <label for="channelId">ID do Canal</label>
                                    <input type="text" class="form-control" id="channelId" name="channelId" required
                                           placeholder="Ex: UCkw4JCwteGrDHIsyIIKo4tQ">
                                    <small class="form-text text-muted">
                                        O ID do canal pode ser encontrado na URL do canal, ex: youtube.com/channel/<strong>UCkw4JCwteGrDHIsyIIKo4tQ</strong>
                                    </small>
                                </div>
                                <button type="submit" class="btn btn-primary">Adicionar Canal</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <div class="mt-3">
                <a href="@Url.Action("Index", "Channels")" class="btn btn-link">
                    <i class="bi bi-arrow-left"></i> Voltar para Meus Canais
                </a>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card bg-light">
                <div class="card-body">
                    <h5 class="card-title">Dica</h5>
                    <p class="card-text">
                        Adicione os canais do YouTube que você gerencia ou tem permissão para acessar.
                        Depois de adicionar os canais, você poderá ver os vídeos deles na seção "Vídeos".
                    </p>
                    <h6 class="mt-3">Como encontrar o ID do canal?</h6>
                    <ol class="small pl-3">
                        <li>Visite o canal no YouTube</li>
                        <li>Observe a URL: <code>youtube.com/channel/ID-DO-CANAL</code></li>
                        <li>Copie o ID que aparece após "/channel/"</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script type="text/javascript">
        $(function() {
            $('#searchButton').click(function() {
                searchChannels();
            });

            $('#channelSearch').keypress(function(e) {
                if (e.which === 13) {
                    e.preventDefault();
                    searchChannels();
                }
            });

            function searchChannels() {
                var query = $('#channelSearch').val().trim();

                if (query.length < 3) {
                    alert('Por favor, insira pelo menos 3 caracteres para buscar.');
                    return;
                }

                $('#searchResults').html('<div class="text-center"><div class="spinner-border text-primary" role="status"></div><p class="mt-2">Buscando canais...</p></div>');

                $.ajax({
                    url: '@Url.Action("Search", "Channels")',
                    type: 'GET',
                    data: { query: query },
                    success: function(response) {
                        if (response.success) {
                            displaySearchResults(response.data);
                        } else {
                            $('#searchResults').html('<div class="alert alert-danger">' + response.message + '</div>');
                        }
                    },
                    error: function() {
                        $('#searchResults').html('<div class="alert alert-danger">Erro ao buscar canais. Tente novamente.</div>');
                    }
                });
            }

            function displaySearchResults(channels) {
                if (!channels || channels.length === 0) {
                    $('#searchResults').html('<div class="alert alert-info">Nenhum canal encontrado com este termo.</div>');
                    return;
                }

                var html = '<h5>Resultados da busca</h5><div class="list-group">';

                channels.forEach(function(channel) {
                    html += '<div class="list-group-item list-group-item-action">' +
                        '<div class="d-flex w-100">' +
                        '<div class="mr-3"><img src="' + channel.thumbnailUrl + '" alt="' + channel.title + '" width="50" class="rounded"></div>' +
                        '<div>' +
                        '<h6 class="mb-1">' + channel.title + '</h6>' +
                        '<p class="mb-1 small text-muted">' + (channel.description ? (channel.description.substring(0, 100) + '...') : '') + '</p>' +
                        '<form action="@Url.Action("Add", "Channels")" method="post">' +
                        '<input type="hidden" name="channelId" value="' + channel.id + '">' +
                        '<div class="d-flex justify-content-between align-items-center mt-2">' +
                        '<small class="text-muted">ID: ' + channel.id + '</small><br/>' +
                        '<button type="submit" class="btn btn-sm btn-primary">Adicionar</button>' +
                        '</div>' +
                        '</form>' +
                        '</div>' +
                        '</div>' +
                        '</div>';
                });

                html += '</div>';
                $('#searchResults').html(html);
            }
        });
    </script>
}