@extends('layouts.app')

@section('title', 'Weekoff Rules')
@section('heading', 'Weekoff Rules')

@section('content')
@include('settings.partials.back-to-home')
@php
    $dayLabels = ['mon' => 'MON', 'tue' => 'TUE', 'wed' => 'WED', 'thu' => 'THR', 'fri' => 'FRI', 'sat' => 'SAT', 'sun' => 'SUN'];
    $defaultSchedule = \App\Models\WeekoffRule::defaultSchedule();
@endphp

<div
    x-data="{
        drawerOpen: {{ $editRule || $errors->any() ? 'true' : 'false' }},
        historyOpen: false,
        historyUrl: '',
        halfDayEnabled: {{ old('half_day_enabled', $editRule?->half_day_enabled) ? 'true' : 'false' }},
        schedule: @js(old('schedule', $editRule?->schedule ?? $defaultSchedule)),
        closeDrawer() {
            this.drawerOpen = false;
            if (window.location.search.includes('edit=')) {
                window.location.href = @js(route('weekoff-rules.index', ['tab' => 'rules']));
            }
        },
        cycleCell(week, day) {
            const order = this.halfDayEnabled
                ? ['working', 'half_day', 'weekly_off']
                : ['working', 'weekly_off'];
            const current = this.schedule[week][day] ?? 'working';
            const idx = order.indexOf(current);
            const next = order[(idx + 1) % order.length];
            this.schedule[week][day] = next;
        },
        cellClass(value) {
            if (value === 'weekly_off') return 'bg-red-500 border-red-600';
            if (value === 'half_day') return 'bg-amber-400 border-amber-500';
            return 'bg-emerald-500 border-emerald-600';
        }
    }"
    @class([
        'flex min-h-0 flex-col',
        $tab === 'rules' ? 'max-h-[calc(100vh-5.5rem)]' : '',
    ])
