@php
    $settingsSection = isset($settingsSection) && is_string($settingsSection) ? $settingsSection : null;
    /** @var \App\Models\UpdateSetting|null $updateSettings */
    $updateSettings = $updateSettings instanceof \App\Models\UpdateSetting ? $updateSettings : null;
    /** @var \Illuminate\Support\Collection<int, \App\Models\UpdateCheck> $updateChecks */
    $updateChecks = ($updateChecks ?? collect()) instanceof \Illuminate\Support\Collection ? $updateChecks : collect($updateChecks ?? []);

    $defaultFeedUrl = \App\Support\UpdateCenterManager::DEFAULT_FEED_URL;
    $feedUrl = old('feed_url', (string) ($updateSettings?->feed_url ?: $defaultFeedUrl));
    $currentVersion = old('current_version', (string) ($updateSettings?->current_version ?: config('app.version', '1.002')));
    $channel = old('channel', (string) ($updateSettings?->channel ?: 'stable'));
    $isActive = old('is_active', (bool) ($updateSettings?->is_active ?? true));
    $autoCheckEnabled = old('auto_check_enabled', (bool) ($updateSettings?->auto_check_enabled ?? true));
    $checkInterval = (int) old('check_interval_minutes', (int) ($updateSettings?->check_interval_minutes ?? 720));
    $requestTimeout = (int) old('request_timeout_seconds', (int) ($updateSettings?->request_timeout_seconds ?? 8));
    $verifyTls = old('verify_tls', (bool) ($updateSettings?->verify_tls ?? true));
    $metaValue = old('meta', $updateSettings?->meta ? json_encode($updateSettings->meta, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) : '');

    $channelOptions = [
        'stable' => __('Stable'),
        'beta' => __('Beta'),
        'nightly' => __('Nightly'),
    ];
@endphp

