@extends('layouts.admin-simple')

@section('title', 'Item Types')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item">Items</li>
    <li class="breadcrumb-item active">Item Types</li>
@endsection

@section('page-title')
    <div class="d-flex justify-content-between align-items-center w-100">
        <div class="page-title-left">
            <h3 class="mb-1">Item Types</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Manage item type categories and classifications</p>
        </div>
        @can('warehouse.items.create')
        <div class="page-actions-right d-flex align-items-center">
            <button type="button" onclick="showAddItemTypeModal()" class="btn btn-sm btn-primary" title="Add new item type">
                <i class="material-icons mr-1" style="font-size: 16px;">add</i>
                New Item Type
            </button>
        </div>
        @endcan
    </div>
@endsection

@section('content')
    <!-- Item Types Table -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0 d-flex align-items-center">
                <i class="material-icons mr-2">category</i>
                Item Types List
            </h5>
            <div class="d-flex align-items-center">
                <label class="text-muted mr-2" style="font-size: 14px;">Show:</label>
                <select id="entries-per-page" class="form-control form-control-sm" style="width: auto;">
                    <option value="10">10</option>
                    <option value="25">25</option>
                    <option value="50">50</option>
                    <option value="100">100</option>
                </select>
                <span class="text-muted ml-2" style="font-size: 14px;">entries</span>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table id="item-types-table" class="table table-hover">
                    <thead>
                        <tr>
                            <th>Type Name</th>
                            <th>Description</th>
                            <th>Status</th>
                            <th>Items Count</th>
                            <th>Created Date</th>
                            <th class="text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Data will be populated by DataTables -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add Item Type Modal -->
    <div class="modal fade" id="addItemTypeModal" tabindex="-1" role="dialog" aria-labelledby="addItemTypeModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addItemTypeModalLabel">
                        <i class="material-icons mr-2">category</i>
                        Add New Item Type
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="addItemTypeForm">
                        @csrf
                        <div class="form-group">
                            <label for="type_name">Type Name <span class="text-danger">*</span></label>
                            <input type="text" name="type_name" id="type_name" class="form-control" required>
                            <div class="invalid-feedback"></div>
                        </div>
                        <div class="form-group">
                            <label for="description">Description</label>
                            <textarea name="description" id="description" class="form-control" rows="3" placeholder="Optional description of the item type"></textarea>
                            <div class="invalid-feedback"></div>
                        </div>
                        <div class="form-group">
                            <label for="status">Status <span class="text-danger">*</span></label>
                            <select name="status" id="status" class="form-control" required>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                            <div class="invalid-feedback"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" onclick="saveItemType()" class="btn btn-primary">
                        <i class="material-icons mr-1" style="font-size: 16px;">save</i>
                        Save Item Type
                    </button>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('styles')
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet" />
    <style>
        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
            line-height: 1.5;
            border-radius: 4px;
        }

        .btn-sm .material-icons {
            font-size: 16px !important;
        }

        .table th {
            border-top: none;
            font-weight: 600;
            color: #495057;
            background-color: #f8f9fa;
        }

        .table-responsive {
            border-radius: 0.375rem;
        }

        .modal,
        #addItemTypeModal {
            z-index: 99999999999 !important;
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            width: 100% !important;
            height: 100% !important;
        }

        .modal-backdrop,
        .modal-backdrop.fade,
        .modal-backdrop.show {
            z-index: 99999999999 !important;
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            width: 100% !important;
            height: 100% !important;
        }

        .modal-dialog {
            z-index: 1000000 !important;
            position: relative !important;
        }

        .modal-content {
            z-index: 1000001 !important;
            position: relative !important;
        }

        /* Force modal to appear above everything */
        .modal.show,
        .modal.fade.show {
            display: block !important;
            z-index: 999999 !important;
            opacity: 1 !important;
        }

        /* Override any potential conflicts */
        .modal * {
            position: relative;
        }

        /* Ensure body doesn't scroll when modal is open */
        body.modal-open {
            overflow: hidden !important;
        }

        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        /* SweetAlert2 custom button styling */
        .swal2-actions {
            gap: 12px !important;
        }

        .swal2-actions .btn {
            min-height: 38px !important;
            height: 38px !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
        }

        .swal2-actions .btn:focus,
        .swal2-actions .btn:focus-visible {
            outline: none !important;
            box-shadow: none !important;
        }

        .swal2-actions .btn:active {
            transform: scale(0.98);
        }
    </style>
