<div class="table-scroller">
    <table class="table ticket-table">
        <thead>
            <tr>
                <th class="ticket-col">@lang('Ticket')</th>
                <th class="requester-col">@lang('Requester')</th>
                <th class="status-col">@lang('Status')</th>
                <th class="last-message-col">@lang('Last Message')</th>
                <th class="action-col"></th>
            </tr>
        </thead>
        <tbody>
            @forelse ($supportTickets as $index => $ticket)
                <tr data-ticket="{{ $ticket->ticket_number }}" class="ticketDetails
                    @if($ticket->ticketStatus->is_awaiting  && $ticket->assign_staff_id > 0) assign_ticket @elseif ($ticket->ticketStatus->is_awaiting) awaiting_ticket @endif"
                    >
                    <td class="ticket-col">
                        <div class="ticket-board">
                            <div class="ticket-board-content">
                                <p class="ticket-board-title">
                                    <span class="animated-circle priorityName" data-hsl_color="{{ json_encode($ticket->priority->converted_color) }}">
                                    </span>
                                    {{ __($ticket->subject) }}
                                </p>
                                <div class="ticket-board-list">
                                    <p class="ticket-board-type">
                                        {{ __($ticket->department?->name) }}
                                    </p>
                                    <p class="ticket-board-id fw-bold">
                                        #{{ $ticket->ticket_number }}
                                    </p>
                                    @if ($ticket->admin)
                                        <a href="{{ route('admin.agent.overview', $ticket->admin->id) }}" class="ticket-board-assign text--base">
                                            <i class="fa fa-user-check"></i>
                                            {{ $ticket->admin->name }}
                                        </a>
                                    @endif

                                    @if (count($ticket->tags))
                                        <div class="ticket-board-tags">
                                            @foreach ($ticket->tags as $tag)
                                                <span class="tag-style tagStyle" data-converted_color="{{ json_encode($tag->converted_color) }}">{{ __($tag->name) }}</span>
                                            @endforeach
                                        </div>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </td>
                    <td class="requester-col">
                        <div class="mini-profile">
                            <div class="mini-profile-img">
                                <img src="{{ getImage(getFilePath('userProfile') . '/' . $ticket->user->image, avatar: true) }}" alt="image">
                            </div>
                            <div class="mini-profile-content">
                                <a href="{{ route('admin.customer.overview', $ticket->user_id) }}" class="name">{{ $ticket->user->fullname }}</a>
                                <p class="email">{{ $ticket->user->email }}</p>
                            </div>
                        </div>
                    </td>
                    <td class="status-col">
                        <span class="badge statusName" data-ticket_number="{{ $ticket->ticket_number }}" data-hsl_color="{{ json_encode($ticket->ticketStatus->converted_color) }}">{{ __($ticket->ticketStatus->name) }}</span>
                    </td>
                    <td class="last-message-col">

                        @php
                            $lastReply = $ticket->replies->last();
                        @endphp

                        @if ($lastReply)
                            {{ diffForHumans($lastReply->created_at) }}
                        @else
                            ----
                        @endif

                    </td>
                    <td class="action-col">
                        <div class="dropdown ticket-dropdown">
                            <button class="ticket-dropdown-btn" data-bs-toggle="dropdown" aria-expanded="false" data-bs-auto-close="outside">
                                <i class="fa fa-ellipsis-v"></i>
                            </button>
                            <div class="dropdown-menu ticket-dropdown-body">
                                <div class="dropdown-menu-block">
                                    <div class="accordion ticket-accordion ticketParent" id="ticket-parent{{ $index }}" data-ticket="{{ $ticket->id }}">
                                        <div class="accordion-item">
                                            <h2 class="accordion-header">
                                                <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#ticket-actions" aria-expanded="true" aria-controls="ticket-actions">
                                                    @lang('Set Priority')
                                                </button>
                                            </h2>
                                            <div id="ticket-actions" class="accordion-collapse collapse show" data-bs-parent="#ticket-parent{{ $index }}">
                                                <div class="accordion-body">
                                                    @foreach ($priorities as $priority)
                                                        <div class="ticket-dropdown-item">
                                                            <span class="animated-circle" data-hsl_color="{{ json_encode($priority->converted_color) }}"></span>
                                                            <p class="title updateTicket" data-priority="{{ $priority->id }}">
                                                                {{ __($priority->name) }}</p>
                                                        </div>
                                                    @endforeach
                                                </div>
                                            </div>
                                        </div>
                                        <div class="accordion-item">
                                            <h2 class="accordion-header">
                                                <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#ticket-status" aria-expanded="false" aria-controls="ticket-status">
                                                    @lang('Set Status')
                                                </button>
                                            </h2>
                                            <div id="ticket-status" class="accordion-collapse collapse" data-bs-parent="#ticket-parent{{ $index }}">
                                                <div class="accordion-body">
                                                    @foreach ($statuses as $status)
                                                        <div class="ticket-dropdown-item">
                                                            <p class="title statusColor updateTicket" data-status="{{ $status->id }}" data-color="{{ $status->color }}">
                                                                {{ __($status->name) }}</p>
                                                        </div>
                                                    @endforeach
                                                </div>
                                            </div>
                                        </div>
                                        <div class="accordion-item">
                                            <h2 class="accordion-header">
                                                <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#ticket-folders" aria-expanded="false" aria-controls="ticket-folders">
                                                    @lang('Folders')
                                                </button>
                                            </h2>
                                            <div id="ticket-folders" class="accordion-collapse collapse" data-bs-parent="#ticket-parent{{ $index }}">
                                                <div class="accordion-body">
                                                    @if (in_array(request()->folder, ['draft', 'spam', 'trash']))
                                                        <div class="ticket-dropdown-item">
                                                            <p class="title updateTicket" data-folder="{{ Status::TICKET_PRIMARY }}">
                                                                @lang('Move to Primary')</p>
                                                        </div>
                                                    @endif
                                                    @if (request()->folder != 'draft')
                                                        <div class="ticket-dropdown-item">
                                                            <p class="title updateTicket" data-folder="{{ Status::TICKET_DRAFT }}">
                                                                @lang('Move to Draft')</p>
                                                        </div>
                                                    @endif
                                                    @if (request()->folder != 'spam')
                                                        <div class="ticket-dropdown-item">
                                                            <p class="title updateTicket" data-folder="{{ Status::TICKET_SPAM }}">
                                                                @lang('Move to Spam')</p>
                                                        </div>
                                                    @endif
                                                    @if (request()->folder != 'trash')
                                                        <div class="ticket-dropdown-item">
                                                            <p class="title updateTicket" data-folder="{{ Status::TICKET_TRASH }}">
                                                                @lang('Move to Trash')</p>
                                                        </div>
                                                    @endif
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
            @empty
                <tr>
                    <td colspan="100%">
                        <x-empty-message message="No ticket found" />
                    </td>
                </tr>
            @endforelse
        </tbody>
    </table>
