@extends('layouts.admin')

@section('title', 'Units')

@section('page-title', 'Units')

@section('content')
<div class="max-w-[1400px] mx-auto">
    <!-- Header Section -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <h1 class="text-2xl font-bold text-gray-900">Units</h1>
        <div class="flex items-center gap-3">
            <button onclick="openUnitModal()" class="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium shadow-lg shadow-primary/30 hover:bg-blue-600 transition-colors">
                <span class="material-symbols-outlined text-lg">add</span>
                <span>New Unit</span>
            </button>
            <select class="px-3 py-2 text-sm border border-gray-200 rounded-lg bg-white text-gray-700 focus:outline-none focus:ring-1 focus:ring-primary">
                <option>10 / page</option>
                <option>25 / page</option>
                <option>50 / page</option>
                <option>100 / page</option>
            </select>
        </div>
    </div>

    <!-- Search Bar -->
    <div class="mb-4">
        <input type="text" placeholder="Search..." class="w-full max-w-md h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary">
    </div>

    <!-- Units Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-left">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">#</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">UNIT NAME</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">SHORT NAME</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">STATUS</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right">ACTION</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    @forelse($units ?? [] as $index => $unit)
                    <tr class="hover:bg-gray-50 transition-colors">
                        <td class="py-4 px-6 text-sm text-gray-600">{{ ($units->currentPage() - 1) * $units->perPage() + $index + 1 }}</td>
                        <td class="py-4 px-6 text-sm font-medium text-gray-900">{{ $unit->name }}</td>
                        <td class="py-4 px-6 text-sm text-gray-600">{{ $unit->short_name }}</td>
                        <td class="py-4 px-6">
                            <label class="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in cursor-pointer">
                                <input type="checkbox" 
                                       class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer checked:right-0 checked:border-primary transition-all duration-300" 
                                       data-unit-id="{{ $unit->id }}"
                                       {{ $unit->is_active ? 'checked' : '' }}
                                       onchange="toggleUnitStatus({{ $unit->id }}, this.checked, this)">
                                <span class="toggle-label block overflow-hidden h-5 rounded-full bg-gray-300 cursor-pointer transition-colors duration-300 {{ $unit->is_active ? 'bg-primary' : '' }}"></span>
                            </label>
                            <span class="ml-3 text-sm font-medium text-gray-700">
                                {{ $unit->is_active ? 'Active' : 'Inactive' }}
                            </span>
                        </td>
                        <td class="py-4 px-6 text-right">
                            <div class="flex items-center justify-end gap-2">
                                <button onclick="editUnit({{ $unit->id }})" class="p-2 text-gray-500 hover:text-primary hover:bg-gray-100 rounded-lg transition-colors">
                                    <span class="material-symbols-outlined text-lg">edit</span>
                                </button>
                                <button onclick="deleteUnit({{ $unit->id }})" class="p-2 text-gray-500 hover:text-red-500 hover:bg-gray-100 rounded-lg transition-colors">
                                    <span class="material-symbols-outlined text-lg">delete</span>
                                </button>
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="5" class="py-12 px-6 text-center text-gray-500">
                            <span class="material-symbols-outlined text-4xl mb-2 block">straighten</span>
                            <p>No units found</p>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        @if(isset($units) && $units->hasPages())
        <div class="px-6 py-4 border-t border-gray-200">
            {{ $units->links() }}
        </div>
        @endif
    </div>
</div>

