@extends('layouts.app')

@section('title', 'WhatsApp')
@section('page-title', 'WhatsApp')

@section('content')
    <div class="mx-auto max-w-3xl">
        <div class="mb-6">
            <h1 class="text-2xl font-semibold text-slate-900">WhatsApp</h1>
            <p class="mt-1 text-sm text-slate-600">
                Canal principal: Evolution API. Conecte o WhatsApp da imobiliária via QR Code e controle o atendimento automático.
            </p>
        </div>

        @include('partials.flash')

        <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
            <dl class="grid gap-4 sm:grid-cols-2">
                <div>
                    <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Provedor</dt>
                    <dd class="mt-1 text-sm font-medium text-slate-900">
                        {{ $provider === \ImovelZapAi\Conversations\Domain\Enums\MessagingProvider::Evolution ? 'Evolution (QR Code)' : 'Meta Cloud API' }}
                    </dd>
                </div>
                <div>
                    <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Status da conexão</dt>
                    <dd class="mt-1">
                        @php
                            $statusClass = match ($connectionStatus) {
                                \ImovelZapAi\Conversations\Domain\Enums\MessagingConnectionStatus::Connected => 'bg-emerald-100 text-emerald-800',
                                \ImovelZapAi\Conversations\Domain\Enums\MessagingConnectionStatus::Connecting => 'bg-amber-100 text-amber-800',
                                default => 'bg-slate-100 text-slate-700',
                            };
                            $statusLabel = match ($connectionStatus) {
                                \ImovelZapAi\Conversations\Domain\Enums\MessagingConnectionStatus::Connected => 'Conectado',
                                \ImovelZapAi\Conversations\Domain\Enums\MessagingConnectionStatus::Connecting => 'Aguardando QR',
                                default => 'Desconectado',
                            };
                        @endphp
                        <span id="connection-badge" class="inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold {{ $statusClass }}">
                            {{ $statusLabel }}
                        </span>
                    </dd>
                </div>
                <div class="sm:col-span-2">
                    <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Atendimento automático</dt>
                    <dd class="mt-1 flex flex-wrap items-center gap-2">
                        <span @class([
                            'inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold',
                            'bg-emerald-100 text-emerald-800' => $automationEnabled,
                            'bg-slate-100 text-slate-700' => ! $automationEnabled,
                        ])>
                            {{ $automationEnabled ? 'Ligado' : 'Desligado' }}
                        </span>
                        @unless ($config)
                            <span class="text-sm text-slate-500">Disponível após conectar o WhatsApp.</span>
                        @endunless
                    </dd>
                </div>
                @if ($config?->instance_name)
                    <div class="sm:col-span-2">
                        <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Instância</dt>
                        <dd class="mt-1 font-mono text-sm text-slate-800">{{ $config->instance_name }}</dd>
                    </div>
                @endif
            </dl>

            @php
                $qr = $qr_base64 ?? session('qr_base64');
                $qrSrc = is_string($qr) && str_starts_with($qr, 'data:')
                    ? $qr
                    : (is_string($qr) && $qr !== '' ? 'data:image/png;base64,'.$qr : null);
            @endphp
            @if ($qrSrc)
                <div class="mt-6 flex flex-col items-center border-t border-slate-100 pt-6">
                    <p class="mb-3 text-sm text-slate-600">Abra o WhatsApp → Aparelhos conectados → Conectar aparelho</p>
                    <img
                        src="{{ $qrSrc }}"
                        alt="QR Code WhatsApp"
                        class="h-64 w-64 rounded-lg border border-slate-200 bg-white p-2"
                    />
                    <p class="mt-3 text-xs text-slate-500">O QR expira em ~60s. Clique em Conectar novamente se necessário.</p>
                </div>
            @endif

            <div class="mt-6 flex flex-wrap gap-3 border-t border-slate-100 pt-6">
                @if ($config)
                    <form method="POST" action="{{ route('whatsapp.automation') }}">
                        @csrf
                        <input type="hidden" name="automation_enabled" value="{{ $automationEnabled ? '0' : '1' }}">
                        <button
                            type="submit"
                            @class([
                                'rounded-lg px-4 py-2 text-sm font-semibold text-white',
                                'bg-slate-700 hover:bg-slate-600' => $automationEnabled,
                                'bg-emerald-600 hover:bg-emerald-500' => ! $automationEnabled,
                            ])
                        >
                            {{ $automationEnabled ? 'Desligar atendimento automático' : 'Ligar atendimento automático' }}
                        </button>
                    </form>
                @endif
                <form method="POST" action="{{ route('whatsapp.connect') }}">
                    @csrf
                    <button
                        type="submit"
                        class="rounded-lg border border-slate-300 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                    >
                        {{ $connectionStatus === \ImovelZapAi\Conversations\Domain\Enums\MessagingConnectionStatus::Connected ? 'Reconectar' : 'Conectar WhatsApp' }}
                    </button>
                </form>
                @if ($config && $connectionStatus !== \ImovelZapAi\Conversations\Domain\Enums\MessagingConnectionStatus::Disconnected)
                    <x-confirm-submit
                        :action="route('whatsapp.disconnect')"
                        title="Desconectar o WhatsApp?"
                        message="O número deixa de ficar ligado a esta imobiliária. Você pode conectar de novo quando quiser."
                        confirm-label="Desconectar"
                        trigger-class="rounded-lg border border-slate-300 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                    >
                        Desconectar
                    </x-confirm-submit>
                @endif
            </div>

            @if ($config)
                <p class="mt-4 text-sm text-slate-600">
                    Quando ligado, o corretor digital responde sozinho no WhatsApp (busca de imóveis, catálogo, qualificação).
                    Desligue para usar o número em conversas pessoais — as mensagens continuam entrando em Pessoas, sem resposta automática.
                </p>
            @endif
        </div>

        <p class="mt-4 text-xs text-slate-500">
            Credenciais da Evolution API ficam no <code class="rounded bg-slate-100 px-1">.env</code>
            (<code class="rounded bg-slate-100 px-1">EVOLUTION_API_URL</code>,
            <code class="rounded bg-slate-100 px-1">EVOLUTION_API_KEY</code>,
            <code class="rounded bg-slate-100 px-1">EVOLUTION_WEBHOOK_BASE_URL</code>).
            Meta Cloud API permanece opcional para cenários enterprise.
        </p>
    </div>

    @if ($connectionStatus !== \ImovelZapAi\Conversations\Domain\Enums\MessagingConnectionStatus::Connected)
        <script>
            const pollStatus = () => {
                fetch(@json(route('whatsapp.status')), {
                    headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
                })
                    .then((response) => response.json())
                    .then((data) => {
                        const badge = document.getElementById('connection-badge');
                        if (!badge) {
                            return;
                        }
                        if (data.qr_base64) {
                            const img = document.querySelector('img[alt="QR Code WhatsApp"]');
                            const src = String(data.qr_base64).startsWith('data:')
                                ? data.qr_base64
                                : 'data:image/png;base64,' + data.qr_base64;
                            if (img) {
                                img.src = src;
                            }
                        }
                        if (!data.connected) {
                            return;
                        }
                        badge.textContent = 'Conectado';
                        badge.className = 'inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold bg-emerald-100 text-emerald-800';
                        window.location.reload();
                    })
                    .catch(() => {});
            };

            setInterval(pollStatus, 4000);
        </script>
    @endif
@endsection
