<template>
    <section class="container py-4">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h1 class="card-title text-primary mb-3">📝 Tasks</h1>
                <!-- Today's Tasks -->
                <div class="mb-4 p-3 bg-white rounded shadow-sm">
                    <h2 class="h6 fw-semibold mb-2">📅 Today</h2>
                    <ul class="list-unstyled mb-0">
                        <li v-for="task in todaysTasks" :key="task.id" class="mb-1 d-flex align-items-center gap-2">
                            <input type="checkbox" :checked="task.is_completed" @change="toggleTaskCompletion(task)" />
                            <span :style="{ textDecoration: task.is_completed ? 'line-through' : 'none' }">
                                {{ formatTask(task) }}
                            </span>
                        </li>
                    </ul>
                </div>
                <!-- Future Tasks grouped by day -->
                <div class="mb-4 p-3 bg-white rounded shadow-sm">
                    <h2 class="h6 fw-semibold mb-2">📆 Upcoming</h2>
                    <div v-for="(tasks, date) in groupedFutureTasks" :key="date" class="mb-3">
                        <h3 class="h6 text-secondary mb-1">{{ formatDateHeader(date) }}</h3>
                        <ul class="list-unstyled mb-0">
                            <li v-for="task in tasks" :key="task.id" class="mb-1">
                                {{ formatTask(task) }}
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <!-- FAB Add Task Button -->
        <button class="fab-button" @click="showAddTaskModal = true">
            <Plus size="20" color="white" />
        </button>
        <!-- Add Task Modal -->
        <div v-if="showAddTaskModal" class="modal-backdrop">
            <div class="modal-content p-4 bg-white rounded shadow">
                <h5 class="mb-3">Add Task</h5>
                <!-- Task name -->
                <input v-model="newTaskContent" type="text" placeholder="Task name" class="form-control mb-1" :class="{ 'is-invalid': errors.content }" />
                <div v-if="errors.content" class="text-danger small mb-2">{{ errors.content }}</div>
                <!-- Date & Time picker -->
                <VueDatePicker v-model="newTaskDateTime" :is-range="false" :enable-time-picker="true" input-class-name="form-control" format="dd-MM-yyyy HH:mm" placeholder="Pick date & time" auto-apply :class="{ 'is-invalid': errors.datetime }" />
                <div v-if="errors.datetime" class="text-danger small mt-1">{{ errors.datetime }}</div>
                <div class="d-flex justify-content-end mt-4 gap-2">
                    <button class="btn btn-sm btn-secondary" @click="closeModal">Cancel</button>
                    <button class="btn btn-sm btn-primary" @click="submitTask">Add Task</button>
                </div>
            </div>
        </div>
    </section>
</template>
<script>
import { Plus } from 'lucide-vue-next';
import VueDatePicker from '@vuepic/vue-datepicker';
import '@vuepic/vue-datepicker/dist/main.css';

export default {
    components: { Plus, VueDatePicker },
    data() {
        return {
            todaysTasks: [],
            futureTasks: [],
            showAddTaskModal: false,
            newTaskContent: '',
            newTaskDateTime: null,
            errors: {
                content: '',
                datetime: ''
            }
        };
    },
    computed: {
        groupedFutureTasks() {
            const groups = {};
            this.futureTasks.forEach(task => {
                const date = task.due.date;
                if (!groups[date]) groups[date] = [];
                groups[date].push(task);
            });
            return groups;
        }
    },
    methods: {
        async toggleTaskCompletion(task) {
            // Flip completion locally for optimistic UI update
            task.is_completed = !task.is_completed;

            try {
                const encodedTitle = encodeURIComponent(task.content);
                const encodedDatetime = encodeURIComponent(task.due.datetime.replace('Z', ''));

                const url = `https://192.168.70.11:8000/todo/${encodedTitle}/${encodedDatetime}/complete`;

                await fetch(url, {
                    method: 'POST',
                });

                // Refresh tasks from backend to reflect accurate state
                await this.fetchTasks();
            } catch (error) {
                // Revert UI change if API call fails
                task.is_completed = !task.is_completed;
                alert('Failed to mark task as completed.');
            }
        },
        async fetchTasks() {
            const res = await fetch('https://192.168.70.11:8000/todo/all');
            const json = await res.json();
            const allTasks = json.data || [];

            // Get local today's date in 'YYYY-MM-DD' format
            const todayDate = new Date();
            const yyyy = todayDate.getFullYear();
            const mm = String(todayDate.getMonth() + 1).padStart(2, '0');
            const dd = String(todayDate.getDate()).padStart(2, '0');
            const today = `${yyyy}-${mm}-${dd}`;

            this.todaysTasks = allTasks.filter(
                t => t.due && t.due.date === today
            );

            this.futureTasks = allTasks.filter(
                t => t.due && t.due.date > today
            );
        },
        formatTask(task) {
            const time = new Date(task.due.datetime).toLocaleTimeString([], {
                hour: '2-digit',
                minute: '2-digit',
            });
            return `${time} ${task.content}`;
        },
        formatDateHeader(dateStr) {
            const options = { weekday: 'long', month: 'short', day: 'numeric' };
            const d = new Date(dateStr);
            return d.toLocaleDateString(undefined, options); // e.g. "Friday, Jun 12"
        },
        closeModal() {
            this.showAddTaskModal = false;
            this.newTaskContent = '';
            this.newTaskDateTime = null;
            this.errors = { content: '', datetime: '' };
        },
        async submitTask() {
            this.errors = { content: '', datetime: '' };

            let valid = true;
            if (!this.newTaskContent.trim()) {
                this.errors.content = 'Please enter a task name';
                valid = false;
            }
            if (!this.newTaskDateTime) {
                this.errors.datetime = 'Please pick a date and time';
                valid = false;
            }

            if (!valid) return;

            // Format datetime in local ISO 8601 format WITHOUT timezone ("Z")
            const pad = n => String(n).padStart(2, '0');
            const dt = this.newTaskDateTime;
            const dueDatetime =
                `${dt.getFullYear()}-${pad(dt.getMonth() + 1)}-${pad(dt.getDate())}T` +
                `${pad(dt.getHours())}:${pad(dt.getMinutes())}:${pad(dt.getSeconds())}`;

            const encodedTitle = encodeURIComponent(this.newTaskContent);
            const encodedDatetime = encodeURIComponent(dueDatetime);

            await fetch(`https://192.168.70.11:8000/todo/${encodedTitle}/${encodedDatetime}/create`, {
                method: 'POST',
            });

            this.closeModal();
            this.fetchTasks();
        },
    },
    mounted() {
        this.fetchTasks();
    },
};
</script>
<style scoped>
.text-primary {
    color: #6f42c1 !important;
}

.fab-button {
    position: fixed;
    bottom: 1.5rem;
    right: 1.5rem;
    width: 56px;
    height: 56px;
    border-radius: 50%;
    background-color: #6f42c1;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    cursor: pointer;
    z-index: 1000;
}

.fab-button:hover {
    background-color: #59359e !important;
    border-color: #59359e !important;
}

.modal-backdrop {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1050;
}

.modal-content {
    width: 100%;
    max-width: 400px;
}

.is-invalid {
    border: 1px solid #dc3545 !important;
    animation: flash 0.3s ease-in-out;
}

@keyframes flash {

    0%,
    100% {
        box-shadow: 0 0 0px rgba(220, 53, 69, 0.5);
    }

    50% {
        box-shadow: 0 0 6px rgba(220, 53, 69, 0.8);
    }
}
</style>