@extends('layouts.admin')
@section('content')
    <!-- Enhanced Header Section -->
    <div class="row mb-4">
        <div class="col-lg-8">
            <div class="d-flex align-items-center">
                <div class="mr-3">
                    <i class="fas fa-edit text-warning" style="font-size: 2rem;"></i>
                </div>
                <div>
                    <h2 class="mb-0 text-dark font-weight-bold">{{ trans('global.edit') }} Video</h2>
                    <p class="text-muted mb-0">Update video details</p>
                </div>
            </div>
        </div>
        <div class="col-lg-4 text-right">
            <a href="{{ route('admin.videos.index') }}" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left mr-2"></i>Back to Videos
            </a>
        </div>
    </div>

    <!-- Enhanced Card Design -->
    <div class="card shadow-sm border-0">
        <div class="card-header bg-white border-0">
            <div class="d-flex align-items-center">
                <i class="fas fa-video text-primary mr-2"></i>
                <h5 class="mb-0 font-weight-bold">Video Information</h5>
            </div>
        </div>

        <div class="card-body">
            <form method="POST" action="{{ route('admin.videos.update', [$video->id]) }}" enctype="multipart/form-data"
                class="needs-validation" novalidate id="videoForm">
                @method('PUT')
                @csrf
                <div class="row">
                    <!-- Title Input -->
                    <div class="col-6 mb-3">
                        <div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
                            <label for="title">Title (Optional)</label>
                            <input class="form-control {{ $errors->has('title') ? 'is-invalid' : '' }}" type="text"
                                name="title" id="title" value="{{ old('title', $video->title) }}"
                                placeholder="Enter video title (optional)">
                            @if ($errors->has('title'))
                                <span class="text-danger">{{ $errors->first('title') }}</span>
                            @endif
                        </div>
                    </div>
                    <div class="col-6 mb-3">
                        <div class="form-group {{ $errors->has('sort_order') ? 'has-error' : '' }}">
                            <label for="sort_order">Sort Order (Optional)</label>
                            <input class="form-control {{ $errors->has('sort_order') ? 'is-invalid' : '' }}" type="number"
                                name="sort_order" id="sort_order" value="{{ old('sort_order', $video->sort_order) }}"
                                placeholder="Enter a sort order value (e.g., 1, 2, 3)">
                            @if ($errors->has('sort_order'))
                                <span class="text-danger">{{ $errors->first('sort_order') }}</span>
                            @endif
                            <span class="help-block">Enter a sort order value (e.g., 1, 2, 3).</span>
                        </div>
                    </div>

                    <!-- Video Type Selection -->
                    <div class="col-12 mb-4">
                        <label class="required">Video Type</label>
                        <div class="btn-group btn-group-toggle d-flex" role="group">
                            <button type="button"
                                class="btn btn-outline-primary {{ old('video_type', $video->video_type) === 'link' ? 'active' : '' }} flex-fill video-type-btn"
                                data-type="link">
                                <i class="fas fa-link mr-2"></i>Video Link
                            </button>
                            <button type="button"
                                class="btn btn-outline-primary {{ old('video_type', $video->video_type) === 'upload' ? 'active' : '' }} flex-fill video-type-btn"
                                data-type="upload">
                                <i class="fas fa-upload mr-2"></i>Upload Video
                            </button>
                        </div>
                        <input type="hidden" name="video_type" id="video_type"
                            value="{{ old('video_type', $video->video_type) }}">
                    </div>

                    <!-- Video Link Input -->
                    <div class="col-12 mb-3" id="link_input_group"
                        style="display: {{ old('video_type', $video->video_type) === 'link' ? 'block' : 'none' }};">
                        <div class="form-group {{ $errors->has('url') ? 'has-error' : '' }}">
                            <label class="required" for="url">Video URL</label>
                            <div class="input-group">
                                <input class="form-control {{ $errors->has('url') ? 'is-invalid' : '' }}" type="text"
                                    name="url" id="url" value="{{ old('url', $video->url) }}"
                                    placeholder="https://www.youtube.com/watch?v=...">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button" id="previewLinkBtn">
                                        <i class="fas fa-eye mr-1"></i>Preview
                                    </button>
                                </div>
                            </div>
                            @if ($errors->has('url'))
                                <span class="text-danger">{{ $errors->first('url') }}</span>
                            @endif
                            <span class="help-block">
                                <i class="fas fa-info-circle mr-1"></i>
                                Enter embeddable YouTube or Vimeo URL. Example: https://www.youtube.com/watch?v=dQw4w9WgXcQ
                            </span>
                        </div>
                    </div>

                    <!-- Video Upload Input -->
                    <div class="col-12 mb-3" id="upload_input_group"
                        style="display: {{ old('video_type', $video->video_type) === 'upload' ? 'block' : 'none' }};">
                        <div class="form-group {{ $errors->has('video_file') ? 'has-error' : '' }}">
                            <label for="video_file">Upload New Video (Optional)</label>
                            <div class="custom-file">
                                <input type="file"
                                    class="custom-file-input {{ $errors->has('video_file') ? 'is-invalid' : '' }}"
                                    id="video_file" name="video_file" accept="video/mp4,video/x-m4v,video/*">
                                <label class="custom-file-label" for="video_file">Choose video file...</label>
                            </div>
                            @if ($errors->has('video_file'))
                                <span class="text-danger">{{ $errors->first('video_file') }}</span>
                            @endif
                            <span class="help-block">
                                <i class="fas fa-info-circle mr-1"></i>
                                Supported formats: MP4, MOV, AVI, WMV. Maximum file size: 100MB
                            </span>

                            @if ($video->video_path)
                                <div class="alert alert-info mt-2 mb-0">
                                    <i class="fas fa-info-circle mr-1"></i>
                                    <strong>Current file:</strong> {{ basename($video->video_path) }}
                                </div>
                            @endif
                        </div>
                    </div>

                    <!-- Video Preview Section -->
                    <div class="col-12 mb-3" id="videoPreviewSection">
                        <label class="d-block mb-2">
                            <i class="fas fa-eye mr-1"></i>Video Preview
                        </label>
                        <div class="card bg-light">
                            <div class="card-body p-3">
                                <div class="video-preview-container"
                                    style="position: relative; background: #000; padding-top: 56.25%; border-radius: 8px; overflow: hidden;">
                                    <div id="videoPreviewContent"
                                        style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;">
                                        @if ($video->video_type === 'upload')
                                            <video controls style="width: 100%; height: 100%; object-fit: contain;">
                                                <source src="{{ $video->embed_url }}" type="video/mp4">
                                                Your browser does not support the video tag.
                                            </video>
                                        @else
                                            <iframe src="{{ $video->embed_url }}"
                                                style="width: 100%; height: 100%; border: 0;"
                                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                                allowfullscreen>
                                            </iframe>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Form Actions -->
                <div class="form-group mt-4 pt-3 border-top">
                    <div class="d-flex justify-content-between flex-wrap">
                        <a href="{{ route('admin.videos.index') }}"
                            class="btn btn-outline-secondary btn-lg shadow-sm mb-2">
                            <i class="fas fa-times mr-2"></i>Cancel
                        </a>
                        <button class="btn btn-primary btn-lg shadow-sm mb-2" type="submit" id="submitBtn">
                            <span class="btn-text">
                                <i class="fas fa-save mr-2"></i>{{ trans('global.update') }}
                            </span>
                            <span class="btn-loading" style="display: none;">
                                <i class="fas fa-spinner fa-spin mr-2"></i>Updating...
                            </span>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
