@extends('admin-layouts.master')
@section('title', 'Edit Housekeeping Task')
<style>
/* Minimal Styling */
.card {
    border: none;
    border-radius: 8px;
}

.card-header {
    border-radius: 8px 8px 0 0 !important;
    font-weight: 600;
}

.form-control:focus, .form-select:focus {
    border-color: #0d6efd;
    box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
}

.btn {
    border-radius: 6px;
    font-weight: 500;
}

.badge {
    font-size: 0.7rem;
}

.alert {
    border-radius: 6px;
}

.shadow-sm {
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075) !important;
}

/* Status indicator */
.status-indicator {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    display: inline-block;
    margin-right: 8px;
}

.status-pending { background-color: #ffc107; }
.status-in_progress { background-color: #17a2b8; }
.status-completed { background-color: #28a745; }
.status-cancelled { background-color: #6c757d; }

/* Responsive adjustments */
@media (max-width: 768px) {
    .card-body {
        padding: 1rem;
    }
}
</style>
@section('content')
<div class="container-fluid">
    <!-- Simple Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h4 class="mb-1">Edit Housekeeping Task #{{ $task->id }}</h4>
            <p class="text-muted mb-0 small">
                <span class="status-indicator status-{{ $task->status }}"></span>
                Status: {{ ucfirst(str_replace('_', ' ', $task->status)) }} | 
                Created: {{ $task->created_at->format('d/m/Y H:i') }}
            </p>
        </div>
        <div>
            <a href="{{ route('housekeeping.show', $task->id) }}" class="btn btn-info btn-sm mr-2">
                <i class="fas fa-eye"></i> Detail
            </a>
            <a href="{{ route('housekeeping.index') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Kembali
            </a>
        </div>
    </div>

    <!-- Status Alert -->
    @if($task->status === 'completed')
    <div class="alert alert-success mb-4">
        <i class="fas fa-check-circle"></i> 
        <strong>Task Completed:</strong> Task ini sudah selesai pada {{ $task->completed_at?->format('d/m/Y H:i') }}. 
        Perubahan masih bisa dilakukan untuk koreksi data.
    </div>
    @elseif($task->status === 'cancelled')
    <div class="alert alert-warning mb-4">
        <i class="fas fa-times-circle"></i> 
        <strong>Task Cancelled:</strong> Task ini telah dibatalkan. 
        Anda dapat mengubah status atau melakukan koreksi data.
    </div>
    @elseif($task->is_overdue)
    <div class="alert alert-danger mb-4">
        <i class="fas fa-exclamation-triangle"></i> 
        <strong>Overdue:</strong> Task ini melewati batas waktu yang ditentukan!
    </div>
    @endif

    <div class="row">
        <!-- Main Form -->
        <div class="col-lg-8">
            <div class="card shadow-sm">
                <div class="card-header bg-warning text-dark">
                    <h6 class="mb-0"><i class="fas fa-edit"></i> Form Edit Task</h6>
                </div>
                <div class="card-body">
                    <form action="{{ route('housekeeping.update', $task->id) }}" method="POST" id="taskForm">
                        @csrf
                        @method('PUT')
                        
                        <!-- Room & Booking -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Room <span class="text-danger">*</span></label>
                                <select class="form-select form-control @error('room_id') is-invalid @enderror" 
                                        name="room_id" required>
                                    <option value="">Pilih Room...</option>
                                    @foreach($rooms as $room)
                                        <option value="{{ $room->id }}" 
                                                {{ (old('room_id', $task->room_id) == $room->id) ? 'selected' : '' }}>
                                            {{ $room->room_number }}
                                            @if($room->typeRoom) - {{ $room->typeRoom->name }} @endif
                                        </option>
                                    @endforeach
                                </select>
                                @error('room_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Booking <span class="text-muted">(Opsional)</span></label>
                                <select class="form-select form-control @error('booking_id') is-invalid @enderror" 
                                        name="booking_id">
                                    <option value="">Pilih Booking...</option>
                                    @foreach($bookings as $booking)
                                        <option value="{{ $booking->id }}" 
                                                {{ (old('booking_id', $task->booking_id) == $booking->id) ? 'selected' : '' }}>
                                            #{{ $booking->id }} - {{ $booking->guest->name ?? 'Unknown Guest' }}
                                        </option>
                                    @endforeach
                                </select>
                                @if($task->booking_id && !$bookings->contains('id', $task->booking_id))
                                    <small class="text-warning">
                                        <i class="fas fa-exclamation-triangle"></i> 
                                        Booking asli (#{{ $task->booking_id }}) tidak ditemukan
                                    </small>
                                @endif
                                @error('booking_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>

                        <!-- Task Type & Priority -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Jenis Task <span class="text-danger">*</span></label>
                                <select class="form-select form-control @error('task_type') is-invalid @enderror" 
                                        name="task_type" id="task_type" required>
                                    <option value="">Pilih Jenis Task...</option>
                                    <option value="checkout_cleaning" 
                                            {{ (old('task_type', $task->task_type) == 'checkout_cleaning') ? 'selected' : '' }}>
                                        Pembersihan Checkout
                                    </option>
                                    <option value="maintenance" 
                                            {{ (old('task_type', $task->task_type) == 'maintenance') ? 'selected' : '' }}>
                                        Maintenance
                                    </option>
                                    <option value="deep_cleaning" 
                                            {{ (old('task_type', $task->task_type) == 'deep_cleaning') ? 'selected' : '' }}>
                                        Deep Cleaning
                                    </option>
                                    <option value="inspection" 
                                            {{ (old('task_type', $task->task_type) == 'inspection') ? 'selected' : '' }}>
                                        Inspeksi
                                    </option>
                                </select>
                                @error('task_type')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Priority <span class="text-danger">*</span></label>
                                <select class="form-select form-control @error('priority') is-invalid @enderror" 
                                        name="priority" id="priority" required>
                                    <option value="">Pilih Priority...</option>
                                    <option value="low" {{ (old('priority', $task->priority) == 'low') ? 'selected' : '' }}>Low</option>
                                    <option value="normal" {{ (old('priority', $task->priority) == 'normal') ? 'selected' : '' }}>Normal</option>
                                    <option value="high" {{ (old('priority', $task->priority) == 'high') ? 'selected' : '' }}>High</option>
                                    <option value="urgent" {{ (old('priority', $task->priority) == 'urgent') ? 'selected' : '' }}>Urgent</option>
                                </select>
                                @error('priority')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>

                        <!-- Status & Assignment -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Status Task</label>
                                <select class="form-select form-control @error('status') is-invalid @enderror" 
                                        name="status" id="status">
                                    <option value="pending" {{ (old('status', $task->status) == 'pending') ? 'selected' : '' }}>Pending</option>
                                    <option value="in_progress" {{ (old('status', $task->status) == 'in_progress') ? 'selected' : '' }}>In Progress</option>
                                    <option value="completed" {{ (old('status', $task->status) == 'completed') ? 'selected' : '' }}>Completed</option>
                                    <option value="cancelled" {{ (old('status', $task->status) == 'cancelled') ? 'selected' : '' }}>Cancelled</option>
                                </select>
                                @error('status')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Assign ke Staff</label>
                                <select class="form-select form-control @error('assigned_to') is-invalid @enderror" 
                                        name="assigned_to">
                                    <option value="">Belum di-assign...</option>
                                    @foreach($users as $user)
                                        <option value="{{ $user->id }}" 
                                                {{ (old('assigned_to', $task->assigned_to) == $user->id) ? 'selected' : '' }}>
                                            {{ $user->name }}
                                        </option>
                                    @endforeach
                                </select>
                                @if($task->assigned_to && !$users->contains('id', $task->assigned_to))
                                    <small class="text-warning">
                                        <i class="fas fa-exclamation-triangle"></i> 
                                        Staff asli tidak ditemukan
                                    </small>
                                @endif
                                @error('assigned_to')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>

                        <!-- Duration & Due Time -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Estimasi Durasi (menit)</label>
                                <input type="number" class="form-control @error('estimated_duration') is-invalid @enderror" 
                                       name="estimated_duration" id="estimated_duration" min="1" 
                                       value="{{ old('estimated_duration', $task->estimated_duration) }}" 
                                       placeholder="60">
                                <small class="text-muted">Estimasi waktu pengerjaan</small>
                                @error('estimated_duration')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Target Selesai</label>
                                <input type="datetime-local" class="form-control @error('due_time') is-invalid @enderror" 
                                       name="due_time" id="due_time" 
                                       value="{{ old('due_time', $task->due_time?->format('Y-m-d\TH:i')) }}">
                                <small class="text-muted">Kapan task harus selesai</small>
                                @error('due_time')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>

                        <!-- Description -->
                        <div class="mb-4">
                            <label class="form-label fw-bold">Deskripsi Task</label>
                            <textarea class="form-control @error('description') is-invalid @enderror" 
                                      name="description" id="description" rows="4" 
                                      placeholder="Jelaskan detail pekerjaan yang harus dilakukan...">{{ old('description', $task->description) }}</textarea>
                            @error('description')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <!-- Notes -->
                        <div class="mb-4">
                            <label class="form-label fw-bold">Catatan Tambahan</label>
                            <textarea class="form-control @error('notes') is-invalid @enderror" 
                                      name="notes" id="notes" rows="2" 
                                      placeholder="Catatan atau update progress...">{{ old('notes', $task->notes) }}</textarea>
                            <small class="text-muted">Catatan untuk tracking progress atau update status</small>
                            @error('notes')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <!-- Action Buttons -->
                        <div class="d-flex gap-2 justify-content-between">
                            <div>
                                @if($task->status !== 'completed')
                                <button type="button" class="btn btn-success" onclick="quickComplete()">
                                    <i class="fas fa-check"></i> Mark as Completed
                                </button>
                                @endif
                                @if($task->status === 'pending')
                                <button type="button" class="btn btn-info" onclick="quickStart()">
                                    <i class="fas fa-play"></i> Start Task
                                </button>
                                @endif
                            </div>
                            <div>
                                <a href="{{ route('housekeeping.index') }}" class="btn btn-outline-secondary mr-2">
                                    <i class="fas fa-times"></i> Batal
                                </a>
                                <button type="submit" class="btn btn-warning">
                                    <i class="fas fa-save"></i> Update Task
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-4">
            <!-- Task Info -->
            <div class="card shadow-sm mb-3">
                <div class="card-header bg-info text-white">
                    <h6 class="mb-0"><i class="fas fa-info-circle"></i> Task Information</h6>
                </div>
                <div class="card-body p-3">
                    <div class="mb-3">
                        <strong>Created:</strong><br>
                        <small>{{ $task->created_at->format('d/m/Y H:i') }}</small>
                    </div>
                    @if($task->assigned_at)
                    <div class="mb-3">
                        <strong>Assigned:</strong><br>
                        <small>{{ $task->assigned_at->format('d/m/Y H:i') }}</small>
                    </div>
                    @endif
                    @if($task->started_at)
                    <div class="mb-3">
                        <strong>Started:</strong><br>
                        <small>{{ $task->started_at->format('d/m/Y H:i') }}</small>
                    </div>
                    @endif
                    @if($task->completed_at)
                    <div class="mb-3">
                        <strong>Completed:</strong><br>
                        <small>{{ $task->completed_at->format('d/m/Y H:i') }}</small>
                    </div>
                    @endif
                    <div class="mb-0">
                        <strong>Last Updated:</strong><br>
                        <small>{{ $task->updated_at->format('d/m/Y H:i') }}</small>
                    </div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="card shadow-sm mb-3">
                <div class="card-header bg-success text-white">
                    <h6 class="mb-0"><i class="fas fa-bolt"></i> Quick Update</h6>
                </div>
                <div class="card-body p-3">
                    <div class="d-grid gap-2">
                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="setQuickTask('checkout')">
                            <i class="fas fa-broom"></i> Reset to Checkout
                        </button>
                        <button type="button" class="btn btn-outline-warning btn-sm" onclick="setQuickTask('maintenance')">
                            <i class="fas fa-tools"></i> Reset to Maintenance
                        </button>
                        {{-- <button type="button" class="btn btn-outline-info btn-sm" onclick="setQuickTask('inspection')">
                            <i class="fas fa-search"></i> Reset to Inspection
                        </button> --}}
                    </div>
                </div>
            </div>

            <!-- Tips -->
            <div class="card shadow-sm">
                <div class="card-header bg-secondary text-white">
                    <h6 class="mb-0"><i class="fas fa-lightbulb"></i> Edit Tips</h6>
                </div>
                <div class="card-body p-3">
                    <div class="alert alert-info border-0 p-2 mb-2">
                        <small><i class="fas fa-info-circle"></i> Mengubah status ke "Completed" akan otomatis set completed_at.</small>
                    </div>
                    <div class="alert alert-warning border-0 p-2 mb-0">
                        <small><i class="fas fa-bell"></i> Perubahan priority ke "Urgent" akan trigger notifikasi.</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
$(document).ready(function() {
    // Initialize form validation
    initializeValidation();
});

// Quick action functions
function quickComplete() {
    $('#status').val('completed');
    $('#notes').val($('#notes').val() + '\n[' + new Date().toLocaleString() + '] Task marked as completed via quick action.');
    showNotification('Status changed to completed. Don\'t forget to update the form!', 'success');
}

function quickStart() {
    $('#status').val('in_progress');
    $('#notes').val($('#notes').val() + '\n[' + new Date().toLocaleString() + '] Task started via quick action.');
    showNotification('Status changed to in progress. Don\'t forget to update the form!', 'info');
}

// Quick task presets (same as create but for editing)
function setQuickTask(type) {
    const button = event.target;
    const originalText = button.innerHTML;
    
    // Show loading
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Loading...';
    button.disabled = true;
    
    setTimeout(() => {
        switch(type) {
            case 'checkout':
                $('#task_type').val('checkout_cleaning');
                $('#priority').val('normal');
                $('#estimated_duration').val(60);
                $('#description').val('Pembersihan standar room setelah guest checkout:\n- Ganti bed sheet dan towel\n- Bersihkan kamar mandi\n- Vacuum carpet\n- Periksa fasilitas room');
                break;
            case 'maintenance':
                $('#task_type').val('maintenance');
                $('#priority').val('high');
                $('#estimated_duration').val(90);
                $('#description').val('Pemeriksaan dan perbaikan:\n- Periksa AC dan lampu\n- Cek fasilitas kamar mandi\n- Test TV dan WiFi\n- Perbaiki jika ada kerusakan');
                break;
            case 'inspection':
                $('#task_type').val('inspection');
                $('#priority').val('normal');
                $('#estimated_duration').val(30);
                $('#description').val('Inspeksi kondisi room:\n- Periksa kebersihan\n- Cek kelengkapan amenities\n- Dokumentasi kondisi\n- Laporkan jika ada masalah');
                break;
        }
        
        // Add notes about the change
        const currentNotes = $('#notes').val();
        const timestamp = new Date().toLocaleString();
        $('#notes').val(currentNotes + `\n[${timestamp}] Template "${type}" applied during edit.`);
        
        // Restore button
        button.innerHTML = originalText;
        button.disabled = false;
        
        // Show notification
        showNotification('Template applied successfully!', 'success');
        
    }, 500);
}

// Auto-set estimated duration based on task type (if not manually changed)
$('#task_type').on('change', function() {
    const taskType = $(this).val();
    const currentDuration = $('#estimated_duration').val();
    
    // Only auto-set if current duration is default values
    if ([30, 60, 90, 120].includes(parseInt(currentDuration))) {
        let duration;
        
        switch(taskType) {
            case 'checkout_cleaning':
                duration = 60;
                break;
            case 'maintenance':
                duration = 90;
                break;
            case 'deep_cleaning':
                duration = 120;
                break;
            case 'inspection':
                duration = 30;
                break;
            default:
                duration = 60;
        }
        
        $('#estimated_duration').val(duration);
    }
});

// Form validation
function initializeValidation() {
    $('#taskForm').on('submit', function(e) {
        let isValid = true;
        const requiredFields = ['room_id', 'task_type', 'priority'];
        
        requiredFields.forEach(function(field) {
            const element = $(`[name="${field}"]`);
            if (!element.val()) {
                isValid = false;
                element.addClass('is-invalid');
            } else {
                element.removeClass('is-invalid');
            }
        });
        
        if (!isValid) {
            e.preventDefault();
            showNotification('Mohon lengkapi semua field yang wajib diisi!', 'error');
        } else {
            // Add update timestamp to notes
            const currentNotes = $('#notes').val();
            const timestamp = new Date().toLocaleString();
            $('#notes').val(currentNotes + `\n[${timestamp}] Task updated via edit form.`);
        }
    });
}

// Notification system
function showNotification(message, type = 'info') {
    const alertClass = type === 'success' ? 'alert-success' : 
                      type === 'error' ? 'alert-danger' : 
                      type === 'warning' ? 'alert-warning' : 'alert-info';
    
    const notification = $(`
        <div class="alert ${alertClass} alert-dismissible fade show position-fixed" 
             style="top: 20px; right: 20px; z-index: 9999; min-width: 300px;">
            ${message}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    `);
    
    $('body').append(notification);
    
    setTimeout(() => notification.alert('close'), 4000);
}

// Real-time validation feedback
$('.form-control, .form-select').on('change', function() {
    const field = $(this);
    if (field.prop('required') && !field.val()) {
        field.addClass('is-invalid');
    } else {
        field.removeClass('is-invalid');
    }
});

// Auto-expand textarea when content is long
$('textarea').each(function() {
    this.style.height = 'auto';
    this.style.height = (this.scrollHeight) + 'px';
});

$('textarea').on('input', function() {
    this.style.height = 'auto';
    this.style.height = (this.scrollHeight) + 'px';
});
</script>
@endpush