<x-app-layout>

    <div class="py-6">
        <div class="max-w-4xl mx-auto sm:px-6 lg:px-8">
            {{-- Flash Messages --}}
            @if(session('error'))
                <div class="mb-6 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg relative" role="alert">
                    <span class="block sm:inline">{{ session('error') }}</span>
                </div>
            @endif

            {{-- Form Card --}}
            <div class="bg-theme-card theme-card rounded-lg shadow-sm">
                <form method="POST" action="{{ route('mentorship.assignments.update', $assignment) }}" id="assignmentForm">
                    @csrf
                    @method('PUT')

                    {{-- Assignment Info (Read-only) --}}
                    <div class="p-6 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
                        <h3 class="text-lg font-semibold text-theme-body mb-4">
                            <i class="fas fa-info-circle mr-2 text-green-600"></i>Assignment Information
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <p class="text-sm text-gray-500 dark:text-gray-400">Programme</p>
                                <p class="font-medium text-theme-body">{{ $assignment->programme->title }}</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500 dark:text-gray-400">Mentor</p>
                                <p class="font-medium text-theme-body">{{ $assignment->mentor->name }}</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500 dark:text-gray-400">Mentee</p>
                                <p class="font-medium text-theme-body">{{ $assignment->mentee->name }}</p>
                            </div>
                        </div>
                        <p class="text-xs text-gray-400 dark:text-gray-500 mt-3">
                            <i class="fas fa-lock mr-1"></i>Programme, mentor, and mentee cannot be changed. Use reassign functionality to change participants.
                        </p>
                    </div>

                    {{-- Schedule --}}
                    <div class="p-6 border-b border-gray-200 dark:border-gray-700">
                        <h3 class="text-lg font-semibold text-theme-body mb-4">
                            <i class="fas fa-calendar-alt mr-2 text-green-600"></i>Schedule
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                            {{-- Start Date --}}
                            <div>
                                <label for="start_date" class="block text-sm font-medium text-theme-body mb-1">
                                    Start Date <span class="text-red-500">*</span>
                                </label>
                                <input type="date" name="start_date" id="start_date" value="{{ old('start_date', $assignment->start_date?->format('Y-m-d')) }}" required
                                       class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-green-500 focus:ring-green-500 @error('start_date') border-red-500 @enderror">
                                @error('start_date')
                                    <p class="mt-1 text-sm text-red-500">{{ $message }}</p>
                                @enderror
                            </div>

                            {{-- End Date --}}
                            <div>
                                <label for="end_date" class="block text-sm font-medium text-theme-body mb-1">
                                    End Date
                                </label>
                                <input type="date" name="end_date" id="end_date" value="{{ old('end_date', $assignment->end_date?->format('Y-m-d')) }}"
                                       class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-green-500 focus:ring-green-500 @error('end_date') border-red-500 @enderror">
                                @error('end_date')
                                    <p class="mt-1 text-sm text-red-500">{{ $message }}</p>
                                @enderror
                            </div>

                            {{-- Meeting Frequency --}}
                            <div>
                                <label for="meeting_frequency" class="block text-sm font-medium text-theme-body mb-1">
                                    Meeting Frequency
                                </label>
                                <select name="meeting_frequency" id="meeting_frequency"
                                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-green-500 focus:ring-green-500">
                                    <option value="">Select frequency</option>
                                    <option value="daily" {{ old('meeting_frequency', $assignment->meeting_frequency) == 'daily' ? 'selected' : '' }}>Daily</option>
                                    <option value="twice_weekly" {{ old('meeting_frequency', $assignment->meeting_frequency) == 'twice_weekly' ? 'selected' : '' }}>Twice Weekly</option>
                                    <option value="weekly" {{ old('meeting_frequency', $assignment->meeting_frequency) == 'weekly' ? 'selected' : '' }}>Weekly</option>
                                    <option value="bi_weekly" {{ old('meeting_frequency', $assignment->meeting_frequency) == 'bi_weekly' ? 'selected' : '' }}>Bi-Weekly</option>
                                    <option value="monthly" {{ old('meeting_frequency', $assignment->meeting_frequency) == 'monthly' ? 'selected' : '' }}>Monthly</option>
                                    <option value="as_needed" {{ old('meeting_frequency', $assignment->meeting_frequency) == 'as_needed' ? 'selected' : '' }}>As Needed</option>
                                </select>
                                @error('meeting_frequency')
                                    <p class="mt-1 text-sm text-red-500">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                    </div>

                    {{-- Goals & Notes --}}
                    <div class="p-6 border-b border-gray-200 dark:border-gray-700">
                        <h3 class="text-lg font-semibold text-theme-body mb-4">
                            <i class="fas fa-bullseye mr-2 text-green-600"></i>Goals & Notes
                        </h3>
                        
                        {{-- Goals --}}
                        <div class="mb-6">
                            <label for="goals" class="block text-sm font-medium text-theme-body mb-1">
                                Mentorship Goals <span class="text-red-500">*</span>
                            </label>
                            <textarea name="goals" id="goals" rows="4" required
                                      placeholder="Define the specific goals and objectives for this mentorship..."
                                      class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-green-500 focus:ring-green-500 @error('goals') border-red-500 @enderror">{{ old('goals', $assignment->goals) }}</textarea>
                            @error('goals')
                                <p class="mt-1 text-sm text-red-500">{{ $message }}</p>
                            @enderror
                        </div>

                        {{-- Notes --}}
                        <div>
                            <label for="notes" class="block text-sm font-medium text-theme-body mb-1">
                                Additional Notes
                            </label>
                            <textarea name="notes" id="notes" rows="3"
                                      placeholder="Any additional notes or special instructions..."
                                      class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-green-500 focus:ring-green-500 @error('notes') border-red-500 @enderror">{{ old('notes', $assignment->notes) }}</textarea>
                            @error('notes')
                                <p class="mt-1 text-sm text-red-500">{{ $message }}</p>
                            @enderror
                        </div>
                    </div>

                    {{-- Milestones --}}
                    <div class="p-6 border-b border-gray-200 dark:border-gray-700">
                        <h3 class="text-lg font-semibold text-theme-body mb-4">
                            <i class="fas fa-flag-checkered mr-2 text-green-600"></i>Milestones
                        </h3>
                        <div id="milestones-container">
                            @php
                                $existingMilestones = $assignment->milestones ?? [];
                                // Ensure at least one milestone field if empty
                                $milestones = count($existingMilestones) > 0 ? $existingMilestones : [['title' => '', 'description' => '', 'due_date' => '', 'completed' => false]];
                            @endphp
                            @foreach($milestones as $index => $milestone)
                                <div class="milestone-item grid grid-cols-1 md:grid-cols-12 gap-4 mb-4">
                                    <div class="md:col-span-3 flex items-center gap-2">
                                        <input type="checkbox" name="milestones[{{ $index }}][completed]" value="1" 
                                               {{ ($milestone['completed'] ?? false) ? 'checked' : '' }}
                                               class="w-4 h-4 text-green-600 rounded border-gray-300 focus:ring-green-500">
                                        <input type="text" name="milestones[{{ $index }}][title]" placeholder="Milestone title"
                                               value="{{ old("milestones.{$index}.title", $milestone['title'] ?? '') }}"
                                               class="flex-1 rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-green-500 focus:ring-green-500">
                                    </div>
                                    <div class="md:col-span-5">
                                        <input type="text" name="milestones[{{ $index }}][description]" placeholder="Description"
                                               value="{{ old("milestones.{$index}.description", $milestone['description'] ?? '') }}"
                                               class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-green-500 focus:ring-green-500">
                                    </div>
                                    <div class="md:col-span-3">
                                        <input type="date" name="milestones[{{ $index }}][due_date]" placeholder="Due date"
                                               value="{{ old("milestones.{$index}.due_date", $milestone['due_date'] ?? '') }}"
                                               class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-green-500 focus:ring-green-500">
                                    </div>
                                    <div class="md:col-span-1 flex items-center">
                                        <button type="button" class="remove-milestone text-red-500 hover:text-red-700 px-2">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                        <button type="button" id="add-milestone" class="inline-flex items-center px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 transition">
                            <i class="fas fa-plus mr-2"></i>Add Milestone
                        </button>
                    </div>

                    {{-- Progress Update --}}
                    <div class="p-6 border-b border-gray-200 dark:border-gray-700">
                        <h3 class="text-lg font-semibold text-theme-body mb-4">
                            <i class="fas fa-chart-line mr-2 text-green-600"></i>Progress
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label for="progress" class="block text-sm font-medium text-theme-body mb-1">
                                    Overall Progress (%)
                                </label>
                                <div class="flex items-center gap-4">
                                    <input type="range" name="progress" id="progress" min="0" max="100" 
                                           value="{{ old('progress', $assignment->progress ?? 0) }}"
                                           class="flex-1 h-2 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-green-600">
                                    <span id="progress-value" class="text-lg font-bold text-green-600 w-12 text-center">{{ old('progress', $assignment->progress ?? 0) }}%</span>
                                </div>
                                <input type="hidden" name="progress" id="progress-hidden" value="{{ old('progress', $assignment->progress ?? 0) }}">
                            </div>
                            <div>
                                <label for="status" class="block text-sm font-medium text-theme-body mb-1">
                                    Status
                                </label>
                                <select name="status" id="status"
                                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-green-500 focus:ring-green-500">
                                    <option value="pending" {{ old('status', $assignment->status) == 'pending' ? 'selected' : '' }}>Pending</option>
                                    <option value="active" {{ old('status', $assignment->status) == 'active' ? 'selected' : '' }}>Active</option>
                                    <option value="completed" {{ old('status', $assignment->status) == 'completed' ? 'selected' : '' }}>Completed</option>
                                    <option value="cancelled" {{ old('status', $assignment->status) == 'cancelled' ? 'selected' : '' }}>Cancelled</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    {{-- Form Actions --}}
                    <div class="p-6 flex items-center justify-end gap-3">
                        <a href="{{ route('mentorship.assignments.show', $assignment) }}" 
                           class="px-6 py-2 bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-200 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-500 transition">
                            Cancel
                        </a>
                        <button type="submit" class="theme-btn-primary inline-flex items-center px-6 py-2 rounded-lg">
                            <i class="fas fa-save mr-2"></i>Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        let milestoneCount = {{ count($milestones) }};

        // Add milestone
        document.getElementById('add-milestone').addEventListener('click', function() {
            const container = document.getElementById('milestones-container');
            const newMilestone = document.createElement('div');
            newMilestone.className = 'milestone-item grid grid-cols-1 md:grid-cols-12 gap-4 mb-4';
            newMilestone.innerHTML = `
                <div class="md:col-span-3 flex items-center gap-2">
                    <input type="checkbox" name="milestones[${milestoneCount}][completed]" value="1" 
                           class="w-4 h-4 text-green-600 rounded border-gray-300 focus:ring-green-500">
                    <input type="text" name="milestones[${milestoneCount}][title]" placeholder="Milestone title"
                           class="flex-1 rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-green-500 focus:ring-green-500">
                </div>
                <div class="md:col-span-5">
                    <input type="text" name="milestones[${milestoneCount}][description]" placeholder="Description"
                           class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-green-500 focus:ring-green-500">
                </div>
                <div class="md:col-span-3">
                    <input type="date" name="milestones[${milestoneCount}][due_date]" placeholder="Due date"
                           class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-green-500 focus:ring-green-500">
                </div>
                <div class="md:col-span-1 flex items-center">
                    <button type="button" class="remove-milestone text-red-500 hover:text-red-700 px-2">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            `;
            container.appendChild(newMilestone);
            milestoneCount++;

            // Add remove event listener
            newMilestone.querySelector('.remove-milestone').addEventListener('click', function() {
                newMilestone.remove();
            });
        });

        // Remove milestone
        document.querySelectorAll('.remove-milestone').forEach(btn => {
            btn.addEventListener('click', function() {
                this.closest('.milestone-item').remove();
            });
        });

        // Progress slider
        const progressSlider = document.getElementById('progress');
        const progressValue = document.getElementById('progress-value');
        const progressHidden = document.getElementById('progress-hidden');

        progressSlider.addEventListener('input', function() {
            progressValue.textContent = this.value + '%';
            progressHidden.value = this.value;
        });
    </script>
    @endpush
</x-app-layout>