@endsection

@section('styles')
    <style>
        .video-type-btn {
            padding: 1rem;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .video-type-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .video-type-btn.active {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }

        .help-block {
            font-size: 0.875rem;
            color: #6c757d;
            margin-top: 0.25rem;
        }

        .video-preview-container {
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }

        #videoPreviewSection {
            animation: fadeIn 0.3s ease-in;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
@endsection

@section('scripts')
    @parent
    <script>
        $(document).ready(function() {
            let isSubmitting = false;

            // Video type toggle functionality
            $('.video-type-btn').click(function() {
                const videoType = $(this).data('type');

                // Update button states
                $('.video-type-btn').removeClass('active');
                $(this).addClass('active');

                // Update hidden input
                $('#video_type').val(videoType);

                // Toggle form sections
                if (videoType === 'link') {
                    $('#link_input_group').show();
                    $('#upload_input_group').hide();
                    $('#url').prop('required', true);
                    $('#video_file').prop('required', false);
                } else {
                    $('#link_input_group').hide();
                    $('#upload_input_group').show();
                    $('#url').prop('required', false);
                    $('#video_file').prop('required', false);
                }
            });

            // Preview link button
            $('#previewLinkBtn').click(function() {
                const url = $('#url').val().trim();
                if (!url) {
                    toastr.warning('Please enter a video URL first');
                    return;
                }

                const embedUrl = getEmbedUrl(url);
                if (embedUrl) {
                    updateVideoPreview(embedUrl, 'iframe');
                    toastr.success('Video preview updated');
                } else {
                    toastr.error('Invalid video URL. Please use YouTube or Vimeo links.');
                }
            });

            // File input change - show preview
            $('#video_file').on('change', function() {
                const file = this.files[0];
                if (file) {
                    const fileName = file.name;
                    $(this).next('.custom-file-label').html(fileName);

                    // Check file size (100MB = 104857600 bytes)
                    if (file.size > 104857600) {
                        toastr.error('File size exceeds 100MB limit');
                        this.value = '';
                        $(this).next('.custom-file-label').html('Choose video file...');
                        return;
                    }

                    // Show video preview
                    const videoUrl = URL.createObjectURL(file);
                    updateVideoPreview(videoUrl, 'video');
                    toastr.success('Video preview updated with new file');
                }
            });

            // Form submission
            $('#videoForm').on('submit', function(e) {
                if (isSubmitting) {
                    e.preventDefault();
                    return false;
                }

                const form = this;
                if (form.checkValidity() === false) {
                    e.preventDefault();
                    e.stopPropagation();
                    $(form).addClass('was-validated');
                    toastr.error('Please fill in all required fields');
                    return false;
                }

                isSubmitting = true;
                const $submitBtn = $('#submitBtn');
                $submitBtn.prop('disabled', true);
                $submitBtn.find('.btn-text').hide();
                $submitBtn.find('.btn-loading').show();
            });

            // Helper functions
            function getEmbedUrl(url) {
                // YouTube
                if (url.includes('youtube.com') || url.includes('youtu.be')) {
                    const videoId = extractYouTubeId(url);
                    if (videoId) {
                        return `https://www.youtube.com/embed/${videoId}`;
                    }
                }

                // Vimeo
                if (url.includes('vimeo.com')) {
                    const videoId = extractVimeoId(url);
                    if (videoId) {
                        return `https://player.vimeo.com/video/${videoId}`;
                    }
                }

                return null;
            }

            function extractYouTubeId(url) {
                const regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
                const match = url.match(regExp);
                return (match && match[7].length == 11) ? match[7] : null;
            }

            function extractVimeoId(url) {
                const regExp =
                    /vimeo\.com\/(?:channels\/(?:\w+\/)?|groups\/(?:[^\/]*)\/videos\/|album\/(?:\d+)\/video\/|video\/|)(\d+)(?:$|\/|\?)/;
                const match = url.match(regExp);
                return match ? match[1] : null;
            }

            function updateVideoPreview(url, type) {
                const $previewContent = $('#videoPreviewContent');
                $previewContent.empty();

                if (type === 'iframe') {
                    $previewContent.html(`
                    <iframe src="${url}" 
                        style="width: 100%; height: 100%; border: 0;"
                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                        allowfullscreen>
                    </iframe>
                `);
                } else {
                    $previewContent.html(`
                    <video controls style="width: 100%; height: 100%; object-fit: contain;">
                        <source src="${url}" type="video/mp4">
                        Your browser does not support the video tag.
                    </video>
                `);
                }

                // Smooth scroll to preview
                $('html, body').animate({
                    scrollTop: $('#videoPreviewSection').offset().top - 100
                }, 500);
            }
        });

        // Show success message if redirected back with success
        @if (session('message'))
            toastr.success('{{ session('message') }}');
        @endif
    </script>
@endsection
