@extends('layouts.admin.theme')
@section("title", env("APP_NAME") . " :: " . __("Novo Arquivo"))
@section('content')
    <form id="repositorio-form" action="{{ route('admin.repositorio.store') }}" method="post" enctype="multipart/form-data">
        <div class="container mt-5">
            <div class="row">
                <div class="col-12">
                    <div class="card shadow">
                        <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                            <h5 class="my-2">{{ __("Novo Arquivo para o Repositório") }}</h5>
                        </div>
                        <div class="card-body">
                            @csrf
                            @include("errors.messageFlash")

                            <div class="mb-3">
                                <input type="hidden" name="page" value="{{ request()->input('page', 1) }}">
                                <input type="hidden" name="name" value="">
                                <label for="title" class="form-label text-bold">{{ __("Título") }}: <span
                                        class="span-admin-create">*</span></label>
                                <input type="text" class="form-control @error('title') is-invalid @enderror" name="title"
                                    id="title" autocomplete="off" value="{{ old('title') }}">
                                @error('title')
                                    <small class="text-danger text-bold">{{ $message }}</small>
                                @enderror
                            </div>
                            <div class="mb-3 text-wrap">
                                <label for="summary" class="form-label text-bold">{{ __("Descrição sumária") }}:</label>
                                <textarea class="form-control @error('summary') is-invalid @enderror" name="summary"
                                    id="summary">{{ old('summary') }}</textarea>
                                @error('summary')
                                    <small class="text-danger text-bold">{{ $message }}</small>
                                @enderror
                            </div>
                            <div class="mb-3">
                                <label for="target" class="form-label text-bold">{{ __("Tipo de link") }} <span
                                        class="span-admin-create">*</span></label>
                                <select class="form-control @error('target') is-invalid @enderror" name="target"
                                    id="target">
                                    @foreach(App\Enums\StatusLinkEnum::cases() as $status)
                                        <option value="{{ $status->name }}">{{ $status->value }}</option>
                                    @endforeach
                                </select>
                                @error('target')
                                    <small class="text-danger text-bold">{{ $message }}</small>
                                @enderror
                            </div>
                            <div class="mb-3">
                                <label for="url" class="form-label text-bold">{{ __("Arquivo") }} <span
                                        class="span-admin-create">*</span></label>
                                <input type="file" class="form-control @error('url') is-invalid @enderror" name="url" id="url" />
                                @error('url')
                                    <small class="text-danger text-bold">{{ $message }}</small>
                                @enderror
                            </div>
                            <div class="mb-3">
                                <label for="status" class="form-label text-bold">{{ __("Status") }} <span
                                        class="span-admin-create">*</span></label>
                                <select class="form-control @error('status') is-invalid @enderror" name="status"
                                    id="status">
                                    @foreach(App\Enums\StatusEnum::cases() as $status)
                                        <option value="{{ $status->name }}">{{ $status->value }}</option>
                                    @endforeach
                                </select>
                                @error('status')
                                    <small class="text-danger text-bold">{{ $message }}</small>
                                @enderror
                            </div>
                            <div id="repositorio-upload-progress" class="mb-3" style="display: none;">
                                <p id="repositorio-upload-status" class="text-muted mb-1"></p>
                                <div class="progress">
                                    <div id="repositorio-upload-progress-bar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
                                </div>
                            </div>
                            @include('components.buttons._backAndSend', [
                                    'textBack' => __('Voltar'),
                                    'textSend' => __('Enviar'),
                                    'routeBack' => 'admin.repositorio.index'
                                ])
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    var form = document.getElementById('repositorio-form');
    if (!form) return;
    var progressWrap = document.getElementById('repositorio-upload-progress');
    var progressBar = document.getElementById('repositorio-upload-progress-bar');
    var statusEl = document.getElementById('repositorio-upload-status');
    var submitBtn = form.querySelector('button[type="submit"]');
    
    function showError(message) {
        statusEl.textContent = message;
        statusEl.className = 'text-danger mb-1';
        progressWrap.style.display = 'block';
    }

    form.addEventListener('submit', function(e) {
        e.preventDefault();
        if (submitBtn.disabled) return;

        var formData = new FormData(form);
        var xhr = new XMLHttpRequest();
        var action = form.getAttribute('action');

        submitBtn.disabled = true;
        progressWrap.style.display = 'block';
        statusEl.className = 'text-muted mb-1';
        statusEl.textContent = '{{ __("Enviando… Para vídeos grandes (até 500MB) pode levar vários minutos. Não feche a página.") }}';
        progressBar.style.width = '0%';
        progressBar.textContent = '0%';
        progressBar.setAttribute('aria-valuenow', 0);

        xhr.upload.addEventListener('progress', function(ev) {
            if (ev.lengthComputable) {
                var pct = Math.round((ev.loaded / ev.total) * 100);
                progressBar.style.width = pct + '%';
                progressBar.textContent = pct + '%';
                progressBar.setAttribute('aria-valuenow', pct);
            }
        });

        xhr.addEventListener('load', function() {
            if (xhr.status === 422) {
                try {
                    var data = JSON.parse(xhr.responseText);
                    if (data.errors) {
                        for (var field in data.errors) {
                            var input = form.querySelector('[name="' + field + '"]');
                            var msg = data.errors[field][0];
                            if (input) {
                                input.classList.add('is-invalid');
                                var errEl = input.parentNode.querySelector('.invalid-feedback') || document.createElement('small');
                                if (!errEl.classList.contains('invalid-feedback')) {
                                    errEl.className = 'text-danger text-bold invalid-feedback d-block';
                                    input.parentNode.appendChild(errEl);
                                }
                                errEl.textContent = msg;
                            }
                        }
                        showError(data.message || '{{ __("Verifique os campos do formulário.") }}');
                    } else if (data.message) {
                        showError(data.message);
                    }
                } catch (e) {
                    showError('{{ __("Verifique os campos do formulário.") }}');
                }
                submitBtn.disabled = false;
                return;
            }
            if (xhr.status === 200) {
                try {
                    var data = JSON.parse(xhr.responseText);
                    if (data.message) {
                        sessionStorage.setItem('success_message', data.message);
                    }
                    if (data.redirect) {
                        window.location.href = data.redirect;
                        return;
                    }
                } catch (e) {
                    // Se não for JSON, tenta usar responseURL
                    if (xhr.responseURL && xhr.responseURL !== window.location.href) {
                        window.location.href = xhr.responseURL;
                        return;
                    }
                }
                // Fallback: volta para a listagem
                window.location.href = '{{ route("admin.repositorio.index") }}';
                return;
            }
            progressWrap.style.display = 'none';
            submitBtn.disabled = false;
            if (xhr.status >= 400 || xhr.status === 302 || xhr.status === 303) {
                var errorMessage = '{{ __("Ocorreu um erro ao enviar o arquivo. Por favor, tente novamente.") }}';
                try {
                    var contentType = xhr.getResponseHeader('Content-Type');
                    if (contentType && contentType.indexOf('application/json') !== -1) {
                        var errorData = JSON.parse(xhr.responseText);
                        if (errorData.message) {
                            errorMessage = errorData.message;
                        }
                    }
                } catch (e) {
                    // Mantém mensagem padrão
                }
                showError(errorMessage);
            }
        });

        xhr.addEventListener('error', function() {
            progressWrap.style.display = 'block';
            statusEl.textContent = '{{ __("Erro de conexão. Verifique sua rede e tente novamente.") }}';
            submitBtn.disabled = false;
        });

        xhr.open('POST', action);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.setRequestHeader('Accept', 'application/json');
        xhr.send(formData);
    });
});
</script>
@endpush
@endsection
