<x-app-layout>
    <x-slot name="header">
        {{ __('Departments') }}
    </x-slot>

    <div x-data class="p-6 space-y-6">
        @if (session('status'))
            <div class="rounded-md bg-green-50 border border-green-200 px-4 py-3 text-sm text-green-800">
                {{ session('status') }}
            </div>
        @endif

        @if ($errors->any())
            <div class="rounded-md bg-red-50 border border-red-200 px-4 py-3 text-sm text-red-800">
                <ul class="list-disc pl-5 space-y-1">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <div class="bg-white border border-gray-200 rounded-xl shadow-sm p-5 flex items-center justify-between">
            <div>
                <h1 class="text-xl font-semibold text-gray-900">Departments</h1>
                <p class="mt-1 text-sm text-gray-600">
                    Manage organizational departments and their members for the current dealer.
                </p>
            </div>

            <a
                href="{{ route('settings.departments.create') }}"
                class="inline-flex items-center rounded-lg bg-red-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-red-700"
            >
                Add Department
            </a>
        </div>

        <div class="space-y-4">
            @forelse ($departments as $department)
                <div
                    x-data="departmentMembersComponent({{ $department->id }})"
                    class="bg-white border border-gray-200 rounded-xl shadow-sm"
                >
                    <div class="flex items-center justify-between px-4 py-3 border-b border-gray-100">
                        <div class="flex items-center gap-3">
                            <h2 class="text-sm font-semibold text-gray-900">
                                {{ $department->name }}
                            </h2>
                            @if ($department->is_system)
                                <span class="inline-flex items-center rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-700">
                                    System
                                </span>
                            @endif
                        </div>

                        <div class="flex items-center gap-2">
                            <button
                                type="button"
                                @click="openAddModal()"
                                class="inline-flex items-center rounded-md border border-gray-200 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50"
                            >
                                Add Users
                            </button>

                            @if ($department->users->isNotEmpty())
                                <button
                                    type="button"
                                    @click="toggleRemoveMode()"
                                    x-show="!removeMode"
                                    class="inline-flex items-center rounded-md border border-gray-200 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50"
                                >
                                    Remove Users
                                </button>
                            @endif

                            @if (!$department->is_system)
                                <a
                                    href="{{ route('settings.departments.edit', $department->id) }}"
                                    class="inline-flex items-center rounded-md border border-gray-200 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50"
                                >
                                    Edit
                                </a>

                                <form
                                    method="POST"
                                    action="{{ route('settings.departments.destroy', $department->id) }}"
                                    id="department-delete-{{ $department->id }}"
                                >
                                    @csrf
                                    @method('DELETE')
                                    <button
                                        type="button"
                                        @click="$store.__confirm.openConfirm('Are you sure you want to delete this department?', 'department-delete-{{ $department->id }}')"
                                        class="inline-flex items-center rounded-md border border-red-200 px-3 py-1.5 text-xs font-medium text-red-700 hover:bg-red-50"
                                    >
                                        Delete
                                    </button>
                                </form>
                            @endif
                        </div>
                    </div>

                    <div class="px-4 py-3 space-y-3">
                        <div class="flex items-center justify-between">
                            <p class="text-xs text-gray-500">
                                Members
                            </p>

                            @if ($department->users->isNotEmpty())
                                <div class="flex items-center gap-2">
                                    <button
                                        type="submit"
                                        form="remove-form-{{ $department->id }}"
                                        x-show="removeMode"
                                        class="inline-flex items-center rounded-md bg-red-600 px-2 py-1 text-xs font-semibold text-white hover:bg-red-700"
                                    >
                                        Remove Selected
                                    </button>

                                    <button
                                        type="button"
                                        @click="cancelRemoveMode()"
                                        x-show="removeMode"
                                        class="inline-flex items-center rounded-md border border-gray-200 px-2 py-1 text-xs text-gray-700 hover:bg-gray-50"
                                    >
                                        Cancel
                                    </button>
                                </div>
                            @endif
                        </div>

                        <form
                            id="remove-form-{{ $department->id }}"
                            method="POST"
                            action="{{ route('settings.departments.members.remove', $department->id) }}"
                            class="space-y-2"
                        >
                            @csrf

                            @forelse ($department->users as $member)
                                <div class="flex items-center justify-between rounded-md border border-gray-100 px-3 py-2">
                                    <div>
                                        <div class="text-sm font-semibold text-gray-900">
                                            {{ $member->full_name }}
                                        </div>
                                        @php
                                            $title = $member->primary_role_name;
                                        @endphp
                                        @if ($title)
                                            <div class="text-xs text-gray-600">
                                                {{ $title }}
                                            </div>
                                        @endif
                                        <div class="text-xs text-gray-500">
                                            {{ $member->email }}
                                        </div>
                                    </div>

                                    <label
                                        class="ml-2"
                                        x-show="removeMode"
                                    >
                                        <input
                                            type="checkbox"
                                            name="user_ids[]"
                                            value="{{ $member->id }}"
                                            class="h-4 w-4 rounded border-gray-300 text-red-600 focus:ring-red-500"
                                        >
                                    </label>
                                </div>
                            @empty
                                <p class="text-xs text-gray-500">
                                    No members in this department yet.
                                </p>
                            @endforelse
                        </form>
                    </div>

                    <!-- Add Users Modal -->
                    <div
                        class="fixed inset-0 z-40 flex items-center justify-center bg-black/40"
                        x-show="addOpen"
                        x-cloak
                    >
                        <div class="bg-white rounded-xl shadow-lg max-w-lg w-full mx-4">
                            <div class="flex items-center justify-between border-b border-gray-100 px-4 py-3">
                                <h3 class="text-sm font-semibold text-gray-900">
                                    Add Users to {{ $department->name }}
                                </h3>
                                <button
                                    type="button"
                                    @click="closeAddModal()"
                                    class="text-gray-400 hover:text-gray-600"
                                >
                                    ✕
                                </button>
                            </div>

                            <div class="px-4 py-3 space-y-3">
                                <div class="flex items-end gap-2">
                                    <div class="flex-1">
                                        <label class="block text-xs font-medium text-gray-600">Search</label>
                                        <input
                                            type="text"
                                            x-model="addQuery"
                                            @keydown.enter.prevent="fetchUsers()"
                                            class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-red-500 focus:ring-red-500 text-sm"
                                            placeholder="Name, surname, email"
                                        >
                                    </div>
                                    <button
                                        type="button"
                                        @click="fetchUsers()"
                                        class="inline-flex items-center rounded-md bg-gray-900 px-3 py-2 text-xs font-semibold text-white hover:bg-gray-800"
                                    >
                                        Search
                                    </button>
                                </div>

                                <form
                                    method="POST"
                                    :action="addActionUrl"
                                    class="max-h-64 overflow-y-auto border border-gray-100 rounded-md p-2 space-y-1"
                                >
                                    @csrf

                                    <template x-if="loading">
                                        <p class="text-xs text-gray-500 px-1 py-1.5">
                                            Loading users...
                                        </p>
                                    </template>

                                    <template x-if="!loading && addResults.length === 0">
                                        <p class="text-xs text-gray-500 px-1 py-1.5">
                                            No users found.
                                        </p>
                                    </template>

                                    <template x-for="user in addResults" :key="user.id">
                                        <label class="flex items-center justify-between rounded-md px-2 py-1 hover:bg-gray-50 cursor-pointer">
                                            <div>
                                                <div class="text-sm font-medium text-gray-900" x-text="user.name + ' ' + user.surname"></div>
                                                <div class="text-xs text-gray-500" x-text="user.email"></div>
                                            </div>
                                            <input
                                                type="checkbox"
                                                name="user_ids[]"
                                                :value="user.id"
                                                class="h-4 w-4 rounded border-gray-300 text-red-600 focus:ring-red-500"
                                            >
                                        </label>
                                    </template>

                                    <div class="flex items-center justify-end gap-2 pt-3">
                                        <button
                                            type="button"
                                            @click="closeAddModal()"
                                            class="inline-flex items-center rounded-md border border-gray-200 px-3 py-1.5 text-xs text-gray-700 hover:bg-gray-50"
                                        >
                                            Cancel
                                        </button>
                                        <button
                                            type="submit"
                                            class="inline-flex items-center rounded-md bg-red-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-red-700"
                                        >
                                            Add Selected
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                </div>
            @empty
                <div class="bg-white border border-gray-200 rounded-xl shadow-sm px-4 py-6 text-center text-sm text-gray-500">
                    No departments found.
                </div>
            @endforelse
        </div>

        @if (isset($deletedDepartments) && $deletedDepartments->isNotEmpty())
            <div class="bg-white border border-gray-200 rounded-xl shadow-sm p-4 space-y-2">
                <div class="flex items-center justify-between pb-2 border-b border-gray-100">
                    <div>
                        <h2 class="text-sm font-semibold text-gray-900">Deleted Departments</h2>
                        <p class="mt-1 text-xs text-gray-500">
                            These departments have been soft deleted and are hidden from the main list.
                        </p>
                    </div>
                </div>

                <div class="divide-y divide-gray-100">
                    @foreach ($deletedDepartments as $department)
                        <div class="flex items-center justify-between px-2 py-2">
                            <div>
                                <div class="text-sm font-semibold text-gray-900">
                                    {{ $department->name }}
                                </div>
                                <div class="text-xs text-gray-500">
                                    Code: {{ $department->code }}
                                </div>
                            </div>
                            <form
                                method="POST"
                                action="{{ route('settings.departments.restore', $department->id) }}"
                            >
                                @csrf
                                @method('PATCH')
                                <button
                                    type="submit"
                                    class="inline-flex items-center rounded-md border border-gray-200 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50"
                                >
                                    Restore
                                </button>
                            </form>
                        </div>
                    @endforeach
                </div>
            </div>
        @endif
    </div>

    <script>
        window.departmentMembersComponent = function (departmentId) {
            return {
                removeMode: false,
                addOpen: false,
                addQuery: '',
                addResults: [],
                loading: false,
                get addActionUrl() {
                    return '{{ url('settings/departments') }}/' + departmentId + '/members/add';
                },
                toggleRemoveMode() {
                    this.removeMode = true;
                },
                cancelRemoveMode() {
                    this.removeMode = false;
                },
                openAddModal() {
                    this.addOpen = true;
                    this.addResults = [];
                    this.addQuery = '';
                    this.fetchUsers();
                },
                closeAddModal() {
                    this.addOpen = false;
                },
                fetchUsers() {
                    this.loading = true;
                    const params = new URLSearchParams();
                    if (this.addQuery) {
                        params.set('q', this.addQuery);
                    }

                    fetch('{{ url('settings/departments') }}/' + departmentId + '/members/search?' + params.toString(), {
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'Accept': 'application/json',
                        },
                    })
                        .then(response => response.json())
                        .then(data => {
                            this.addResults = Array.isArray(data) ? data : [];
                        })
                        .catch(() => {
                            this.addResults = [];
                        })
                        .finally(() => {
                            this.loading = false;
                        });
                },
            };
        };
    </script>
</x-app-layout>