@endpush

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        let itemTypesTable;

        let itemTypesInitialized = false;

        function initializeItemTypesPage() {
            if (itemTypesInitialized) {
                console.log('⚠️ Item Types page already initialized, skipping...');
                return;
            }

            console.log('🔧 Initializing item types page...');
            initializeDataTable();

            // Entries per page change handler
            $('#entries-per-page').change(function() {
                if (itemTypesTable) {
                    itemTypesTable.page.len($(this).val()).draw();
                }
            });


            itemTypesInitialized = true;
        }

        // Listen for the custom dataTablesReady event
        window.addEventListener('dataTablesReady', function() {
            console.log('🎉 Item Types: DataTables ready event received!');
            initializeItemTypesPage();
        });

        $(document).ready(function() {
            console.log('📄 Item Types page ready, checking if DataTables is available...');

            setTimeout(function() {
                if (typeof $ !== 'undefined' && typeof $.fn.DataTable !== 'undefined' && !itemTypesInitialized) {
                    console.log('✅ Item Types: DataTables found on document ready, initializing...');
                    initializeItemTypesPage();
                } else if (!itemTypesInitialized) {
                    console.log('⏳ Item Types: DataTables not ready yet, waiting for dataTablesReady event...');
                }
            }, 1000);
        });

        function initializeDataTable() {
            if (typeof $.fn.DataTable === 'undefined') {
                console.error('DataTables library not loaded');
                return;
            }

            itemTypesTable = $('#item-types-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: '{{ route("warehouse.item-types.index") }}',
                    type: 'GET'
                },
                columns: [
                    {
                        data: 'type_name',
                        name: 'type_name',
                        render: function(data, type, row) {
                            return `
                                <div class="d-flex align-items-center">
                                    <div class="mr-3">
                                        <div class="bg-primary text-white d-flex align-items-center justify-content-center rounded-circle" style="width: 40px; height: 40px;">
                                            <i class="material-icons" style="font-size: 20px;">category</i>
                                        </div>
                                    </div>
                                    <div>
                                        <div class="font-weight-medium">${data}</div>
                                    </div>
                                </div>
                            `;
                        }
                    },
                    {
                        data: 'description',
                        name: 'description',
                        render: function(data, type, row) {
                            return data === '-' ? '<span class="text-muted">No description</span>' : data;
                        }
                    },
                    {
                        data: 'status',
                        name: 'status',
                        render: function(data, type, row) {
                            const badgeClass = data === 'active' ? 'badge-success' : 'badge-danger';
                            return `<span class="badge ${badgeClass}">${data.charAt(0).toUpperCase() + data.slice(1)}</span>`;
                        }
                    },
                    {
                        data: 'items_count',
                        name: 'items_count',
                        render: function(data, type, row) {
                            return `<span class="badge badge-info">${data} items</span>`;
                        }
                    },
                    {
                        data: 'created_at',
                        name: 'created_at',
                        render: function(data, type, row) {
                            return `
                                <div>
                                    <div class="small">${data}</div>
                                    <div class="small text-muted">Created</div>
                                </div>
                            `;
                        }
                    },
                    {
                        data: null,
                        name: 'actions',
                        orderable: false,
                        searchable: false,
                        render: function(data, type, row) {
                            return `
                                <div class="btn-group" role="group">
                                    <a href="{{ url('warehouse/item-types') }}/${row.id}" class="btn btn-sm btn-outline-primary" title="View Item Type">
                                        <i class="material-icons" style="font-size: 16px;">visibility</i>
                                    </a>
                                    @can('warehouse.items.edit')
                                    <a href="{{ url('warehouse/item-types') }}/${row.id}/edit" class="btn btn-sm btn-outline-success" title="Edit Item Type">
                                        <i class="material-icons" style="font-size: 16px;">edit</i>
                                    </a>
                                    @endcan
                                    @can('warehouse.items.delete')
                                    <button onclick="deleteItemType(${row.id}, '${row.type_name}')" class="btn btn-sm btn-outline-danger" title="Delete Item Type">
                                        <i class="material-icons" style="font-size: 16px;">delete</i>
                                    </button>
                                    @endcan
                                </div>
                            `;
                        }
                    }
                ],
                order: [[4, 'desc']],
                pageLength: 25,
                lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
                language: {
                    processing: '<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div></div>',
                    emptyTable: 'No item types found',
                    zeroRecords: 'No matching item types found'
                },
                drawCallback: function(settings) {
                    $('#entries-per-page').val(settings._iDisplayLength);
                }
            });
        }

        function deleteItemType(id, typeName) {
            Swal.fire({
                title: 'Delete Item Type?',
                html: `Are you sure you want to delete <strong>"${typeName}"</strong>?<br><small class="text-muted">This action cannot be undone.</small>`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: '<i class="material-icons" style="font-size: 16px; vertical-align: middle;">delete</i> Yes, Delete',
                cancelButtonText: '<i class="material-icons" style="font-size: 16px; vertical-align: middle;">cancel</i> Cancel',
                reverseButtons: true,
                focusCancel: true,
                customClass: {
                    confirmButton: 'btn btn-danger px-4',
                    cancelButton: 'btn btn-secondary px-4'
                },
                buttonsStyling: false
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Deleting...',
                        text: 'Please wait while we delete the item type.',
                        icon: 'info',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        showConfirmButton: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });

                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                    });

                    $.ajax({
                        url: `{{ url('warehouse/item-types') }}/${id}`,
                        type: 'DELETE',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    title: 'Deleted!',
                                    text: 'Item type deleted successfully',
                                    icon: 'success',
                                    timer: 2000,
                                    showConfirmButton: false
                                });
                                itemTypesTable.draw();
                            } else {
                                Swal.fire({
                                    title: 'Error!',
                                    text: response.message || 'Failed to delete item type',
                                    icon: 'error',
                                    confirmButtonText: 'OK',
                                    customClass: {
                                        confirmButton: 'btn btn-primary'
                                    },
                                    buttonsStyling: false
                                });
                            }
                        },
                        error: function(xhr) {
                            Swal.fire({
                                title: 'Error!',
                                text: 'Error deleting item type. Please try again.',
                                icon: 'error',
                                confirmButtonText: 'OK',
                                customClass: {
                                    confirmButton: 'btn btn-primary'
                                },
                                buttonsStyling: false
                            });
                        }
                    });
                }
            });
        }

        function showAddItemTypeModal() {
            // Clear form and validation errors
            $('#addItemTypeForm')[0].reset();
            clearValidationErrors();

            // Remove any existing event handlers to prevent stacking
            $('#addItemTypeModal').off('shown.bs.modal');
            $('#addItemTypeModal').off('hidden.bs.modal');

            // Force very high z-index before showing
            $('#addItemTypeModal').css({
                'z-index': 99999999999,
                'position': 'fixed',
                'top': '0',
                'left': '0',
                'width': '100%',
                'height': '100%'
            });

            // Show modal
            $('#addItemTypeModal').modal({
                backdrop: true,
                keyboard: true,
                show: true
            });

            // Aggressively force z-index after modal is shown (use .one() for single execution)
            $('#addItemTypeModal').one('shown.bs.modal', function() {
                $(this).css({
                    'z-index': 99999999999,
                    'position': 'fixed'
                });
                $('.modal-backdrop').css({
                    'z-index': 99999999999,
                    'position': 'fixed'
                });
                $('.modal-dialog').css({
                    'z-index': 1000000,
                    'position': 'relative'
                });
                $('.modal-content').css({
                    'z-index': 1000001,
                    'position': 'relative'
                });

                // Force body class and hide overlapping elements
                $('body').addClass('modal-open').css('overflow', 'hidden');
                $('.sidebar, .main-sidebar, .navbar, .main-header, .content-wrapper, .overlay, .page-overlay, .loading-overlay').css('z-index', '1');

                // Move modal to body if it's not already there
                if (!$('#addItemTypeModal').parent().is('body')) {
                    $('#addItemTypeModal').appendTo('body');
                }
            });

            // Cleanup when modal is hidden (use .one() for single execution)
            $('#addItemTypeModal').one('hidden.bs.modal', function() {
                $('body').removeClass('modal-open').css('overflow', '');
                $('.sidebar, .main-sidebar, .navbar, .main-header, .content-wrapper, .overlay, .page-overlay, .loading-overlay').css('z-index', '');

                // Remove inline styles to reset for next use
                $(this).removeAttr('style');
                $('.modal-backdrop').removeAttr('style');
                $('.modal-dialog').removeAttr('style');
                $('.modal-content').removeAttr('style');
            });
        }

        function saveItemType() {
            const form = $('#addItemTypeForm')[0];
            const formData = new FormData(form);

            clearValidationErrors();

            const saveBtn = $('button[onclick="saveItemType()"]');
            const originalHtml = saveBtn.html();
            saveBtn.prop('disabled', true);
            saveBtn.html('<i class="material-icons mr-1" style="font-size: 16px; animation: spin 1s linear infinite;">sync</i>Saving...');

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                url: '{{ route("warehouse.item-types.store") }}',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        // Properly hide modal and cleanup
                        $('#addItemTypeModal').modal('hide');

                        // Force cleanup of modal elements
                        setTimeout(function() {
                            $('.modal-backdrop').remove();
                            $('body').removeClass('modal-open').css('overflow', '');

                            // Reset all modal-related styles
                            $('#addItemTypeModal').removeAttr('style');
                            $('.modal-dialog').removeAttr('style');
                            $('.modal-content').removeAttr('style');
                            $('.sidebar, .main-sidebar, .navbar, .main-header, .content-wrapper, .overlay, .page-overlay, .loading-overlay').css('z-index', '');
                        }, 300);

                        // Refresh table
                        itemTypesTable.draw();
                        showAlert('Item type added successfully!', 'success');
                    } else {
                        showAlert(response.message || 'Error adding item type', 'error');
                    }
                },
                error: function(xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors;
                        displayValidationErrors(errors);
                    } else {
                        showAlert('Error adding item type. Please try again.', 'error');
                    }
                },
                complete: function() {
                    saveBtn.prop('disabled', false);
                    saveBtn.html(originalHtml);
                }
            });
        }

        function clearValidationErrors() {
            $('.form-control').removeClass('is-invalid');
            $('.invalid-feedback').text('');
        }

        function displayValidationErrors(errors) {
            $.each(errors, function(field, messages) {
                const input = $(`[name="${field}"]`);
                input.addClass('is-invalid');
                input.siblings('.invalid-feedback').text(messages[0]);
            });
        }

        function showAlert(message, type) {
            const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
            const alert = `
                <div class="alert ${alertClass} alert-dismissible fade show position-fixed" style="top: 20px; right: 20px; z-index: 9999;">
                    ${message}
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                </div>
            `;
            $('body').append(alert);
            setTimeout(() => $('.alert').alert('close'), 5000);
        }
    </script>
@endpush