<x-app-layout>
    <x-slot name="header">
        <div class="flex justify-between items-center">
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">
                Settings
            </h2>
            <div class="flex space-x-2">
                <a href="{{ route('dashboard') }}" class="bg-gray-800 hover:bg-gray-900 text-white font-medium py-2 px-4 rounded border border-gray-800">
                    Back to Dashboard
                </a>
            </div>
        </div>
    </x-slot>

    <div class="py-12">
        <div class="max-w-6xl mx-auto sm:px-6 lg:px-8 space-y-6">

            <!-- Success Message -->
            @if(session('success'))
                <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative" role="alert">
                    <span class="block sm:inline">{{ session('success') }}</span>
                </div>
            @endif

            <!-- Due Date Settings -->
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900">
                    <h3 class="text-lg font-semibold mb-4">Due Date Settings</h3>

                    <form method="POST" action="{{ route('settings.update') }}" class="space-y-4">
                        @csrf
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label for="warningDays" class="block text-sm font-medium text-gray-700">Warning Days</label>
                                <input type="number" id="warningDays" name="warning_days"
                                       value="{{ $settings['warning_days'] ?? 7 }}" min="1" required
                                       class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <p class="mt-1 text-sm text-gray-500">Days before due date to show warning</p>
                            </div>

                            <div>
                                <label for="criticalDays" class="block text-sm font-medium text-gray-700">Critical Days</label>
                                <input type="number" id="criticalDays" name="critical_days"
                                       value="{{ $settings['critical_days'] ?? 2 }}" min="1" required
                                       class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <p class="mt-1 text-sm text-gray-500">Days before due date to show critical warning</p>
                            </div>
                        </div>

                        <div class="flex justify-end">
                            <button type="submit" class="bg-gray-800 hover:bg-gray-900 text-white font-medium py-2 px-4 rounded border border-gray-800">
                                Save Settings
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Status Management -->
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900">
                    <h3 class="text-lg font-semibold mb-4">Status Management</h3>

                    <!-- Add Status Form -->
                    <form id="addStatusForm" class="mb-6">
                        @csrf
                        <div class="flex gap-4 items-end">
                            <div class="flex-1">
                                <label for="statusName" class="block text-sm font-medium text-gray-700">Status Name</label>
                                <input type="text" id="statusName" name="name" required
                                       class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            </div>
                            <div>
                                <button type="submit" class="bg-gray-800 hover:bg-gray-900 text-white font-medium py-2.5 px-4 rounded border border-gray-800 h-10">
                                    Add Status
                                </button>
                            </div>
                        </div>
                    </form>

                    <!-- Status Table -->
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status Name</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Is Paid Status?</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200" id="statusTableBody">
                                @foreach($statuses as $status)
                                <tr>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ $status->name }}</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                        <input type="checkbox" {{ $status->is_paid_status ? 'checked' : '' }}
                                               onchange="updateStatusPaidFlag({{ $status->id }}, this.checked)"
                                               class="rounded">
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                        <div class="flex space-x-2">
                                            <button onclick="editStatus({{ $status->id }}, '{{ $status->name }}', {{ $status->is_paid_status ? 'true' : 'false' }})"
                                                    class="inline-flex items-center px-3 py-1 border border-blue-300 text-xs font-medium rounded text-blue-700 bg-blue-50 hover:bg-blue-100 transition-colors">
                                                <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                                </svg>
                                                Edit
                                            </button>
                                            <button onclick="deleteStatus({{ $status->id }})"
                                                    class="inline-flex items-center px-3 py-1 border border-red-300 text-xs font-medium rounded text-red-700 bg-red-50 hover:bg-red-100 transition-colors">
                                                <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                                </svg>
                                                Delete
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Add Status Form Handler
        document.getElementById('addStatusForm').addEventListener('submit', function(e) {
            e.preventDefault();

            const formData = new FormData(this);

            fetch('/settings/statuses', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Accept': 'application/json',
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Add new row to table
                    const tbody = document.getElementById('statusTableBody');
                    const newRow = document.createElement('tr');
                    newRow.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${data.status.name}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <input type="checkbox" ${data.status.is_paid_status ? 'checked' : ''}
                                   onchange="updateStatusPaidFlag(${data.status.id}, this.checked)"
                                   class="rounded">
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <div class="flex space-x-2">
                                <button onclick="editStatus(${data.status.id}, '${data.status.name}', ${data.status.is_paid_status})"
                                        class="inline-flex items-center px-3 py-1 border border-blue-300 text-xs font-medium rounded text-blue-700 bg-blue-50 hover:bg-blue-100 transition-colors">
                                    <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                    </svg>
                                    Edit
                                </button>
                                <button onclick="deleteStatus(${data.status.id})"
                                        class="inline-flex items-center px-3 py-1 border border-red-300 text-xs font-medium rounded text-red-700 bg-red-50 hover:bg-red-100 transition-colors">
                                    <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                    </svg>
                                    Delete
                                </button>
                            </div>
                        </td>
                    `;
                    tbody.appendChild(newRow);

                    // Clear form
                    document.getElementById('statusName').value = '';

                    // Show success message
                    showMessage('Status added successfully!', 'success');
                } else {
                    showMessage(data.message || 'Error adding status', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('Error adding status', 'error');
            });
        });

        // Update Status Paid Flag
        function updateStatusPaidFlag(statusId, isPaid) {
            fetch(`/settings/statuses/${statusId}`, {
                method: 'PUT',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                },
                body: JSON.stringify({
                    is_paid_status: isPaid
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage('Status updated successfully!', 'success');
                } else {
                    showMessage(data.message || 'Error updating status', 'error');
                    // Revert checkbox
                    event.target.checked = !isPaid;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('Error updating status', 'error');
                // Revert checkbox
                event.target.checked = !isPaid;
            });
        }

        // Edit Status
        function editStatus(statusId, currentName, isPaidStatus) {
            const newName = prompt('Enter new status name:', currentName);
            if (newName && newName !== currentName) {
                fetch(`/settings/statuses/${statusId}`, {
                    method: 'PUT',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                    },
                    body: JSON.stringify({
                        name: newName
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload(); // Reload to show updated name
                    } else {
                        showMessage(data.message || 'Error updating status', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage('Error updating status', 'error');
                });
            }
        }

        // Delete Status
        function deleteStatus(statusId) {
            if (confirm('Are you sure you want to delete this status?')) {
                fetch(`/settings/statuses/${statusId}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                        'Accept': 'application/json',
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload(); // Reload to remove deleted status
                    } else {
                        showMessage(data.message || 'Error deleting status', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage('Error deleting status', 'error');
                });
            }
        }

        // Show Message
        function showMessage(message, type) {
            const alertClass = type === 'success' ? 'bg-green-100 border-green-400 text-green-700' : 'bg-red-100 border-red-400 text-red-700';
            const alertHtml = `
                <div class="${alertClass} px-4 py-3 rounded relative mb-4" role="alert">
                    <span class="block sm:inline">${message}</span>
                </div>
            `;

            // Insert at the top of the page content
            const container = document.querySelector('.py-12 > div');
            container.insertAdjacentHTML('afterbegin', alertHtml);

            // Remove after 3 seconds
            setTimeout(() => {
                const alert = container.querySelector('.px-4.py-3.rounded.relative.mb-4');
                if (alert) alert.remove();
            }, 3000);
        }
    </script>
</x-app-layout>