>
    @if(session('success'))
        <div class="mb-3 shrink-0 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-800">{{ session('success') }}</div>
    @endif
    @if(session('error'))
        <div class="mb-3 shrink-0 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800">{{ session('error') }}</div>
    @endif

    <div class="mb-3 shrink-0 border-b border-slate-200">
        <nav class="-mb-px flex gap-6 text-sm">
            <a href="{{ route('weekoff-rules.index', ['tab' => 'rules']) }}"
               class="border-b-2 px-1 pb-3 {{ $tab === 'rules' ? 'border-teal-600 text-teal-700' : 'border-transparent text-slate-500 hover:text-slate-700' }}">
                Weekoff Rules
            </a>
            <a href="{{ route('weekoff-rules.index', ['tab' => 'assign']) }}"
               class="border-b-2 px-1 pb-3 {{ $tab === 'assign' ? 'border-teal-600 text-teal-700' : 'border-transparent text-slate-500 hover:text-slate-700' }}">
                Assign Rules
            </a>
        </nav>
    </div>

    @if($tab === 'rules')
        <x-card class="flex min-h-0 flex-1 flex-col !p-0 overflow-hidden">
            <div class="flex shrink-0 items-center justify-between border-b border-slate-100 px-4 py-3">
                <p class="text-sm text-slate-600">Configure weekly off patterns for your company.</p>
                <button
                    type="button"
                    @click="drawerOpen = true"
                    class="inline-flex items-center rounded-lg bg-teal-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-teal-700"
                >
                    <i class="bi bi-plus-lg mr-1"></i> Add
                </button>
            </div>

            <div class="min-h-0 flex-1 overflow-auto">
                <x-table>
                <x-slot name="head">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Name</th>
                        <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Effective From</th>
                        <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Status</th>
                        <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Default</th>
                        <th class="px-4 py-3 text-right text-xs font-medium uppercase text-slate-500">Actions</th>
                    </tr>
                </x-slot>
                @forelse($rules as $rule)
                    <tr>
                        <td class="whitespace-nowrap px-4 py-3 text-sm font-medium text-slate-900">{{ $rule->name }}</td>
                        <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">{{ $rule->effective_from?->format('d-m-Y') }}</td>
                        <td class="whitespace-nowrap px-4 py-3 text-sm">
                            @if($rule->status === 'active')
                                <span class="rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-medium text-emerald-700">Active</span>
                            @else
                                <span class="rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-600">Inactive</span>
                            @endif
                        </td>
                        <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">
                            {{ $rule->is_company_default ? 'Yes' : 'No' }}
                        </td>
                        <td class="whitespace-nowrap px-4 py-3 text-right text-sm">
                            <a href="{{ route('weekoff-rules.index', ['tab' => 'rules', 'edit' => $rule->id]) }}"
                               class="btn-icon-action btn-icon-action--edit" title="Edit" aria-label="Edit"><i class="bi bi-pencil-square"></i></a>
                        </td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="5" class="px-4 py-8 text-center text-sm text-slate-500">
                            No weekoff rules yet. Add a company default rule so all employees get weekly offs.
                        </td>
                    </tr>
                @endforelse
                </x-table>
            </div>
        </x-card>
    @else
        @include('weekoff-rules.partials.assign-tab', [
            'roles' => $roles,
            'locations' => $locations,
            'employees' => $employees,
            'activeRules' => $activeRules,
            'currentAssignments' => $currentAssignments,
        ])
    @endif

    {{-- Rule form drawer --}}
    <div x-show="drawerOpen" x-cloak class="fixed inset-0 z-[70]" role="dialog" aria-modal="true">
        <div class="absolute inset-0 bg-slate-900/35" @click="closeDrawer()"></div>
        <div
            x-show="drawerOpen"
            x-transition:enter="transform transition ease-out duration-250"
            x-transition:enter-start="translate-x-full"
            x-transition:enter-end="translate-x-0"
            x-transition:leave="transform transition ease-in duration-200"
            x-transition:leave-start="translate-x-0"
            x-transition:leave-end="translate-x-full"
            class="absolute right-0 top-0 flex h-full w-full max-w-[420px] flex-col border-l border-slate-200 bg-white shadow-2xl"
        >
            <div class="flex shrink-0 items-center justify-between border-b border-slate-200 px-4 py-3">
                <h3 class="text-base font-semibold text-slate-900">{{ $editRule ? 'Edit Weekoff Rules' : 'Add Weekoff Rules' }}</h3>
                <button type="button" class="rounded-md p-1.5 text-slate-500 hover:bg-slate-100" @click="closeDrawer()">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>

            <form
                id="rule-form"
                method="POST"
                action="{{ $editRule ? route('weekoff-rules.update', $editRule) : route('weekoff-rules.store') }}"
                class="flex min-h-0 flex-1 flex-col"
                novalidate
                data-weekoff-rule-form="{{ $editRule ? 'edit' : 'create' }}"
            >
                @csrf
                @if($editRule) @method('PUT') @endif

                <div class="min-h-0 flex-1 space-y-3 overflow-y-auto px-4 py-3">
                    <div class="grid gap-3 sm:grid-cols-2">
                        <div class="sm:col-span-2">
                            <label class="block text-xs font-medium text-slate-600">Rule Name <span class="text-red-500">*</span></label>
                            <input type="text" name="name" value="{{ old('name', $editRule?->name) }}"
                                   class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-1.5 text-sm">
                            @error('name')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                            <p data-js-error="name" class="mt-1 text-xs text-red-600 hidden"></p>
                        </div>

                        <div>
                            <label class="block text-xs font-medium text-slate-600">Effective From <span class="text-red-500">*</span></label>
                            <input type="date" name="effective_from" value="{{ old('effective_from', $editRule?->effective_from?->format('Y-m-d') ?? now()->format('Y-m-d')) }}"
                                   class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-1.5 text-sm">
                            @error('effective_from')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                            <p data-js-error="effective_from" class="mt-1 text-xs text-red-600 hidden"></p>
                        </div>

                        <div class="flex items-end">
                            <label class="inline-flex w-full items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-xs text-slate-700">
                                <input type="hidden" name="half_day_enabled" value="0">
                                <input type="checkbox" name="half_day_enabled" value="1" x-model="halfDayEnabled"
                                       @checked(old('half_day_enabled', $editRule?->half_day_enabled)) class="rounded border-slate-300">
                                Half Day Enabled
                            </label>
                        </div>

                        <div class="sm:col-span-2">
                            <label class="block text-xs font-medium text-slate-600">Description</label>
                            <textarea name="description" rows="2" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-1.5 text-sm">{{ old('description', $editRule?->description) }}</textarea>
                            @error('description')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                            <p data-js-error="description" class="mt-1 text-xs text-red-600 hidden"></p>
                        </div>
                    </div>

                    <div class="rounded-lg border border-slate-200 p-3">
                        <p class="mb-2 text-xs font-medium uppercase tracking-wide text-slate-500">Rule Settings</p>

                        <div class="w-full">
                            <div class="grid grid-cols-[2rem_repeat(7,minmax(0,1fr))] gap-1 text-center text-[10px] font-medium text-slate-500">
                                <div></div>
                                @foreach($dayLabels as $label)
                                    <div class="truncate py-0.5">{{ $label }}</div>
                                @endforeach

                                @foreach(\App\Models\WeekoffRule::weekKeys() as $week)
                                    <div class="flex items-center justify-start pl-0.5 text-[10px] text-slate-400">W{{ $week }}</div>
                                    @foreach(\App\Models\WeekoffRule::dayKeys() as $day)
                                        <div class="flex items-center justify-center">
                                            <button
                                                type="button"
                                                class="h-7 w-full max-w-[2rem] rounded border"
                                                :class="cellClass(schedule['{{ $week }}']['{{ $day }}'])"
                                                @click="cycleCell('{{ $week }}', '{{ $day }}')"
                                                title="Click to change"
                                            ></button>
                                            <input type="hidden" name="schedule[{{ $week }}][{{ $day }}]" :value="schedule['{{ $week }}']['{{ $day }}']">
                                        </div>
                                    @endforeach
                                @endforeach
                            </div>
                        </div>

                        <div class="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-[10px] text-slate-600">
                            <span class="inline-flex items-center gap-1"><span class="inline-block h-2.5 w-2.5 rounded bg-emerald-500"></span> Working</span>
                            <span class="inline-flex items-center gap-1"><span class="inline-block h-2.5 w-2.5 rounded bg-amber-400"></span> Half Day</span>
                            <span class="inline-flex items-center gap-1"><span class="inline-block h-2.5 w-2.5 rounded bg-red-500"></span> Weekly Off</span>
                        </div>
                    </div>

                    <div class="grid gap-3 sm:grid-cols-2">
                        <div>
                            <label class="mb-1.5 block text-xs font-medium text-slate-600">Status</label>
                            <div class="inline-flex w-full overflow-hidden rounded-lg border border-slate-300">
                                <label class="flex-1 cursor-pointer">
                                    <input type="radio" name="status" value="active" class="peer sr-only" @checked(old('status', $editRule?->status ?? 'active') === 'active')>
                                    <span class="block py-1.5 text-center text-xs peer-checked:bg-teal-600 peer-checked:text-white text-slate-700">Active</span>
                                </label>
                                <label class="flex-1 cursor-pointer border-l border-slate-300">
                                    <input type="radio" name="status" value="inactive" class="peer sr-only" @checked(old('status', $editRule?->status) === 'inactive')>
                                    <span class="block py-1.5 text-center text-xs peer-checked:bg-teal-600 peer-checked:text-white text-slate-700">Inactive</span>
                                </label>
                            </div>
                        </div>

                        <div>
                            <label class="mb-1.5 block text-xs font-medium text-slate-600">Company Default</label>
                            <div class="inline-flex w-full overflow-hidden rounded-lg border border-slate-300">
                                <label class="flex-1 cursor-pointer">
                                    <input type="radio" name="is_company_default" value="1" class="peer sr-only" @checked(old('is_company_default', $editRule?->is_company_default) == true)>
                                    <span class="block py-1.5 text-center text-xs peer-checked:bg-teal-600 peer-checked:text-white text-slate-700">Yes</span>
                                </label>
                                <label class="flex-1 cursor-pointer border-l border-slate-300">
                                    <input type="radio" name="is_company_default" value="0" class="peer sr-only" @checked(! old('is_company_default', $editRule?->is_company_default ?? false))>
                                    <span class="block py-1.5 text-center text-xs peer-checked:bg-teal-600 peer-checked:text-white text-slate-700">No</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <p class="text-[11px] leading-relaxed text-slate-500">Company default applies to all employees without a specific assignment.</p>
                </div>

                <div class="flex shrink-0 gap-2 border-t border-slate-200 bg-white px-4 py-3">
                    <button type="submit" class="inline-flex flex-1 items-center justify-center rounded-lg bg-teal-600 px-4 py-2 text-sm font-medium text-white hover:bg-teal-700">
                        {{ $editRule ? 'Update' : 'Save' }}
                    </button>
                    <button type="button" @click="closeDrawer()" class="inline-flex items-center justify-center rounded-lg border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
                        Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>

    {{-- History drawer --}}
    <div x-show="historyOpen" x-cloak class="fixed inset-0 z-[70]" role="dialog" aria-modal="true">
        <div class="absolute inset-0 bg-slate-900/35" @click="historyOpen = false; historyUrl = ''"></div>
        <div class="absolute right-0 top-0 h-full w-full max-w-lg overflow-hidden border-l border-slate-200 bg-white shadow-2xl">
            <div class="flex items-center justify-between border-b border-slate-200 px-4 py-3">
                <h3 class="font-semibold text-slate-900">Assignment History</h3>
                <button type="button" class="rounded-md p-2 text-slate-500 hover:bg-slate-100" @click="historyOpen = false; historyUrl = ''">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>
            <iframe x-show="historyUrl" :src="historyUrl" class="h-[calc(100%-57px)] w-full bg-white" title="Assignment History"></iframe>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="{{ asset('js/form-validation.js') }}"></script>
<script src="{{ asset('js/form-text-rules.js') }}"></script>
<script src="{{ asset('js/weekoff-form-validation.js') }}"></script>
@endpush