</div>

@if ($supportTickets->hasPages())
    <div class="pagination-wrapper">
        {{ paginateLinks($supportTickets) }}
    </div>
@endif

<div id="confirmationModal" class="modal custom--modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">@lang('Confirmation Alert!')</h5>
                <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                    <i class="las la-times"></i>
                </button>
            </div>
            <form method="POST" class="confirmationForm">
                @csrf
                <input type="hidden" name="list_page" value="1">
                <div class="modal-body">
                    <p class="question"></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn--dark btn--sm" data-bs-dismiss="modal">@lang('No')</button>
                    <button type="submit" class="btn btn--primary btn--sm" data-bs-dismiss="modal">@lang('Yes')</button>
                </div>
            </form>
        </div>
    </div>
</div>


@push('script')
    <script>
        (function($) {
            "use strict";
            $('.animated-circle[data-hsl_color]').each(function() {
                const jsonString = $(this).attr('data-hsl_color');
                try {
                    const hsl = JSON.parse(jsonString);
                    const hslString = `${hsl.h} ${hsl.s}% ${hsl.l}%`;
                    $(this).css('--circle-color', hslString);
                } catch (e) {
                    console.error('Invalid HSL data:', jsonString);
                }
            });

            $('.statusColor').each(function() {
                let color = $(this).data('color');
                $(this).css('color', '#' + color);
            });

            $('.updateTicket').on('click', function() {
                let modal = $('#confirmationModal');
                let action = `{{ route('admin.ticket.update', '') }}`;

                let priority = $(this).data('priority');
                let status = $(this).data('status');
                let folder = $(this).data('folder');

                let ticketId = $(this).closest('.ticketParent').data('ticket');

                let question = '';
                if (priority) {
                    question = `@lang('Are you sure to change priority to') <b>${$(this).text().trim()}</b>?`;
                } else if (status) {
                    question = `@lang('Are you sure to change status to') <b>${$(this).text().trim()}</b>?`;
                } else if (folder) {
                    let lastWord = $(this).text().trim().split(' ').pop();
                    question = `@lang('Are you sure to move ticket to') <b>${lastWord}</b>?`;
                }

                modal.find('form').attr('action', action + '/' + ticketId);
                modal.find('form').find('input[name="priority"]').remove();
                modal.find('form').find('input[name="status"]').remove();
                modal.find('form').find('input[name="folder"]').remove();

                if (priority) {
                    modal.find('form').append(`<input type="hidden" name="priority" value="${priority}">`);
                }
                if (status) {
                    modal.find('form').append(`<input type="hidden" name="status" value="${status}">`);
                }
                if (folder) {
                    modal.find('form').append(`<input type="hidden" name="folder" value="${folder}">`);
                }

                modal.find('.question').html(question);
                modal.modal('show');
            });

            $('.confirmationForm').on('submit', function(e) {
                e.preventDefault();
                var form = $(this);
                var action = form.attr('action');
                var data = form.serialize();

                $.ajax({
                    url: action,
                    method: 'POST',
                    data: data,
                    success: function(response) {
                        if (response.status === 'error') {
                            notify('error', response.message);
                            return;
                        }
                        notify('success', response.message);

                        if (response.data && response.data.status) {
                            const tickerNumber = response.data.ticket.ticket_number;
                            const hslColor = response.data.status.converted_color;
                            const $badge = $(`.statusName[data-ticket_number="${tickerNumber}"]`);
                            $badge.text(response.data.status.name);
                            $badge.attr('data-hsl_color', JSON.stringify(hslColor));
                            const hslString = `${hslColor.h} ${hslColor.s}% ${hslColor.l}%`;
                            $badge.css('--badge-color', hslString);
                        }

                        if (response.data && response.data.folder) {
                            const tickerNumber = response.data.ticket.ticket_number;
                            const $badge = $(`.statusName[data-ticket_number="${tickerNumber}"]`);
                            $badge.closest('tr').remove();
                        }
                    }
                });
            });

            let route = `{{ route('admin.ticket.details', '') }}`;

            $('.ticketDetails').on('click', function(e) {
                if ($(e.target).closest('.action-col').length) {
                    return;
                }
                let ticketNumber = $(this).data('ticket');
                window.location.href = route + '/' + ticketNumber;
            });

            $('.statusName').each(function() {
                const jsonString = $(this).attr('data-hsl_color');
                try {
                    const hsl = JSON.parse(jsonString);
                    const hslString = `${hsl.h} ${hsl.s}% ${hsl.l}%`;
                    $(this).css('--badge-color', hslString);
                } catch (e) {
                    console.error('Invalid HSL data:', jsonString);
                }
            });

            $('.tagStyle').each(function() {
                const jsonString = $(this).attr('data-converted_color');
                try {
                    const hsl = JSON.parse(jsonString);
                    const hslString = `${hsl.h} ${hsl.s}% ${hsl.l}%`;
                    $(this).css('--tag-color', hslString);
                } catch (e) {
                    console.error('Invalid HSL data:', jsonString);
                }
            });

            $('.listTable tr.awaiting_ticket').first().find('td').css('background-color', 'hsl(var(--danger) / .1) !important');
            $('.listTable tr.awaiting_ticket').eq(1).find('td').css('background-color', 'hsl(var(--danger) / 0.085) !important');
            $('.listTable tr.awaiting_ticket').eq(2).find('td').css('background-color', 'hsl(var(--danger) / 0.07) !important');
            $('.listTable tr.awaiting_ticket').eq(3).find('td').css('background-color', 'hsl(var(--danger) / 0.05) !important');
            
        })(jQuery);
    </script>
@endpush
