@php
    $statusBadgeStyles = [
        'new' => 'bg-slate-100 text-slate-700',
        'ringing' => 'bg-amber-100 text-amber-700',
        'in_progress' => 'bg-sky-100 text-sky-700',
        'completed' => 'bg-emerald-100 text-emerald-700',
        'missed' => 'bg-rose-100 text-rose-700',
        'failed' => 'bg-gray-200 text-gray-700',
    ];
@endphp

<x-app-layout>
    <x-slot name="header">
        <div class="flex flex-wrap items-center justify-between gap-3">
            <div>
                <h2 class="font-semibold text-xl text-gray-800 leading-tight">{{ __('Telephony') }}</h2>
                <p class="text-sm text-gray-500">{{ __('Connect a provider, receive calls, and store call logs.') }}</p>
            </div>
            <div class="flex items-center gap-2">
                @include('partials.section-access-controls', [
                    'sectionAccessEntity' => 'telephony',
                    'sectionAccessTitle' => __('Telephony'),
                    'canManageSectionAccess' => $canManageSectionAccess ?? false,
                    'sectionAccessUsers' => $sectionAccessUsers ?? collect(),
                ])
            </div>
        </div>
    </x-slot>

    <div class="pb-12">
        <div class="w-full px-6 space-y-4">
            <section class="bg-white border border-gray-200 rounded-xl p-4 space-y-4">
                <div class="flex flex-wrap items-start justify-between gap-3">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-900">{{ __('Telephony settings') }}</h3>
                        <p class="text-sm text-gray-500">{{ __('Store provider credentials and webhook for call imports.') }}</p>
                    </div>
                    <span class="inline-flex items-center rounded-full px-2.5 py-1 text-xs font-medium {{ ($settings->is_active ?? false) ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-600' }}">
                        {{ ($settings->is_active ?? false) ? __('Active') : __('Disabled') }}
                    </span>
                </div>

                <div class="rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs text-slate-600">
                    <div class="flex flex-col gap-1">
                        <span class="font-semibold text-slate-700">{{ __('Webhook URL') }}</span>
                        <code class="rounded bg-white px-2 py-1 text-slate-800 break-all">{{ $webhookUrl }}</code>
                        <span>{{ __('Send header') }} <code class="rounded bg-white px-1 py-0.5">X-CRM-Webhook-Secret</code></span>
                    </div>
                </div>

                @if ($canManageSettings)
                    <form method="POST" action="{{ route('telephony.settings.update') }}" class="grid grid-cols-1 gap-4">
                        @csrf
                        @method('PATCH')

                        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">{{ __('Provider') }}</label>
                                <input name="provider" type="text" value="{{ old('provider', $settings->provider) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="SIP / Asterisk / Twilio">
                                <x-input-error class="mt-1" :messages="$errors->get('provider')" />
                            </div>

                            <div class="flex items-end">
                                <label class="inline-flex items-center gap-2 text-sm text-gray-700">
                                    <input type="checkbox" name="is_active" value="1" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500" @checked(old('is_active', $settings->is_active))>
                                    {{ __('Active integration') }}
                                </label>
                                <x-input-error class="mt-1" :messages="$errors->get('is_active')" />
                            </div>
                        </div>

                        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">{{ __('API base URL') }}</label>
                                <input name="api_base_url" type="text" value="{{ old('api_base_url', $settings->api_base_url) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="https://api.provider.com">
                                <x-input-error class="mt-1" :messages="$errors->get('api_base_url')" />
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">{{ __('Account ID') }}</label>
                                <input name="account_id" type="text" value="{{ old('account_id', $settings->account_id) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="ACXXXXXX">
                                <x-input-error class="mt-1" :messages="$errors->get('account_id')" />
                            </div>
                        </div>

                        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">{{ __('API key') }}</label>
                                <input name="api_key" type="text" value="{{ old('api_key', $settings->api_key) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <x-input-error class="mt-1" :messages="$errors->get('api_key')" />
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">{{ __('API secret') }}</label>
                                <input name="api_secret" type="text" value="{{ old('api_secret', $settings->api_secret) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <x-input-error class="mt-1" :messages="$errors->get('api_secret')" />
                            </div>
                        </div>

                        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">{{ __('Inbound number') }}</label>
                                <input name="inbound_number" type="text" value="{{ old('inbound_number', $settings->inbound_number) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="+1 (555) 000-0000">
                                <x-input-error class="mt-1" :messages="$errors->get('inbound_number')" />
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">{{ __('Outbound number') }}</label>
                                <input name="outbound_number" type="text" value="{{ old('outbound_number', $settings->outbound_number) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="+1 (555) 000-0000">
                                <x-input-error class="mt-1" :messages="$errors->get('outbound_number')" />
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700">{{ __('Webhook secret') }}</label>
                            <input name="webhook_secret" type="text" value="{{ old('webhook_secret', $settings->webhook_secret) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            <x-input-error class="mt-1" :messages="$errors->get('webhook_secret')" />
                        </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 settings') }}
                            </button>
                        </div>
                    </form>
                @else
                    <p class="text-sm text-gray-500">{{ __('You do not have rights to edit telephony settings.') }}</p>
                @endif
            </section>

            <section class="bg-white border border-gray-200 rounded-xl p-4 space-y-4">
                <div class="flex flex-wrap items-center justify-between gap-3">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-900">{{ __('Call log') }}</h3>
                        <p class="text-sm text-gray-500">{{ __('All incoming and outgoing calls with filters.') }}</p>
                    </div>
                    <div class="text-xs text-gray-500">{{ __('Total:') }} {{ $calls->total() }}</div>
                </div>

                <form method="GET" action="{{ route('telephony.index') }}" class="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-6">
                    <div class="xl:col-span-2">
                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Search') }}</label>
                        <input type="text" name="q" value="{{ $search }}" placeholder="{{ __('Number or call ID') }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Direction') }}</label>
                        <select name="direction" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            <option value="">{{ __('All') }}</option>
                            @foreach ($directionOptions as $value => $label)
                                <option value="{{ $value }}" @selected($direction === $value)>{{ $label }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Status') }}</label>
                        <select name="status" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            <option value="">{{ __('All') }}</option>
                            @foreach ($statusOptions as $value => $label)
                                <option value="{{ $value }}" @selected($status === $value)>{{ $label }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('User') }}</label>
                        <x-user-search-select
                            id="telephony-user-filter"
                            name="user_id"
                            :users="$userOptions"
                            :selected="$selectedUserId"
                            placeholder="{{ __('All users') }}"
                            empty-label="{{ __('All') }}"
                        />
                    </div>

                    <div class="flex items-end gap-2">
                        <button type="submit" class="inline-flex items-center rounded-md bg-gray-800 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700">
                            {{ __('Find') }}
                        </button>
                        <a href="{{ route('telephony.index') }}" class="inline-flex items-center rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">
                            {{ __('Reset') }}
                        </a>
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('From date') }}</label>
                        <input type="date" name="date_from" value="{{ $dateFrom }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('To date') }}</label>
                        <input type="date" name="date_to" value="{{ $dateTo }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                </form>

                @if ($canCreateCall)
                    <details class="rounded-lg border border-gray-200 bg-gray-50 p-3">
                        <summary class="cursor-pointer text-sm font-medium text-gray-700">{{ __('Log a call') }}</summary>
                        <form method="POST" action="{{ route('telephony.calls.store') }}" class="mt-3 grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-6">
                            @csrf

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Direction') }}</label>
                                <select name="direction" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                    @foreach ($directionOptions as $value => $label)
                                        <option value="{{ $value }}" @selected(old('direction', 'inbound') === $value)>{{ $label }}</option>
                                    @endforeach
                                </select>
                                <x-input-error class="mt-1" :messages="$errors->get('direction')" />
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('From') }}</label>
                                <input name="from_number" type="text" value="{{ old('from_number') }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="+1 (555) 100-2000">
                                <x-input-error class="mt-1" :messages="$errors->get('from_number')" />
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('To') }}</label>
                                <input name="to_number" type="text" value="{{ old('to_number') }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="+1 (555) 200-3000">
                                <x-input-error class="mt-1" :messages="$errors->get('to_number')" />
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Status') }}</label>
                                <select name="status" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                    @foreach ($statusOptions as $value => $label)
                                        <option value="{{ $value }}" @selected(old('status', 'completed') === $value)>{{ $label }}</option>
                                    @endforeach
                                </select>
                                <x-input-error class="mt-1" :messages="$errors->get('status')" />
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Duration (sec)') }}</label>
                                <input name="duration_seconds" type="number" min="0" value="{{ old('duration_seconds', 0) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <x-input-error class="mt-1" :messages="$errors->get('duration_seconds')" />
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('User') }}</label>
                                <x-user-search-select
                                    id="telephony-user-create"
                                    name="user_id"
                                    :users="$userOptions"
                                    :selected="old('user_id')"
                                    placeholder="{{ __('Select user') }}"
                                    empty-label="{{ __('Not selected') }}"
                                />
                                <x-input-error class="mt-1" :messages="$errors->get('user_id')" />
                            </div>

                            <div class="md:col-span-2 xl:col-span-3">
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Started at') }}</label>
                                <input name="started_at" type="datetime-local" value="{{ old('started_at') }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <x-input-error class="mt-1" :messages="$errors->get('started_at')" />
                            </div>

                            <div class="md:col-span-2 xl:col-span-3">
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Ended at') }}</label>
                                <input name="ended_at" type="datetime-local" value="{{ old('ended_at') }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <x-input-error class="mt-1" :messages="$errors->get('ended_at')" />
                            </div>

                            <div class="md:col-span-2 xl:col-span-3">
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Recording URL') }}</label>
                                <input name="recording_url" type="text" value="{{ old('recording_url') }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <x-input-error class="mt-1" :messages="$errors->get('recording_url')" />
                            </div>

                            <div class="md:col-span-2 xl:col-span-3">
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('External ID') }}</label>
                                <input name="external_id" type="text" value="{{ old('external_id') }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <x-input-error class="mt-1" :messages="$errors->get('external_id')" />
                            </div>

                            <div class="md:col-span-2 xl:col-span-6 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">
                                    {{ __('Add call') }}
                                </button>
                            </div>
                        </form>
                    </details>
                @endif

                <div class="overflow-hidden rounded-lg border border-gray-200">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Direction') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('From') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('To') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Status') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Duration') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('User') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Started') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Recording') }}</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 bg-white">
                            @forelse ($calls as $call)
                                @php
                                    $badgeClass = $statusBadgeStyles[$call->status] ?? 'bg-slate-100 text-slate-700';
                                    $durationSeconds = (int) ($call->duration_seconds ?? 0);
                                    $durationLabel = $durationSeconds > 0
                                        ? sprintf('%d:%02d', intdiv($durationSeconds, 60), $durationSeconds % 60)
                                        : '—';
                                @endphp
                                <tr class="hover:bg-gray-50">
                                    <td class="px-4 py-3 text-sm text-gray-700">
                                        {{ $directionOptions[$call->direction] ?? ucfirst((string) $call->direction) }}
                                    </td>
                                    <td class="px-4 py-3 text-sm text-gray-700">
                                        <div class="font-medium text-gray-900">{{ $call->from_number ?: '—' }}</div>
                                        <div class="text-xs text-gray-500">{{ $call->external_id ?: '—' }}</div>
                                    </td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $call->to_number ?: '—' }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">
                                        <span class="inline-flex items-center rounded-full px-2.5 py-1 text-xs font-medium {{ $badgeClass }}">
                                            {{ $statusOptions[$call->status] ?? ucfirst((string) $call->status) }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $durationLabel }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $call->user?->name ?: '—' }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">
                                        {{ $call->started_at ? $call->started_at->format('d.m.Y H:i') : '—' }}
                                    </td>
                                    <td class="px-4 py-3 text-sm text-gray-700">
                                        @if ($call->recording_url)
                                            <a href="{{ $call->recording_url }}" class="text-indigo-600 hover:text-indigo-500" target="_blank" rel="noopener">
                                                {{ __('Open recording') }}
                                            </a>
                                        @else
                                            —
                                        @endif
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="8" class="px-4 py-8 text-center text-sm text-gray-500">{{ __('No calls found.') }}</td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>

                <div>
                    {{ $calls->links() }}
                </div>
            </section>
        </div>
    </div>
</x-app-layout>
