@extends('layouts.app')

@section('page_title', 'Submit Work Report')

@section('content')
    <div class="row justify-content-center">
        <div class="col-lg-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-0 p-4">
                    <h5 class="fw-bold mb-0">Daily Work Summary</h5>
                    <p class="text-muted small mb-0">Linked to attendance on: {{ $attendance->date->format('d M, Y') }}</p>
                </div>
                <div class="card-body p-4 pt-0">
                    <form action="{{ route('reports.store') }}" method="POST">
                        @csrf
                        <input type="hidden" name="attendance_id" value="{{ $attendance->id }}">

                        <div class="mb-4">
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <label class="form-label fw-bold mb-0">Executive Summary</label>
                                <button type="button" class="btn btn-sm btn-link text-decoration-none p-0" id="parseTasks">
                                    <i class="bi bi-magic"></i> Extract Tasks from Summary
                                </button>
                            </div>
                            <textarea name="raw_summary" id="summaryText" class="form-control" rows="4"
                                placeholder="Briefly describe what you worked on today (use - or 1. for tasks)..." required>{{ $existingReport ? $existingReport->raw_summary : '' }}</textarea>
                            <div class="form-text smaller">Write your summary. Use bullets (- or *) for specific tasks to
                                auto-extract.</div>
                        </div>

                        <div class="mb-4">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <label class="form-label fw-bold mb-0">Detailed Tasks</label>
                                <div class="btn-group">
                                    <button type="button" class="btn btn-sm btn-outline-info" data-bs-toggle="modal"
                                        data-bs-target="#importTasksModal">
                                        <i class="bi bi-download"></i> Import
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-primary" id="addTask">
                                        <i class="bi bi-plus"></i> Add Item
                                    </button>
                                </div>
                            </div>
                            <div id="taskList">
                                @if ($existingReport && $existingReport->tasks->count() > 0)
                                    @foreach ($existingReport->tasks as $task)
                                        <div class="input-group mb-2 task-item">
                                            <span class="input-group-text bg-light"><i class="bi bi-check2"></i></span>
                                            <input type="text" name="tasks[]" class="form-control"
                                                value="{{ $task->task_description }}" required>
                                            <button type="button" class="btn btn-outline-danger remove-task"><i
                                                    class="bi bi-trash"></i></button>
                                        </div>
                                    @endforeach
                                @else
                                    <div class="input-group mb-2 task-item">
                                        <span class="input-group-text bg-light"><i class="bi bi-check2"></i></span>
                                        <input type="text" name="tasks[]" class="form-control"
                                            placeholder="Describe specific task..." required>
                                        <button type="button" class="btn btn-outline-danger remove-task"><i
                                                class="bi bi-trash"></i></button>
                                    </div>
                                @endif
                            </div>
                        </div>

                        <div class="d-grid mt-5">
                            <button type="submit" class="btn btn-primary btn-lg fw-bold rounded-3">
                                <i class="bi bi-send me-2"></i> SUBMIT REPORT
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Import Tasks Modal -->
    <div class="modal fade" id="importTasksModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold">Import Project Tasks</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-0">
                    <div class="list-group list-group-flush">
                        @forelse($assignedTasks as $t)
                            <label class="list-group-item d-flex align-items-center cursor-pointer py-3">
                                <input class="form-check-input me-3 import-task-check" type="checkbox"
                                    value="{{ $t->title }}">
                                <div class="flex-grow-1">
                                    <div class="fw-bold small">{{ $t->title }}</div>
                                    <div class="text-muted smaller">Project: {{ $t->project->name }}</div>
                                </div>
                                <span
                                    class="badge bg-{{ $t->status == 'in_progress' ? 'warning' : 'primary' }}-subtle text-{{ $t->status == 'in_progress' ? 'warning' : 'primary' }} smaller">
                                    {{ ucfirst($t->status) }}
                                </span>
                            </label>
                        @empty
                            <div class="p-4 text-center text-muted small">No active tasks assigned to you.</div>
                        @endforelse
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary w-100 fw-bold" id="confirmImport">IMPORT SELECTED</button>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
        <script>
            $(document).ready(function() {
                $('#addTask').on('click', function() {
                    addTaskRow('');
                });

                function addTaskRow(value = '') {
                    const html = `
                        <div class="input-group mb-2 task-item" style="display:none;">
                            <span class="input-group-text bg-light"><i class="bi bi-check2"></i></span>
                            <input type="text" name="tasks[]" class="form-control" placeholder="Describe specific task..." value="${value}" required>
                            <button type="button" class="btn btn-outline-danger remove-task"><i class="bi bi-trash"></i></button>
                        </div>
                    `;
                    $(html).appendTo('#taskList').slideDown(200);
                }

                $('#parseTasks').on('click', function() {
                    const text = $('#summaryText').val();
                    if (!text) return;

                    const lines = text.split('\n');
                    const tasks = [];

                    lines.forEach(line => {
                        const trimmed = line.trim();
                        // Match lines starting with -, *, or 1. (numbers)
                        const match = trimmed.match(/^[-*•]|\d+\.\s*(.*)/);
                        if (match) {
                            const taskDesc = trimmed.replace(/^[-*•\d.]+\s*/, '');
                            if (taskDesc) tasks.push(taskDesc);
                        }
                    });

                    if (tasks.length > 0) {
                        // Clear placeholders if only one empty task exists
                        if ($('.task-item').length === 1 && $('.task-item input').val() === '') {
                            $('.task-item').remove();
                        }

                        tasks.forEach(t => addTaskRow(t));

                        Toast.fire({
                            icon: 'success',
                            title: tasks.length + ' tasks extracted!'
                        });
                    } else {
                        Toast.fire({
                            icon: 'info',
                            title: 'No bulleted tasks found in summary.'
                        });
                    }
                });

                $('#confirmImport').on('click', function() {
                    const selected = $('.import-task-check:checked');
                    if (selected.length === 0) return;

                    // Clear placeholders if only one empty task exists
                    if ($('.task-item').length === 1 && $('.task-item input').val() === '') {
                        $('.task-item').remove();
                    }

                    selected.each(function() {
                        addTaskRow($(this).val());
                    });

                    $('#importTasksModal').modal('hide');
                    selected.prop('checked', false);

                    Toast.fire({
                        icon: 'success',
                        title: selected.length + ' tasks imported!'
                    });
                });

                $(document).on('click', '.remove-task', function() {
                    if ($('.task-item').length > 1) {
                        $(this).closest('.task-item').slideUp(200, function() {
                            $(this).remove();
                        });
                    } else {
                        Toast.fire({
                            icon: 'warning',
                            title: 'At least one task is required.'
                        });
                    }
                });
            });
        </script>
    @endpush
@endsection
