<!-- resources/views/livewire/attachment-type-controller.blade.php -->
<div>
    <style>
        .type-badge {
            background: var(--primary-light);
            color: var(--primary-color);
            padding: 0.35rem 1rem;
            border-radius: 30px;
            font-size: 0.85rem;
            font-weight: 500;
        }
        
        .usage-badge {
            background: #e2e8f0;
            color: #4a5568;
            padding: 0.25rem 0.75rem;
            border-radius: 30px;
            font-size: 0.8rem;
        }
        
        [data-theme="dark"] .usage-badge {
            background: #2d3748;
            color: #cbd5e0;
        }
        
        .detail-row {
            display: flex;
            margin-bottom: 1rem;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 0.75rem;
        }
        
        .detail-label {
            font-weight: 600;
            width: 120px;
            color: var(--text-secondary);
        }
        
        .detail-value {
            flex: 1;
            color: var(--text-primary);
        }
        
        .files-list {
            max-height: 150px;
            overflow-y: auto;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 0.5rem;
        }
    </style>

    <div class="main-content" id="mainContent">
        <div class="container-fluid px-0">
            <!-- Header -->
            <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between mb-4">
                <div>
                    <h2 class="fw-semibold mb-1">📁 Attachment Types</h2>
                    <p class="text-muted mb-0">Manage different attachment types like Letters, Newspapers, etc.</p>
                </div>
                <button class="btn btn-primary mt-3 mt-md-0" data-bs-toggle="modal" data-bs-target="#typeModal" wire:click="resetForm">
                    <i class="bi bi-plus-circle me-2"></i>New Type
                </button>
            </div>

            <!-- Main Card -->
            <div class="card dashboard-card">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <div>
                        <i class="bi bi-tags me-2" style="color: var(--primary-color);"></i>
                        Registered Types
                        <span class="ms-2 small text-muted" id="recordCount">{{ count($types) }}</span>
                    </div>
                    <span wire:loading class="ms-3">
                        <span class="livewire-loading"></span>
                    </span>
                </div>
                <div class="card-body p-3 p-md-4">
                    <div class="table-responsive">
                        <table id="typesTable" class="table table-hover" style="width:100%">
                            <thead class="bg-light">
                                <tr>
                                    <th>ID</th>
                                    <th>Type Name</th>
                                    <th>Description</th>
                                    <th>Usage</th>
                                    <th>Status</th>
                                    <th>Created</th>
                                    <th class="text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse ($types as $type)
                                    <tr>
                                        <td>{{ $type->id }}</td>
                                        <td>
                                            <span class="type-badge">
                                                <i class="bi bi-tag me-1"></i>
                                                {{ $type->name }}
                                            </span>
                                        </td>
                                        <td>
                                            @if($type->description)
                                                <span class="text-truncate d-inline-block" style="max-width: 200px;" title="{{ $type->description }}">
                                                    {{ Str::limit($type->description, 30) }}
                                                </span>
                                            @else
                                                <span class="text-muted">—</span>
                                            @endif
                                        </td>
                                        <td>
                                            <span class="usage-badge">
                                                <i class="bi bi-paperclip me-1"></i>
                                                {{ $type->attachments_count }} attachment(s)
                                            </span>
                                        </td>
                                        <td>
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" 
                                                       type="checkbox" 
                                                       wire:change="toggleActive({{ $type->id }})"
                                                       wire:loading.attr="disabled"
                                                       id="active-{{ $type->id }}"
                                                       {{ $type->active ? 'checked' : '' }}>
                                                <label class="form-check-label small" for="active-{{ $type->id }}">
                                                    {{ $type->active ? 'Active' : 'Inactive' }}
                                                </label>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="small">
                                                <div>{{ $type->created_at->format('Y-m-d') }}</div>
                                                <div class="text-muted">{{ $type->createdBy->name ?? 'System' }}</div>
                                            </div>
                                        </td>
                                        <td class="text-center">
                                            <div class="btn-group btn-group-sm" role="group">
                                                <button class="btn btn-outline-info action-btn"
                                                        wire:click="view({{ $type->id }})"
                                                        data-bs-toggle="modal"
                                                        data-bs-target="#viewModal"
                                                        title="View details">
                                                    <i class="bi bi-eye"></i>
                                                </button>
                                                <button class="btn btn-outline-primary action-btn"
                                                        wire:click="edit({{ $type->id }})"
                                                        data-bs-toggle="modal"
                                                        data-bs-target="#typeModal"
                                                        title="Edit">
                                                    <i class="bi bi-pencil"></i>
                                                </button>
                                                <button class="btn btn-outline-danger action-btn"
                                                        onclick="confirmDelete({{ $type->id }}, '{{ $type->name }}', {{ $type->attachments_count }})"
                                                        title="Delete">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                @empty
                                    <tr class="text-center">
                                        <td colspan="7" class="py-5 text-muted">
                                            <i class="bi bi-tags fs-1 d-block mb-3"></i>
                                            <p class="mb-0">No attachment types found. Click "New Type" to create one.</p>
                                        </td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- View Modal -->
        <div class="modal fade" id="viewModal" tabindex="-1" aria-labelledby="viewModalLabel" aria-hidden="true" wire:ignore.self>
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="viewModalLabel">
                            <i class="bi bi-eye me-2 text-info"></i>
                            Type Details
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        @if($selectedType)
                            <div class="text-center mb-4">
                                <div class="type-badge d-inline-block px-4 py-2" style="font-size: 1.2rem;">
                                    <i class="bi bi-tag me-2"></i>
                                    {{ $selectedType->name }}
                                </div>
                            </div>
                            
                            <div class="detail-row">
                                <span class="detail-label">Description:</span>
                                <span class="detail-value">{{ $selectedType->description ?: 'No description' }}</span>
                            </div>
                            
                            <div class="detail-row">
                                <span class="detail-label">Usage:</span>
                                <span class="detail-value">
                                    <span class="usage-badge">
                                        {{ $selectedType->attachments_count }} attachment(s)
                                    </span>
                                </span>
                            </div>
                            
                            @if($selectedType->attachments_count > 0)
                            <div class="detail-row">
                                <span class="detail-label">Attachments:</span>
                                <span class="detail-value">
                                    <div class="files-list">
                                        @foreach($selectedType->attachments as $attachment)
                                            <div class="d-flex align-items-center mb-2">
                                                <i class="bi bi-file-earmark me-2 text-primary"></i>
                                                <span class="small">{{ $attachment->file->name ?? 'N/A' }}</span>
                                            </div>
                                        @endforeach
                                    </div>
                                </span>
                            </div>
                            @endif
                            
                            <div class="detail-row">
                                <span class="detail-label">Status:</span>
                                <span class="detail-value">
                                    @if($selectedType->active)
                                        <span class="badge-success"><i class="bi bi-check-circle me-1"></i>Active</span>
                                    @else
                                        <span class="badge-danger"><i class="bi bi-x-circle me-1"></i>Inactive</span>
                                    @endif
                                </span>
                            </div>
                            
                            <div class="detail-row">
                                <span class="detail-label">Created By:</span>
                                <span class="detail-value">{{ $selectedType->createdBy->name ?? 'System' }}</span>
                            </div>
                            
                            <div class="detail-row">
                                <span class="detail-label">Created At:</span>
                                <span class="detail-value">{{ $selectedType->created_at->format('Y-m-d H:i') }}</span>
                            </div>
                        @else
                            <div class="text-center py-4">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                            </div>
                        @endif
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                        @if($selectedType)
                            <button type="button" class="btn btn-primary" 
                                    wire:click="edit({{ $selectedType->id }})"
                                    data-bs-toggle="modal"
                                    data-bs-target="#typeModal"
                                    data-bs-dismiss="modal">
                                <i class="bi bi-pencil me-2"></i>Edit
                            </button>
                        @endif
                    </div>
                </div>
            </div>
        </div>

        <!-- Add/Edit Modal -->
        <div class="modal fade" id="typeModal" tabindex="-1" aria-labelledby="typeModalLabel" aria-hidden="true" wire:ignore.self>
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="typeModalLabel">
                            <i class="bi {{ $editMode ? 'bi-pencil-square' : 'bi-plus-circle' }} me-2 text-primary"></i>
                            {{ $editMode ? 'Edit Type' : 'New Type' }}
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <form wire:submit="{{ $editMode ? 'update' : 'store' }}">
                        <div class="modal-body">
                            <div class="row g-3">
                                <!-- Name -->
                                <div class="col-12">
                                    <label class="form-label fw-medium">
                                        Type Name <span class="text-danger">*</span>
                                    </label>
                                    <input type="text"
                                           class="form-control @error('name') is-invalid @enderror"
                                           wire:model="name"
                                           placeholder="e.g., Letter, Newspaper, Report, ...">
                                    @error('name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <!-- Description -->
                                <div class="col-12">
                                    <label class="form-label fw-medium">Description</label>
                                    <textarea class="form-control @error('description') is-invalid @enderror"
                                              wire:model="description"
                                              rows="3"
                                              placeholder="Describe this type..."></textarea>
                                    @error('description')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <!-- Status -->
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input"
                                               type="checkbox"
                                               wire:model="active"
                                               id="activeStatus"
                                               {{ $active ? 'checked' : '' }}>
                                        <label class="form-check-label fw-medium" for="activeStatus">
                                            {{ $active ? 'Active' : 'Inactive' }}
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="modal-footer">
                            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary" wire:loading.attr="disabled">
                                <span wire:loading.remove>
                                    <i class="bi {{ $editMode ? 'bi-check-circle' : 'bi-save' }} me-2"></i>
                                    {{ $editMode ? 'Update' : 'Save' }}
                                </span>
                                <span wire:loading>
                                    <span class="spinner-border spinner-border-sm me-2" role="status"></span>
                                    Saving...
                                </span>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        function confirmDelete(typeId, typeName, attachmentsCount) {
            if (attachmentsCount > 0) {
                Swal.fire({
                    title: 'Cannot Delete',
                    html: `Type <strong>"${typeName}"</strong> has ${attachmentsCount} attachment(s).<br><br>Please remove the attachments first.`,
                    icon: 'error',
                    confirmButtonColor: '#4361ee',
                    confirmButtonText: 'OK',
                    background: 'var(--card-bg)',
                    color: 'var(--text-primary)'
                });
                return;
            }
            
            Swal.fire({
                title: 'Are you sure?',
                html: `Are you sure you want to delete type <strong>"${typeName}"</strong>?<br><br>This action cannot be undone.`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ef4444',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'Cancel',
                background: 'var(--card-bg)',
                color: 'var(--text-primary)',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    @this.delete(typeId);
                }
            });
        }

        // Make sure Livewire is loaded
        document.addEventListener('livewire:init', function() {
            console.log('Livewire initialized');
            
            // Listen for events
            Livewire.on('close-modal', () => {
                console.log('Closing modal');
                $('#typeModal').modal('hide');
                $('.modal-backdrop').remove();
                $('body').removeClass('modal-open');
            });

            Livewire.on('show-success', (data) => {
                console.log('Success:', data);
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: data.message || data[0] || 'Operation successful!',
                    timer: 2000,
                    showConfirmButton: false,
                    background: 'var(--card-bg)',
                    color: 'var(--text-primary)'
                });
            });

            Livewire.on('show-error', (data) => {
                console.log('Error:', data);
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: data[0] || 'An error occurred',
                    background: 'var(--card-bg)',
                    color: 'var(--text-primary)'
                });
            });

            Livewire.on('refresh-table', () => {
                console.log('Refreshing table');
                location.reload();
            });
        });

        // Clean up modal backdrop when modal is hidden
        $(document).ready(function() {
            $('#typeModal').on('hidden.bs.modal', function() {
                $('.modal-backdrop').remove();
                $('body').removeClass('modal-open');
                $('body').css('overflow', 'auto');
            });

            $('#viewModal').on('hidden.bs.modal', function() {
                $('.modal-backdrop').remove();
                $('body').removeClass('modal-open');
                $('body').css('overflow', 'auto');
            });
        });
    </script>
</div>