import { ref } from 'vue';
import { defineStore } from 'pinia';
import {
    type ApiReminder,
    type CreateReminderPayload,
    type ListRemindersParams,
    type ReminderCounts,
    type ReminderFilter,
    type UpdateReminderPayload,
    completeReminder,
    createReminder,
    deleteReminder,
    listReminders,
    updateReminder,
} from '../api/reminders';

/**
 * Pinia store для напоминаний (RemindersView + nav-badge в AppLayout
 * + DealDetailDrawer-секция).
 *
 * Стратегия: counts всегда обновляются на load() — даже если items
 * фильтруются. nav-badge в AppLayout биндит counts.active.
 *
 * Optimistic-updates для complete/delete с revert на reject.
 */
export const useRemindersStore = defineStore('reminders', () => {
    const items = ref<ApiReminder[]>([]);
    const counts = ref<ReminderCounts>({ active: 0, today: 0, upcoming: 0, overdue: 0 });
    const loading = ref(false);
    const fetchError = ref(false);
    const currentFilter = ref<ReminderFilter>('active');

    async function load(params: ListRemindersParams = {}): Promise<void> {
        loading.value = true;
        fetchError.value = false;
        try {
            const response = await listReminders(params);
            items.value = response.items;
            counts.value = response.counts;
            currentFilter.value = params.filter ?? 'active';
        } catch {
            fetchError.value = true;
        } finally {
            loading.value = false;
        }
    }

    async function refreshCounts(): Promise<void> {
        // Лёгкий запрос только для bell-badge: limit=1, нам важны counts.
        try {
            const response = await listReminders({ filter: 'active', limit: 1 });
            counts.value = response.counts;
        } catch {
            /* silent */
        }
    }

    async function create(payload: CreateReminderPayload): Promise<ApiReminder | null> {
        try {
            const reminder = await createReminder(payload);
            // Если новый reminder подходит под текущий filter и deal — добавляем в начало.
            // (load() в любом случае пересчитает counts, но optimistic покажет сразу.)
            items.value = [reminder, ...items.value];
            counts.value.active++;
            return reminder;
        } catch {
            return null;
        }
    }

    async function update(id: number, payload: UpdateReminderPayload): Promise<ApiReminder | null> {
        try {
            const updated = await updateReminder(id, payload);
            const idx = items.value.findIndex((r) => r.id === id);
            if (idx >= 0) items.value.splice(idx, 1, updated);
            return updated;
        } catch {
            return null;
        }
    }

    async function complete(id: number): Promise<void> {
        const item = items.value.find((r) => r.id === id);
        if (!item || item.completed_at !== null) return;

        // Optimistic.
        const previous = item.completed_at;
        item.completed_at = new Date().toISOString();
        counts.value.active = Math.max(0, counts.value.active - 1);

        try {
            const updated = await completeReminder(id);
            item.completed_at = updated.completed_at;
            // Если фильтр active — убираем из items.
            if (
                currentFilter.value === 'active' ||
                currentFilter.value === 'today' ||
                currentFilter.value === 'upcoming' ||
                currentFilter.value === 'overdue'
            ) {
                items.value = items.value.filter((r) => r.id !== id);
            }
        } catch {
            // Revert.
            item.completed_at = previous;
            counts.value.active++;
        }
    }

    async function remove(id: number): Promise<void> {
        const item = items.value.find((r) => r.id === id);
        if (!item) return;
        const wasActive = item.completed_at === null;
        const previousItems = [...items.value];
        const previousCounts = { ...counts.value };

        // Optimistic.
        items.value = items.value.filter((r) => r.id !== id);
        if (wasActive) counts.value.active = Math.max(0, counts.value.active - 1);

        try {
            await deleteReminder(id);
        } catch {
            // Revert.
            items.value = previousItems;
            counts.value = previousCounts;
        }
    }

    function reset(): void {
        items.value = [];
        counts.value = { active: 0, today: 0, upcoming: 0, overdue: 0 };
        fetchError.value = false;
    }

    return {
        items,
        counts,
        loading,
        fetchError,
        currentFilter,
        load,
        refreshCounts,
        create,
        update,
        complete,
        remove,
        reset,
    };
});