<section class="space-y-6">
    <header>
        <h2 class="inline-flex items-center gap-2 text-lg font-medium text-gray-900">
            <x-menu-icon name="fa-solid fa-arrows-rotate" class="h-5 w-5 text-gray-500" />
            {{ __('Updates') }}
        </h2>
        <p class="mt-1 text-sm text-gray-600">
            {{ __('Configure update source, run checks and monitor available versions.') }}
        </p>
    </header>

    <div class="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">
        <div class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2">
            <p class="text-xs uppercase tracking-wide text-slate-500">{{ __('Current version') }}</p>
            <p class="mt-1 text-sm font-semibold text-slate-900">{{ $updateSettings?->current_version ?: $currentVersion }}</p>
        </div>
        <div class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2">
            <p class="text-xs uppercase tracking-wide text-slate-500">{{ __('Last remote version') }}</p>
            <p class="mt-1 text-sm font-semibold text-slate-900">{{ $updateSettings?->last_remote_version ?: '—' }}</p>
        </div>
        <div class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2">
            <p class="text-xs uppercase tracking-wide text-slate-500">{{ __('Last check') }}</p>
            <p class="mt-1 text-sm font-semibold text-slate-900">{{ $updateSettings?->last_checked_at?->format('d.m.Y H:i') ?: '—' }}</p>
        </div>
        <div class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2">
            <p class="text-xs uppercase tracking-wide text-slate-500">{{ __('Status') }}</p>
            <p class="mt-1 text-sm font-semibold {{ ($updateSettings?->is_active ?? true) ? 'text-emerald-700' : 'text-slate-700' }}">
                {{ ($updateSettings?->is_active ?? true) ? __('Active') : __('Disabled') }}
            </p>
        </div>
    </div>

    @if (session('status') === 'updates-settings-updated')
        <p class="rounded-md border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-700">
            {{ __('Update settings have been saved.') }}
        </p>
    @endif

    @if (session('status') === 'updates-check-completed')
        <p class="rounded-md border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-700">
            {{ session('success', __('Update check has been completed.')) }}
        </p>
        @if (session('error'))
            <p class="mt-2 rounded-md border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-700">
                {{ session('error') }}
            </p>
        @endif
    @endif

    <form method="POST" action="{{ route('profile.updates.update') }}" class="space-y-4 rounded-lg border border-slate-200 bg-white p-4">
        @csrf
        @method('PATCH')
        @if ($settingsSection)
            <input type="hidden" name="_settings_section" value="{{ $settingsSection }}">
        @endif

        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div>
                <label for="updates-feed-url" class="block text-sm font-medium text-slate-700">{{ __('Update source URL') }}</label>
                <input id="updates-feed-url" name="feed_url" type="text" value="{{ $feedUrl }}" placeholder="{{ $defaultFeedUrl }}" class="mt-1 w-full rounded-md border-slate-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                <p class="mt-1 text-xs text-slate-500">{{ __('Default source: :url', ['url' => $defaultFeedUrl]) }}</p>
                <x-input-error class="mt-2" :messages="$errors->get('feed_url')" />
            </div>

            <div>
                <label for="updates-current-version" class="block text-sm font-medium text-slate-700">{{ __('Current version') }}</label>
                <input id="updates-current-version" name="current_version" type="text" value="{{ $currentVersion }}" class="mt-1 w-full rounded-md border-slate-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                <x-input-error class="mt-2" :messages="$errors->get('current_version')" />
            </div>
        </div>

        <div class="grid grid-cols-1 gap-4 md:grid-cols-3">
            <div>
                <label for="updates-channel" class="block text-sm font-medium text-slate-700">{{ __('Channel') }}</label>
                <select id="updates-channel" name="channel" class="mt-1 w-full rounded-md border-slate-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    @foreach ($channelOptions as $optionKey => $optionLabel)
                        <option value="{{ $optionKey }}" @selected($channel === $optionKey)>{{ $optionLabel }}</option>
                    @endforeach
                </select>
                <x-input-error class="mt-2" :messages="$errors->get('channel')" />
            </div>

            <div>
                <label for="updates-check-interval" class="block text-sm font-medium text-slate-700">{{ __('Check interval (minutes)') }}</label>
                <input id="updates-check-interval" name="check_interval_minutes" type="number" min="5" max="10080" value="{{ $checkInterval }}" class="mt-1 w-full rounded-md border-slate-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                <x-input-error class="mt-2" :messages="$errors->get('check_interval_minutes')" />
            </div>

            <div>
                <label for="updates-timeout" class="block text-sm font-medium text-slate-700">{{ __('Request timeout (seconds)') }}</label>
                <input id="updates-timeout" name="request_timeout_seconds" type="number" min="2" max="60" value="{{ $requestTimeout }}" class="mt-1 w-full rounded-md border-slate-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                <x-input-error class="mt-2" :messages="$errors->get('request_timeout_seconds')" />
            </div>
        </div>

        <div class="grid grid-cols-1 gap-2 md:grid-cols-3">
            <label class="inline-flex items-center gap-2 text-sm text-slate-700">
                <input type="checkbox" name="is_active" value="1" class="rounded border-slate-300 text-indigo-600 shadow-sm focus:ring-indigo-500" @checked($isActive)>
                {{ __('Enable update module') }}
            </label>
            <label class="inline-flex items-center gap-2 text-sm text-slate-700">
                <input type="checkbox" name="auto_check_enabled" value="1" class="rounded border-slate-300 text-indigo-600 shadow-sm focus:ring-indigo-500" @checked($autoCheckEnabled)>
                {{ __('Enable automatic checks') }}
            </label>
            <label class="inline-flex items-center gap-2 text-sm text-slate-700">
                <input type="checkbox" name="verify_tls" value="1" class="rounded border-slate-300 text-indigo-600 shadow-sm focus:ring-indigo-500" @checked($verifyTls)>
                {{ __('Verify TLS certificate') }}
            </label>
        </div>

        <div>
            <label for="updates-meta" class="block text-sm font-medium text-slate-700">{{ __('Meta JSON') }}</label>
            <textarea id="updates-meta" name="meta" rows="3" class="mt-1 w-full rounded-md border-slate-300 text-xs font-mono shadow-sm focus:border-indigo-500 focus:ring-indigo-500">{{ $metaValue }}</textarea>
            <x-input-error class="mt-2" :messages="$errors->get('meta')" />
        </div>

        <div class="flex justify-end">
            <button type="submit" class="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500">
                {{ __('Save update settings') }}
            </button>
        </div>
    </form>

    <form method="POST" action="{{ route('profile.updates.check') }}" class="inline-flex">
        @csrf
        @if ($settingsSection)
            <input type="hidden" name="_settings_section" value="{{ $settingsSection }}">
        @endif
        <button type="submit" class="inline-flex items-center rounded-md border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
            {{ __('Check updates now') }}
        </button>
    </form>

    <div class="space-y-3">
        <h3 class="text-sm font-semibold text-slate-900">{{ __('Update check history') }}</h3>

        @if ($updateChecks->isEmpty())
            <p class="rounded-md border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-600">{{ __('No update checks yet.') }}</p>
        @else
            <div class="overflow-hidden rounded-lg border border-slate-200">
                <table class="min-w-full divide-y divide-slate-200">
                    <thead class="bg-slate-50">
                        <tr>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Checked at') }}</th>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Status') }}</th>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Version') }}</th>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Source') }}</th>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Message') }}</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 bg-white">
                        @foreach ($updateChecks as $check)
                            <tr>
                                <td class="px-3 py-2 text-sm text-slate-700">{{ $check->checked_at?->format('d.m.Y H:i:s') ?: '—' }}</td>
                                <td class="px-3 py-2 text-sm">
                                    <span class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {{ $check->status === 'success' ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700' }}">
                                        {{ $check->status === 'success' ? __('Success') : __('Failed') }}
                                    </span>
                                    @if ($check->is_update_available)
                                        <span class="ml-2 inline-flex rounded-full bg-amber-100 px-2 py-0.5 text-xs font-semibold text-amber-700">{{ __('Update available') }}</span>
                                    @endif
                                </td>
                                <td class="px-3 py-2 text-sm text-slate-700">
                                    {{ $check->remote_version ?: '—' }}
                                    @if ($check->remote_build)
                                        <span class="text-xs text-slate-500">({{ $check->remote_build }})</span>
                                    @endif
                                </td>
                                <td class="px-3 py-2 text-xs text-slate-600">{{ $check->endpoint_url ?: '—' }}</td>
                                <td class="px-3 py-2 text-sm text-slate-700">{{ $check->error_message ?: '—' }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @endif
    </div>
</section>
