@extends('layouts.app')

@section('title', 'Leave Summary')
@section('heading', 'Leave Summary')

@section('content')
    @include('leaves.top-submenu')

    <div class="space-y-6">
        {{-- Header --}}
        <div class="flex flex-wrap items-start justify-between gap-3">
            <div>
                <p class="text-sm text-slate-600">
                    Your leave summary for calendar year
                    <strong class="text-slate-800">{{ $year }}</strong>.
                </p>
            </div>
            <div class="flex flex-wrap items-center gap-2">
                <form method="GET" action="{{ route('leaves.dashboard') }}" class="inline-flex items-center gap-2">
                    <label for="leave-year" class="sr-only">Year</label>
                    <select id="leave-year" name="year" onchange="this.form.submit()"
                            class="rounded border border-slate-200 bg-white px-3 py-2 text-sm text-slate-800 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 js-select2" style="width: 110px;">
                        @foreach($yearOptions as $opt)
                            <option value="{{ $opt }}" @selected((int) $year === (int) $opt)>{{ $opt }}</option>
                        @endforeach
                    </select>
                </form>
                <a href="{{ route('leaves.create') }}"
                   class="inline-flex items-center gap-1.5 rounded bg-primary px-4 py-2 text-sm font-semibold text-white shadow-sm hover:opacity-95">
                    <i class="bi bi-plus-lg"></i> Request Leave
                </a>
                @if(auth()->user()->hasPermission('leave_types_create'))
                    <a href="{{ route('leave-types.manage') }}"
                       class="inline-flex items-center rounded border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
                        Leave Rules
                    </a>
                @endif
            </div>
        </div>

        @if(session('import_errors'))
            <x-card>
                <h3 class="mb-2 text-sm font-semibold text-amber-800">Import row errors</h3>
                <ul class="max-h-40 space-y-1 overflow-y-auto text-sm text-amber-900">
                    @foreach(session('import_errors') as $row => $message)
                        <li>Row {{ $row }}: {{ $message }}</li>
                    @endforeach
                </ul>
            </x-card>
        @endif

        @include('leaves.partials.stats', ['leaveStats' => $leaveStats])

        <div class="grid gap-6 xl:grid-cols-3">
            <div class="space-y-6 xl:col-span-2">
                @include('leaves.partials.balance-cards', ['balances' => $balances])
                @include('leaves.partials.rules-summary', ['ruleSummaries' => $ruleSummaries])
            </div>
            <div class="space-y-6">
                @include('leaves.partials.monthly-generation', [
                    'monthlyGeneration' => $monthlyGeneration,
                    'allowAdvanceMonthly' => $allowAdvanceMonthly,
                    'allowMonthlyOpeningOverride' => $allowMonthlyOpeningOverride,
                    'year' => $year,
                ])
                @include('leaves.partials.pending-cards', [
                    'pendingLeaves' => $pendingLeaves,
                    'recentLeaves' => $recentLeaves,
                ])
            </div>
        </div>

        @if(! empty($teamBalances))
            <x-card>
                <h2 class="mb-4 text-base font-semibold text-slate-900">Team balances</h2>
                <div class="max-h-[28rem] space-y-3 overflow-y-auto">
                    @foreach($teamBalances as $entry)
                        <div class="rounded border border-slate-200 p-3">
                            <p class="mb-2 text-sm font-semibold text-slate-800">{{ $entry['user']->name }}</p>
                            <div class="flex flex-wrap gap-2 text-xs">
                                @foreach($entry['balances'] as $row)
                                    @unless($row['is_unlimited'])
                                        <span class="rounded-full bg-slate-100 px-2 py-1 text-slate-700">
                                            {{ $row['name'] }}: {{ number_format($row['available'], 1) }} avail
                                        </span>
                                    @else
                                        <span class="rounded-full bg-slate-100 px-2 py-1 text-slate-700">
                                            {{ $row['name'] }}: ∞
                                        </span>
                                    @endunless
                                @endforeach
                            </div>
                        </div>
                    @endforeach
                </div>
            </x-card>
        @endif
    </div>
@endsection

@push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            if (typeof Chart === 'undefined') return;

            var palette = { muted: '#94a3b8', border: '#ffffff' };
            var leaveStats = @json($leaveStats);

            var weeklyEl = document.getElementById('leaveWeeklyChart');
            if (weeklyEl) {
                new Chart(weeklyEl.getContext('2d'), {
                    type: 'bar',
                    data: {
                        labels: leaveStats.weekly.labels,
                        datasets: [{
                            data: leaveStats.weekly.data,
                            backgroundColor: '#0ea5e9',
                            borderRadius: 4,
                            borderSkipped: false,
                            maxBarThickness: 28
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: { legend: { display: false } },
                        scales: {
                            x: { grid: { display: false }, ticks: { color: palette.muted } },
                            y: { beginAtZero: true, ticks: { color: palette.muted, precision: 0 } }
                        }
                    }
                });
            }

            var typeEl = document.getElementById('leaveTypesConsumedChart');
            if (typeEl) {
                var typeLabels = leaveStats.by_type.labels || [];
                var typeData = leaveStats.by_type.data || [];
                new Chart(typeEl.getContext('2d'), {
                    type: 'doughnut',
                    data: {
                        labels: typeLabels.length ? typeLabels : ['No leave taken'],
                        datasets: [{
                            data: typeData.length ? typeData : [1],
                            backgroundColor: typeData.length
                                ? ['#ef4444', '#10b981', '#0ea5e9', '#f59e0b', '#6366f1', '#14b8a6']
                                : ['#e2e8f0'],
                            borderColor: palette.border,
                            borderWidth: 2
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        cutout: '62%',
                        plugins: {
                            legend: { position: 'bottom', labels: { boxWidth: 10, color: palette.muted } }
                        }
                    }
                });
            }

            var monthlyEl = document.getElementById('leaveMonthlyChart');
            if (monthlyEl) {
                new Chart(monthlyEl.getContext('2d'), {
                    type: 'bar',
                    data: {
                        labels: leaveStats.monthly.labels,
                        datasets: [{
                            data: leaveStats.monthly.data,
                            backgroundColor: '#14b8a6',
                            borderRadius: 4,
                            borderSkipped: false,
                            maxBarThickness: 18
                        }]
                    },
                    options: {
                        indexAxis: 'y',
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: { legend: { display: false } },
                        scales: {
                            x: { beginAtZero: true, ticks: { color: palette.muted, precision: 0 } },
                            y: { grid: { display: false }, ticks: { color: palette.muted } }
                        }
                    }
                });
            }

        });
    </script>
@endpush
