@extends('layouts.admin')

@section('title', 'Notification Templates')
@section('page-title', 'Notification Templates')

@section('content')
<div class="space-y-6">

    {{-- Header card --}}
    <section class="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
        <div class="flex flex-wrap items-start justify-between gap-4">
            <div>
                <h2 class="text-xl font-bold text-slate-900">Push Notification Templates</h2>
                <p class="mt-1 text-sm text-slate-500">
                    Manage the messages that are sent automatically to users' devices when key events occur.
                    Use <code class="rounded bg-slate-100 px-1.5 py-0.5 text-xs font-mono text-slate-700">{name}</code>,
                    <code class="rounded bg-slate-100 px-1.5 py-0.5 text-xs font-mono text-slate-700">{plan}</code>,
                    <code class="rounded bg-slate-100 px-1.5 py-0.5 text-xs font-mono text-slate-700">{expires_at}</code>,
                    <code class="rounded bg-slate-100 px-1.5 py-0.5 text-xs font-mono text-slate-700">{days}</code>,
                    <code class="rounded bg-slate-100 px-1.5 py-0.5 text-xs font-mono text-slate-700">{email}</code>
                    as dynamic placeholders.
                </p>
            </div>
        </div>

        @if(session('success'))
        <div class="mt-4 flex items-center gap-3 rounded-2xl border border-emerald-200 bg-emerald-50 px-5 py-3">
            <svg class="h-5 w-5 text-emerald-500 shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>
            <p class="text-sm font-medium text-emerald-700">{{ session('success') }}</p>
        </div>
        @endif

        @if(session('error'))
        <div class="mt-4 flex items-center gap-3 rounded-2xl border border-red-200 bg-red-50 px-5 py-3">
            <svg class="h-5 w-5 text-red-500 shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
            <p class="text-sm font-medium text-red-700">{{ session('error') }}</p>
        </div>
        @endif
    </section>

    {{-- Manual Broadcast --}}
    <section class="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm" x-data="{ target: 'all' }">
        <div class="mb-5 flex items-center gap-3">
            <span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-brand-50 text-brand-600">
                <svg class="h-5 w-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>
            </span>
            <div>
                <h2 class="text-lg font-bold text-slate-900">Send Manual Notification</h2>
                <p class="text-sm text-slate-500">Broadcast a custom push notification to all or specific users.</p>
            </div>
        </div>

        @if(!$pushReady)
        <div class="mb-4 flex items-center gap-3 rounded-2xl border border-amber-200 bg-amber-50 px-5 py-3">
            <svg class="h-5 w-5 text-amber-500 shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
            <p class="text-sm font-medium text-amber-700">Firebase is not configured. Manual notifications cannot be sent until FCM is set up in Settings.</p>
        </div>
        @endif

        <form action="{{ route('admin.notifications.send-manual') }}" method="POST" class="space-y-4">
            @csrf

            <div class="grid gap-4 md:grid-cols-2">
                <div>
                    <label class="mb-1.5 block text-sm font-semibold text-slate-700">Title</label>
                    <input type="text" name="title" value="{{ old('title') }}" required
                        class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm outline-none transition focus:border-brand-600 focus:ring-4 focus:ring-brand-600/10"
                        placeholder="Notification title…">
                    @error('title')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>
                <div>
                    <label class="mb-1.5 block text-sm font-semibold text-slate-700">Image URL <span class="text-slate-400 font-normal">(optional)</span></label>
                    <input type="url" name="image_url" value="{{ old('image_url') }}"
                        class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm outline-none transition focus:border-brand-600 focus:ring-4 focus:ring-brand-600/10"
                        placeholder="https://…">
                    @error('image_url')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>
            </div>

            <div>
                <label class="mb-1.5 block text-sm font-semibold text-slate-700">Message Body</label>
                <textarea name="body" rows="3" required
                    class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm outline-none transition focus:border-brand-600 focus:ring-4 focus:ring-brand-600/10 resize-none"
                    placeholder="Your notification message…">{{ old('body') }}</textarea>
                @error('body')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
            </div>

            {{-- Target selection --}}
            <div>
                <label class="mb-2 block text-sm font-semibold text-slate-700">Send To</label>
                <div class="flex flex-wrap gap-3">
                    <label class="flex cursor-pointer items-center gap-2 rounded-2xl border border-slate-200 px-4 py-2.5 text-sm transition has-[:checked]:border-brand-400 has-[:checked]:bg-brand-50">
                        <input type="radio" name="target" value="all" x-model="target" class="accent-brand-600" checked>
                        <span class="font-medium text-slate-700">All Users</span>
                    </label>
                    <label class="flex cursor-pointer items-center gap-2 rounded-2xl border border-slate-200 px-4 py-2.5 text-sm transition has-[:checked]:border-brand-400 has-[:checked]:bg-brand-50">
                        <input type="radio" name="target" value="selected" x-model="target" class="accent-brand-600">
                        <span class="font-medium text-slate-700">Selected Users</span>
                    </label>
                </div>
                @error('target')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
            </div>

            {{-- User multi-select (shown only for "selected") --}}
            <div x-show="target === 'selected'" x-transition>
                <label class="mb-1.5 block text-sm font-semibold text-slate-700">Choose Users</label>
                <div class="max-h-52 overflow-y-auto rounded-2xl border border-slate-200 divide-y divide-slate-100">
                    @foreach($users as $user)
                    <label class="flex cursor-pointer items-center gap-3 px-4 py-2.5 text-sm hover:bg-slate-50 transition has-[:checked]:bg-brand-50">
                        <input type="checkbox" name="user_ids[]" value="{{ $user->id }}" class="h-4 w-4 rounded accent-brand-600">
                        <span class="flex-1 truncate font-medium text-slate-800">{{ $user->name }}</span>
                        <span class="text-xs text-slate-400 truncate">{{ $user->email }}</span>
                    </label>
                    @endforeach
                </div>
                @error('user_ids')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
            </div>

            <div class="pt-1">
                <button type="submit" @if(!$pushReady) disabled @endif
                    class="inline-flex items-center gap-2 rounded-2xl bg-brand-600 px-5 py-2.5 text-sm font-semibold text-white transition hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed">
                    <svg class="h-4 w-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>
                    Send Notification
                </button>
            </div>
        </form>
    </section>

    {{-- Template cards --}}
    @foreach(\App\Models\NotificationTemplate::EVENTS as $event => $meta)
        @php $tpl = $templates[$event] ?? null; @endphp
        <section x-data="{ open: false }" class="rounded-3xl border border-slate-200 bg-white shadow-sm">

            {{-- Card header --}}
            <div class="flex items-center justify-between p-6">
                <div class="flex items-center gap-4">
                    {{-- Enabled / disabled indicator --}}
                    @if($tpl && $tpl->is_enabled)
                        <span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-emerald-100 text-emerald-600">
                            <svg class="h-5 w-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"/></svg>
                        </span>
                    @else
                        <span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-slate-100 text-slate-400">
                            <svg class="h-5 w-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"/></svg>
                        </span>
                    @endif

                    <div>
                        <p class="font-semibold text-slate-900">{{ $meta['label'] }}</p>
                        <p class="text-sm text-slate-500">{{ $meta['desc'] }}</p>
                        @if($tpl)
                        <p class="mt-1 text-xs text-slate-400 font-mono">{{ $event }}</p>
                        @endif
                    </div>
                </div>

                <div class="flex items-center gap-2 shrink-0">
                    @if($tpl)
                    {{-- Toggle enabled/disabled --}}
                    <form action="{{ route('admin.notifications.toggle', $tpl) }}" method="POST">
                        @csrf
                        <button type="submit"
                            class="rounded-xl border px-3 py-1.5 text-xs font-semibold transition
                                {{ $tpl->is_enabled
                                    ? 'border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-100'
                                    : 'border-slate-200 bg-slate-50 text-slate-600 hover:bg-slate-100' }}">
                            {{ $tpl->is_enabled ? 'Enabled' : 'Disabled' }}
                        </button>
                    </form>
                    @endif

                    {{-- Expand/collapse --}}
                    <button type="button" @click="open = !open"
                        class="flex items-center gap-2 rounded-xl bg-brand-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-brand-700">
                        <svg class="h-4 w-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        <span x-text="open ? 'Close' : 'Edit'"></span>
                    </button>
                </div>
            </div>

            {{-- Preview strip (collapsed) --}}
            @if($tpl)
            <div x-show="!open" class="border-t border-slate-100 bg-slate-50 px-6 py-3 rounded-b-3xl">
                <p class="text-xs font-semibold text-slate-500 uppercase tracking-[0.2em] mb-1">Title</p>
                <p class="text-sm text-slate-700 font-medium truncate">{{ $tpl->title }}</p>
                <p class="mt-2 text-xs font-semibold text-slate-500 uppercase tracking-[0.2em] mb-1">Body</p>
                <p class="text-sm text-slate-600 line-clamp-2">{{ $tpl->body }}</p>
            </div>
            @endif

            {{-- Edit panel (expanded) --}}
            <div x-show="open" x-transition class="border-t border-slate-100 px-6 pb-6 pt-4 rounded-b-3xl">
                @if($tpl)
                <form action="{{ route('admin.notifications.update', $tpl) }}" method="POST" class="space-y-4">
                    @csrf @method('PUT')

                    <div class="grid gap-4 md:grid-cols-2">
                        <div>
                            <label class="mb-1.5 block text-sm font-semibold text-slate-700">Title</label>
                            <input type="text" name="title" value="{{ old('title', $tpl->title) }}"
                                class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm outline-none transition focus:border-brand-600 focus:ring-4 focus:ring-brand-600/10"
                                placeholder="e.g. Welcome, {name}!">
                            @error('title')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                        </div>
                        <div>
                            <label class="mb-1.5 block text-sm font-semibold text-slate-700">Image URL <span class="text-slate-400 font-normal">(optional)</span></label>
                            <input type="url" name="image_url" value="{{ old('image_url', $tpl->image_url) }}"
                                class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm outline-none transition focus:border-brand-600 focus:ring-4 focus:ring-brand-600/10"
                                placeholder="https://...">
                            @error('image_url')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                        </div>
                    </div>

                    <div>
                        <label class="mb-1.5 block text-sm font-semibold text-slate-700">Message Body</label>
                        <textarea name="body" rows="3"
                            class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm outline-none transition focus:border-brand-600 focus:ring-4 focus:ring-brand-600/10 resize-none"
                            placeholder="Hi {name}, your {plan} plan is now active.">{{ old('body', $tpl->body) }}</textarea>
                        @error('body')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                    </div>

                    {{-- Available variables cheatsheet --}}
                    <div class="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3">
                        <p class="mb-2 text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Available placeholders</p>
                        <div class="flex flex-wrap gap-2">
                            @foreach(\App\Models\NotificationTemplate::VARIABLES as $var => $desc)
                            <span title="{{ $desc }}"
                                class="inline-flex cursor-help items-center gap-1 rounded-xl bg-white border border-slate-200 px-2.5 py-1 text-xs font-mono font-semibold text-brand-700">
                                {{ $var }}
                            </span>
                            @endforeach
                        </div>
                    </div>

                    <div class="flex flex-wrap items-center gap-3 pt-2">
                        <button type="submit"
                            class="inline-flex items-center gap-2 rounded-2xl bg-brand-600 px-5 py-2.5 text-sm font-semibold text-white transition hover:bg-brand-700">
                            <svg class="h-4 w-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>
                            Save Template
                        </button>

                        {{-- Test send --}}
                        @if($devices->isNotEmpty())
                        <div x-data="{ testOpen: false }" class="relative">
                            <button type="button" @click="testOpen = !testOpen"
                                class="inline-flex items-center gap-2 rounded-2xl border border-slate-300 px-5 py-2.5 text-sm font-semibold text-slate-700 transition hover:border-brand-400 hover:text-brand-600">
                                <svg class="h-4 w-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>
                                Send Test
                            </button>
                            <div x-show="testOpen" x-transition @click.outside="testOpen = false"
                                class="absolute left-0 top-full mt-2 w-80 rounded-2xl border border-slate-200 bg-white p-4 shadow-xl z-10">
                                <form action="{{ route('admin.notifications.test', $tpl) }}" method="POST" class="space-y-3">
                                    @csrf
                                    <label class="block text-sm font-semibold text-slate-700">Target Device</label>
                                    <select name="device_id" class="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand-600">
                                        @foreach($devices as $device)
                                        <option value="{{ $device->id }}">{{ $device->user?->name ?? 'Unknown' }} — {{ Str::limit($device->device_id, 16) }}</option>
                                        @endforeach
                                    </select>
                                    <button type="submit" class="w-full rounded-xl bg-slate-900 px-4 py-2 text-sm font-semibold text-white transition hover:bg-slate-700">
                                        Send Test Notification
                                    </button>
                                </form>
                            </div>
                        </div>
                        @endif
                    </div>
                </form>
                @else
                    <p class="text-sm text-slate-500 italic">This template has not been created yet. Run <code class="rounded bg-slate-100 px-1 text-xs">php artisan migrate</code> to seed the default templates.</p>
                @endif
            </div>

        </section>
    @endforeach

</div>
@endsection
