<div class="htmx-indicator full-width-loader">
    <div class="indeterminate"></div>
</div>

@if(isset($error))
    <div class="alert alert-danger">
        {!! __($error) !!}
    </div>
@else
<div id="allTasksContainer"
     hx-get="{{BASE_URL}}/hx/AllTasks/AllTasks/get"
     hx-trigger="{{ \Leantime\Domain\Tickets\Htmx\HtmxTicketEvents::UPDATE }} from:body, refresh"
     class="clear"
     hx-swap="outerHTML"
     hx-ext="json-enc"
     hx-indicator=".htmx-indicator"
>
    <!-- Filters Section -->
    <div class="clear" style="position:absolute; top:10px; right:35px;">
        <!-- Group By Selector -->
        <div class="btn-group left">
            <button class="btn btn-link btn-round-icon dropdown-toggle f-right" type="button" 
                    data-tippy-content="{!! __('alltasks.grouping.title') !!}"
                    data-toggle="dropdown">
                <span class="fa-solid fa-diagram-project"></span>
            </button>
            <ul class="dropdown-menu pull-right">
                <li class="nav-header">{!! __("alltasks.grouping.title") !!}</li>
                <li>
                    <span class="radio">
                        <input type="radio" name="allTasksGroupBy"
                               @if($groupBy == "user") checked='checked' @endif
                               value="user" id="allTasksGroupByUser"
                               hx-get="{{BASE_URL}}/hx/AllTasks/AllTasks/get"
                               hx-trigger="click"
                               hx-target="#allTasksContainer"
                               hx-swap="outerHTML"
                               hx-indicator=".htmx-indicator"
                               style="margin-top:4px;"
                               hx-vals='{"projectFilter": "{{ $projectFilter }}", "userFilter": "{{ $userFilter }}", "statusFilter": "{{ $statusFilter }}", "groupBy": "user"}'
                        />
                        <label for="allTasksGroupByUser">{!! __("alltasks.grouping.by_user") !!}</label>
                    </span>
                </li>
                <li>
                    <span class="radio">
                        <input type="radio" name="allTasksGroupBy"
                               @if($groupBy == "project") checked='checked' @endif
                               value="project" id="allTasksGroupByProject"
                               hx-get="{{BASE_URL}}/hx/AllTasks/AllTasks/get"
                               hx-trigger="click"
                               hx-target="#allTasksContainer"
                               hx-swap="outerHTML"
                               hx-indicator=".htmx-indicator"
                               style="margin-top:4px;"
                               hx-vals='{"projectFilter": "{{ $projectFilter }}", "userFilter": "{{ $userFilter }}", "statusFilter": "{{ $statusFilter }}", "groupBy": "project"}'
                        />
                        <label for="allTasksGroupByProject">{!! __("alltasks.grouping.by_project") !!}</label>
                    </span>
                </li>
            </ul>
        </div>

        <!-- Filters Dropdown -->
        <div class="btn-group left">
            <button class="btn btn-link btn-round-icon dropdown-toggle f-right" type="button" data-toggle="dropdown">
                <i class="fas fa-filter"></i>
                @php
                    $activeFilters = 0;
                    if ($projectFilter != '') $activeFilters++;
                    if ($userFilter != '') $activeFilters++;
                    if ($statusFilter != 'not_done') $activeFilters++;
                @endphp
                @if($activeFilters > 0)
                    <span class='badge badge-primary'>{{ $activeFilters }}</span>
                @endif
            </button>
            <ul class="dropdown-menu pull-right" style="min-width:250px;">
                <li class="nav-header">{!! __("alltasks.filters.title") !!}</li>
                
                <!-- Project Filter -->
                <li style="padding: 5px 15px;" onclick="event.stopPropagation();">
                    <label>{!! __('alltasks.filters.project') !!}</label>
                    <select name="projectFilter" 
                            class="tw-w-full"
                            hx-get="{{BASE_URL}}/hx/AllTasks/AllTasks/get"
                            hx-trigger="change"
                            hx-target="#allTasksContainer"
                            hx-swap="outerHTML"
                            hx-indicator=".htmx-indicator"
                            hx-include="[name='userFilter'], [name='statusFilter'], [name='allTasksGroupBy']:checked">
                        <option value="" {{ $projectFilter === '' ? 'selected' : '' }}>{!! __("alltasks.filters.all_projects") !!}</option>
                        @if(isset($allProjects))
                            @foreach($allProjects as $project)
                                <option value="{{ $project['id'] }}" {{ $projectFilter == $project['id'] ? 'selected' : '' }}>
                                    {{ $project['name'] }}
                                </option>
                            @endforeach
                        @endif
                    </select>
                </li>

                <!-- User Filter -->
                <li style="padding: 5px 15px;" onclick="event.stopPropagation();">
                    <label>{!! __('alltasks.filters.user') !!}</label>
                    <select name="userFilter"
                            class="tw-w-full"
                            hx-get="{{BASE_URL}}/hx/AllTasks/AllTasks/get"
                            hx-trigger="change"
                            hx-target="#allTasksContainer"
                            hx-swap="outerHTML"
                            hx-indicator=".htmx-indicator"
                            hx-include="[name='projectFilter'], [name='statusFilter'], [name='allTasksGroupBy']:checked">
                        <option value="" {{ $userFilter === '' ? 'selected' : '' }}>{!! __("alltasks.filters.all_users") !!}</option>
                        @if(isset($allUsers))
                            @foreach($allUsers as $user)
                                <option value="{{ $user['id'] }}" {{ $userFilter == $user['id'] ? 'selected' : '' }}>
                                    {{ $user['firstname'] }} {{ $user['lastname'] }}
                                </option>
                            @endforeach
                        @endif
                    </select>
                </li>

                <!-- Status Filter -->
                <li style="padding: 5px 15px;" onclick="event.stopPropagation();">
                    <label>{!! __('alltasks.filters.status') !!}</label>
                    <select name="statusFilter"
                            class="tw-w-full"
                            hx-get="{{BASE_URL}}/hx/AllTasks/AllTasks/get"
                            hx-trigger="change"
                            hx-target="#allTasksContainer"
                            hx-swap="outerHTML"
                            hx-indicator=".htmx-indicator"
                            hx-include="[name='projectFilter'], [name='userFilter'], [name='allTasksGroupBy']:checked">
                        <option value="not_done" {{ $statusFilter == 'not_done' ? 'selected' : '' }}>
                            {!! __('alltasks.filters.open_tasks') !!}
                        </option>
                        <option value="" {{ $statusFilter == '' ? 'selected' : '' }}>
                            {!! __('alltasks.filters.all_statuses') !!}
                        </option>
                        <option value="done" {{ $statusFilter == 'done' ? 'selected' : '' }}>
                            {!! __('alltasks.filters.completed') !!}
                        </option>
                    </select>
                </li>
            </ul>
        </div>
    </div>

    <div class="tw-flex tw-flex-col">
        <div class="">
            @if(!isset($ticketsGrouped) || count($ticketsGrouped) == 0)
                <div class='center'>
                    <div style='width:30%' class='svgContainer'>
                        {!! file_get_contents(ROOT . "/dist/images/svg/undraw_a_moment_to_relax_bbpa.svg") !!}
                    </div>
                    <br/>
                    <h4>{!! __("alltasks.messages.no_tasks_found") !!}</h4>
                </div>
            @endif

            @foreach($ticketsGrouped as $groupId => $tickets)
                @php
                    // Determine icon and group name based on groupBy
                    if ($groupBy === 'user') {
                        $icon = 'fa fa-user';
                        $groupLabel = $groupNames[$groupId] ?? 'Unknown';
                    } else {
                        $icon = 'fa fa-folder';
                        $groupLabel = $groupNames[$groupId] ?? 'Unknown';
                    }
                @endphp
                
                <x-global::accordion id="ticketBox-{{ $groupBy }}-{{ $groupId }}">
                    <x-slot name="title">
                        <i class="{{ $icon }}"></i> {{ $groupLabel }}
                        <span class="task-count">({{ count($tickets) }})</span>
                    </x-slot>
                    <x-slot name="content">
                        <div id="sortable-tasks-{{ $groupId }}" class="sortable-container">
                            @foreach($tickets as $ticket)
                                @php
                                    $projectId = $ticket['projectId'];
                                    $ticketDataJson = json_encode([
                                        'id' => $ticket['id'],
                                        'title' => $ticket['headline'],
                                        'color' => 'var(--accent2)',
                                        'entityType' => 'ticket',
                                        'url' => BASE_URL.'#/tickets/showTicket/'.$ticket['id'],
                                    ]);
                                @endphp
                                
                                <div class="ticketBox priority-border-{{ $ticket['priority'] ?? 0 }}" 
                                     data-val="{{ $ticket['id'] }}"
                                     data-event='{!! $ticketDataJson !!}'>
                                    
                                    <div class="tw-flex tw-flex-row">
                                        <div class="tw-flex-1 ticket-title ticket-title-wrapper">
                                            <div class="title-text">
                                                @if($groupBy === 'user')
                                                    <small style="display:inline-block;">{{ $projectNames[$projectId] ?? $ticket['projectName'] ?? 'Unknown' }}</small> <br/>
                                                @endif
                                                <strong>
                                                    <a href="#/tickets/showTicket/{{ $ticket['id'] }}" preload="mouseover">
                                                        {{ $ticket['headline'] }}
                                                    </a>
                                                </strong>
                                            </div>
                                        </div>

                                        <div class="tw-content-center right">
                                            <div class="tw-flex tw-flex-row tw-gap-2 tw-items-center">
                                                @if($groupBy === 'project' && !empty($ticket['userFirstname']))
                                                    <div class="tw-hidden sm:tw-block profileImage">
                                                        <img src="{{ BASE_URL }}/api/users?profileImage={{ $ticket['editorId'] ?? $ticket['userId'] }}" 
                                                             alt="{{ $ticket['userFirstname'] }}"
                                                             data-tippy-content="{{ $ticket['userFirstname'] }} {{ $ticket['userLastname'] }}"/>
                                                    </div>
                                                @endif

                                                @if(!empty($ticket['dateToFinish']) && $ticket['dateToFinish'] != '0000-00-00 00:00:00' && $ticket['dateToFinish'] != '1969-12-31 00:00:00')
                                                    @php
                                                        $today = strtotime(date('Y-m-d'));
                                                        $dueDate = strtotime($ticket['dateToFinish']);
                                                        $isOverdue = $dueDate < $today;
                                                    @endphp
                                                    <div class="ticket-due-date {{ $isOverdue ? 'overdue' : '' }}">
                                                        <i class="fa fa-calendar"></i>
                                                        {{ format($ticket['dateToFinish'])->date() }}
                                                    </div>
                                                @endif

                                                @if(isset($statusLabels[$projectId][$ticket['status']]))
                                                    <div class="dropdown ticketDropdown statusDropdown colorized">
                                                        <a class="dropdown-toggle status {{ $statusLabels[$projectId][$ticket['status']]['class'] ?? 'label-default' }}"
                                                           href="javascript:void(0);"
                                                           role="button"
                                                           id="allTasksStatusDropdown{{ $ticket['id'] }}"
                                                           data-toggle="dropdown"
                                                           aria-haspopup="true"
                                                           aria-expanded="false">
                                                            <span class="text">
                                                                {{ $statusLabels[$projectId][$ticket['status']]['name'] }}
                                                            </span>
                                                            &nbsp;<i class="fa fa-caret-down" aria-hidden="true"></i>
                                                        </a>
                                                        <ul class="dropdown-menu pull-right"
                                                            aria-labelledby="allTasksStatusDropdown{{ $ticket['id'] }}">
                                                            <li class="nav-header border">{{ __("dropdown.choose_status") }}</li>
                                                            @foreach($statusLabels[$projectId] as $statusKey => $statusLabel)
                                                                <li class='dropdown-item'>
                                                                    <a href='javascript:void(0);'
                                                                       class='{{ $statusLabel["class"] }}'
                                                                       data-label='{{ $statusLabel["name"] }}'
                                                                       data-value='{{ $ticket["id"] }}_{{ $statusKey }}_{{ $statusLabel["class"] }}'>
                                                                        {{ $statusLabel["name"] }}
                                                                    </a>
                                                                </li>
                                                            @endforeach
                                                        </ul>
                                                    </div>
                                                @endif
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    </x-slot>
                </x-global::accordion>
            @endforeach
        </div>
    </div>
</div>

<script type="text/javascript">
    jQuery(document).ready(function () {
        initAllTasksWidget();
    });

    htmx.onLoad(function () {
        initAllTasksWidget();
    });

    function initAllTasksWidget() {
        // Initialize status dropdown
        leantime.ticketsController.initStatusDropdown();
    }

    // Use event delegation at document level to avoid multiple bindings
    jQuery(document).off('click.allTasksStatus').on('click.allTasksStatus', '#allTasksContainer .statusDropdown .dropdown-item a', function() {
        // Wait for the status update to complete, then reload the widget
        setTimeout(function() {
            htmx.trigger('#allTasksContainer', 'refresh');
        }, 500);
    });
</script>
@endif
