<x-layouts.dashboard title="GTS API Manager">
    @php
        $statMeta = [
            'Providers' => ['settings', 'blue', 'Connected API accounts'],
            'Active Providers' => ['pulse', 'green', 'Ready for automation'],
            'Imported Services' => ['services', 'blue', 'Synced provider services'],
            'Auto Submit Services' => ['tasks', 'green', 'Can place orders automatically'],
            'Provider Orders' => ['seller', 'blue', 'Orders linked to providers'],
            'API Queue' => ['revision', 'orange', 'Needs sync or delivery check'],
        ];
    @endphp

    <section class="gts-admin-hero card api-manager-hero">
        <div>
            <p class="eyebrow">GTS Automation</p>
            <h2>API Manager</h2>
            <p>Manage SMM provider connections, sync imported services with commission, monitor balances, and check provider-backed orders from one clean desk.</p>
        </div>
        <div class="gts-trust-points">
            <a class="btn small" href="{{ route('gts-admin.gts-providers.create') }}">Add Provider</a>
            <a class="ghost small" href="{{ route('gts-admin.gts-services.index') }}">Manage Services</a>
            <a class="ghost small" href="{{ route('gts-admin.gts-orders.index') }}">Sync Orders</a>
        </div>
    </section>

    <div class="stats saas-stats api-manager-stats">
        @foreach ($stats as $label => $value)
            @php([$icon, $tone, $detail] = $statMeta[$label])
            <article class="stat saas-stat">
                <span class="stat-top"><i class="stat-icon {{ $tone }}"><x-sidebar-icon :name="$icon"/></i><em><x-sidebar-icon name="more"/></em></span>
                <small>{{ $label }}</small>
                <strong>{{ number_format($value) }}</strong>
                <span class="stat-growth">{{ $detail }}</span>
            </article>
        @endforeach
    </div>

    <section class="table-card api-provider-board">
        <header class="table-head">
            <div>
                <h3>Provider Connections</h3>
                <p>Sync services, apply commission, refresh balance, and review connection status.</p>
            </div>
            <a class="ghost small" href="{{ route('gts-admin.gts-providers.index') }}">Provider CRUD</a>
        </header>
        <div class="api-provider-grid">
            @forelse ($providers as $provider)
                <article class="api-provider-card">
                    <div class="api-provider-top">
                        <span class="stat-icon blue"><x-sidebar-icon name="settings"/></span>
                        <div>
                            <h4>{{ $provider->name }}</h4>
                            <p>{{ parse_url($provider->api_url, PHP_URL_HOST) ?: $provider->api_url }}</p>
                        </div>
                        <span class="badge status-{{ str($provider->status)->slug() }}">{{ str($provider->status)->headline() }}</span>
                    </div>
                    <dl>
                        <div><dt>Balance</dt><dd>{{ number_format((float) $provider->balance, 2) }}</dd></div>
                        <div><dt>Services</dt><dd>{{ number_format($provider->services_count) }}</dd></div>
                        <div><dt>Active</dt><dd>{{ number_format($provider->active_services_count) }}</dd></div>
                        <div><dt>Last Sync</dt><dd>{{ $provider->last_synced_at?->diffForHumans() ?? 'Never' }}</dd></div>
                    </dl>
                    <form class="provider-sync-form api-sync-form" method="post" action="{{ route('gts-admin.gts-providers.sync', $provider) }}">
                        @csrf
                        <label>
                            Commission %
                            <input name="profit_percent" type="number" min="0" max="1000" step="0.01" value="30">
                        </label>
                        <button class="btn small">Sync All</button>
                        <a class="ghost small" href="{{ route('gts-admin.api-manager', ['provider_id' => $provider->id]) }}">Live Select</a>
                        <a class="ghost small" href="{{ route('gts-admin.gts-providers.edit', $provider) }}">Edit</a>
                    </form>
                </article>
            @empty
                <div class="empty-state">No API providers yet. Add your first SMM provider to start service sync.</div>
            @endforelse
        </div>
    </section>

    <section class="table-card api-live-sync">
        <header class="table-head">
            <div>
                <h3>Live Provider Services</h3>
                <p>Load provider services first, select what you want to sell, then import with bulk or separate commission.</p>
            </div>
            <form class="api-live-provider-form" method="get" action="{{ route('gts-admin.api-manager') }}">
                <select name="provider_id" required>
                    <option value="">Choose provider</option>
                    @foreach ($providers as $provider)
                        <option value="{{ $provider->id }}" @selected($selectedProvider?->id === $provider->id)>{{ $provider->name }}</option>
                    @endforeach
                </select>
                <button class="btn small">Load Live Services</button>
            </form>
        </header>

        @if ($selectedProvider)
            <div class="api-live-summary">
                <article><small>Selected Provider</small><strong>{{ $selectedProvider->name }}</strong><span>{{ parse_url($selectedProvider->api_url, PHP_URL_HOST) ?: $selectedProvider->api_url }}</span></article>
                <article><small>Live Services</small><strong>{{ number_format(count($liveServices['services'] ?? [])) }}</strong><span>Fetched from provider API</span></article>
                <article><small>Already Imported</small><strong>{{ number_format(count($importedServiceIds ?? [])) }}</strong><span>Matched by provider service ID</span></article>
            </div>

            @if ($liveServices['error'] ?? null)
                <div class="empty-state error-state">Provider API error: {{ $liveServices['error'] }}</div>
            @elseif (count($liveServices['services'] ?? []) > 0)
                <form method="post" action="{{ route('gts-admin.gts-providers.import-services', $selectedProvider) }}" class="api-import-form">
                    @csrf
                    <div class="api-import-toolbar">
                        <label>
                            Bulk Commission %
                            <input name="bulk_profit_percent" type="number" min="0" max="1000" step="0.01" value="{{ old('bulk_profit_percent', 30) }}">
                        </label>
                        <span class="muted">Separate commission fields are optional. Empty rows use the bulk commission.</span>
                        <button class="ghost small" type="button" onclick="toggleApiServiceSelection(true)">Select All</button>
                        <button class="ghost small" type="button" onclick="toggleApiServiceSelection(false)">Clear</button>
                        <button class="btn small">Import Selected</button>
                    </div>

                    <div class="api-live-table-wrap">
                        <table class="api-live-table">
                            <thead>
                                <tr>
                                    <th>Select</th>
                                    <th>Provider Service</th>
                                    <th>Category</th>
                                    <th>Rate</th>
                                    <th>Min / Max</th>
                                    <th>Flags</th>
                                    <th>Separate Commission</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($liveServices['services'] as $remote)
                                    @php
                                        $remoteId = (string) data_get($remote, 'service');
                                        $imported = in_array($remoteId, $importedServiceIds ?? [], true);
                                        $remoteRate = (float) data_get($remote, 'rate', 0);
                                    @endphp
                                    <tr>
                                        <td>
                                            <label class="api-check">
                                                <input class="api-service-checkbox" type="checkbox" name="service_ids[]" value="{{ $remoteId }}" @checked(! $imported)>
                                                <span>{{ $imported ? 'Update' : 'Add' }}</span>
                                            </label>
                                        </td>
                                        <td>
                                            <strong>{{ data_get($remote, 'name', 'Provider Service '.$remoteId) }}</strong>
                                            <small>#{{ $remoteId }} {{ data_get($remote, 'type') ? ' / '.data_get($remote, 'type') : '' }}</small>
                                        </td>
                                        <td>{{ data_get($remote, 'category', 'Imported') }}</td>
                                        <td><strong>{{ number_format($remoteRate, 4) }}</strong><small>provider / 1K</small></td>
                                        <td>{{ number_format((int) data_get($remote, 'min', 1)) }} / {{ number_format((int) data_get($remote, 'max', 10000)) }}</td>
                                        <td>
                                            <span class="badge status-{{ data_get($remote, 'refill') ? 'active' : 'inactive' }}">Refill {{ data_get($remote, 'refill') ? 'Yes' : 'No' }}</span>
                                            <span class="badge status-{{ data_get($remote, 'dripfeed') ? 'active' : 'inactive' }}">Drip {{ data_get($remote, 'dripfeed') ? 'Yes' : 'No' }}</span>
                                            @if ($imported)<span class="badge status-approved">Imported</span>@endif
                                        </td>
                                        <td>
                                            <input name="profit_percent_by_service[{{ $remoteId }}]" type="number" min="0" max="1000" step="0.01" placeholder="Use bulk">
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </form>
            @else
                <div class="empty-state">No live services returned by this provider.</div>
            @endif
        @else
            <div class="empty-state">Choose a provider to load live services before importing selected selling points.</div>
        @endif
    </section>

    <div class="grid two api-manager-grid">
        <section class="table-card">
            <header class="table-head">
                <div>
                    <h3>Imported Services</h3>
                    <p>Latest services synced from active providers.</p>
                </div>
                <a class="ghost small" href="{{ route('gts-admin.gts-services.index') }}">View All</a>
            </header>
            <table>
                <thead><tr><th>Service</th><th>Provider</th><th>Rate</th><th>Auto</th><th>Status</th></tr></thead>
                <tbody>
                    @forelse ($services as $service)
                        <tr>
                            <td><strong>{{ $service->name }}</strong><small>{{ $service->category }} / #{{ $service->provider_service_id ?: 'manual' }}</small></td>
                            <td>{{ $service->provider?->name ?? 'Manual' }}</td>
                            <td>{{ number_format((float) $service->rate_per_1000, 4) }}</td>
                            <td><span class="badge status-{{ $service->auto_submit ? 'active' : 'inactive' }}">{{ $service->auto_submit ? 'On' : 'Off' }}</span></td>
                            <td><span class="badge status-{{ str($service->status)->slug() }}">{{ str($service->status)->headline() }}</span></td>
                        </tr>
                    @empty
                        <tr><td colspan="5">No imported services yet. Sync a provider to fill this table.</td></tr>
                    @endforelse
                </tbody>
            </table>
        </section>

        <section class="table-card">
            <header class="table-head">
                <div>
                    <h3>Provider Order Sync</h3>
                    <p>Recent orders connected with provider order IDs.</p>
                </div>
                <a class="ghost small" href="{{ route('gts-admin.gts-orders.index') }}">View All</a>
            </header>
            <table>
                <thead><tr><th>Order</th><th>Client</th><th>Provider</th><th>Status</th><th>Action</th></tr></thead>
                <tbody>
                    @forelse ($orders as $order)
                        <tr>
                            <td><strong>{{ $order->order_number }}</strong><small>{{ $order->provider_order_id ?: 'Not submitted' }}</small></td>
                            <td>{{ $order->user?->name ?? 'GTS Client' }}</td>
                            <td>{{ $order->service?->provider?->name ?? '-' }}</td>
                            <td><span class="badge status-{{ str($order->status)->slug() }}">{{ str($order->status)->headline() }}</span></td>
                            <td>
                                @if ($order->provider_order_id)
                                    <form method="post" action="{{ route('gts-admin.gts-orders.sync', $order) }}">@csrf<button class="ghost small">Sync</button></form>
                                @else
                                    <span class="muted">Queued</span>
                                @endif
                            </td>
                        </tr>
                    @empty
                        <tr><td colspan="5">No provider orders yet.</td></tr>
                    @endforelse
                </tbody>
            </table>
        </section>
    </div>

    <script>
        function toggleApiServiceSelection(checked) {
            document.querySelectorAll('.api-service-checkbox').forEach(function (input) {
                input.checked = checked;
            });
        }
    </script>
</x-layouts.dashboard>