<!-- Add Unit Modal -->
<div id="unitModal" data-admin-modal class="fixed inset-0 z-50 hidden">
    <div class="absolute inset-0 bg-black/50 backdrop-blur-sm" onclick="closeUnitModal()"></div>
    <div class="absolute right-0 top-0 h-full w-full max-w-md bg-white shadow-2xl transform transition-transform duration-300">
        <div class="flex flex-col h-full">
            <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-bold text-gray-900" id="unitModalTitle">Add New Unit</h2>
                <button onclick="closeUnitModal()" class="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <form id="unitForm" method="POST" class="flex-1 overflow-y-auto">
                @csrf
                <input type="hidden" id="unitId" name="id">
                <div class="p-6 space-y-6">
                    <div>
                        <label for="unitName" class="block text-sm font-medium text-gray-700 mb-2">
                            Unit Name <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="unitName" name="name" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="e.g., Kilogram">
                    </div>
                    <div>
                        <label for="unitShortName" class="block text-sm font-medium text-gray-700 mb-2">
                            Short Name <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="unitShortName" name="short_name" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="e.g., kg">
                    </div>
                </div>
                <div class="px-6 py-4 border-t border-gray-200 flex justify-end gap-3">
                    <button type="button" onclick="closeUnitModal()" class="px-5 py-2.5 rounded-lg border border-gray-300 text-gray-700 font-medium hover:bg-gray-50 transition-colors">
                        Cancel
                    </button>
                    <button type="submit" class="px-5 py-2.5 rounded-lg bg-primary text-white font-medium hover:bg-blue-600 transition-colors">
                        Save Unit
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('scripts')
<script>
    let currentUnitId = null;

    function openUnitModal(id = null) {
        currentUnitId = id;
        const modal = document.getElementById('unitModal');
        const form = document.getElementById('unitForm');
        const title = document.getElementById('unitModalTitle');
        
        modal.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
        
        if (id) {
            title.textContent = 'Edit Unit';
            form.action = `{{ route('admin.products.units.index') }}/${id}`;
            
            // Fetch unit data
            fetch(`{{ route('admin.products.units.index') }}/${id}`, {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.unit) {
                    document.getElementById('unitId').value = data.unit.id;
                    document.getElementById('unitName').value = data.unit.name;
                    document.getElementById('unitShortName').value = data.unit.short_name;
                }
            })
            .catch(error => console.error('Error loading unit:', error));
        } else {
            title.textContent = 'Add New Unit';
            form.action = '{{ route("admin.products.units.store") }}';
            form.reset();
            document.getElementById('unitId').value = '';
        }
    }

    function closeUnitModal() {
        document.getElementById('unitModal').classList.add('hidden');
        document.body.style.overflow = '';
        document.getElementById('unitForm').reset();
        document.getElementById('unitId').value = '';
        currentUnitId = null;
    }

    function editUnit(id) {
        openUnitModal(id);
    }

    function toggleUnitStatus(id, isActive, checkboxElement) {
        const originalState = !isActive;
        
        fetch(`{{ route('admin.products.units.index') }}/${id}`, {
            method: 'PUT',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                is_active: isActive,
                _method: 'PUT'
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update the label text
                const label = checkboxElement.closest('label').querySelector('span');
                label.textContent = isActive ? 'Active' : 'Inactive';
            } else {
                // Revert checkbox state on error
                checkboxElement.checked = originalState;
                alert(data.message || 'Error updating status');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            checkboxElement.checked = originalState;
            alert('Error updating status');
        });
    }

    function deleteUnit(id) {
        if (confirm('Are you sure you want to delete this unit? This action cannot be undone.')) {
            fetch(`{{ route('admin.products.units.index') }}/${id}`, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            })
            .then(response => {
                if (response.ok) {
                    location.reload();
                } else {
                    return response.json().then(data => {
                        alert(data.message || 'Error deleting unit');
                    });
                }
            })
            .catch(error => {
                console.error('Error:', error);
                location.reload();
            });
        }
    }

    // Handle form submission
    document.getElementById('unitForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        const unitId = document.getElementById('unitId').value;
        const url = unitId 
            ? `{{ route('admin.products.units.index') }}/${unitId}`
            : '{{ route("admin.products.units.store") }}';
        const method = unitId ? 'PUT' : 'POST';
        
        // Add _method for PUT requests
        if (method === 'PUT') {
            formData.append('_method', 'PUT');
        }
        
        fetch(url, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert('Error saving unit: ' + (data.message || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            location.reload();
        });
    });
</script>
@endpush
@endsection
