import { writable } from 'svelte/store';
import { getSupabase } from '$lib/supabase';
import { generateId } from '$lib/utils/id';
import type { Task, TaskList } from '@colectivo/types';

// ── Task lists store (overview page) ──────────────────────────────────────────

export const taskLists = writable<TaskList[]>([]);
export const taskListsLoading = writable(false);

export async function loadTaskLists(collectiveId: string) {
	taskListsLoading.set(true);
	const { data, error } = await getSupabase()
		.from('task_lists')
		.select('*')
		.eq('collective_id', collectiveId)
		.order('created_at', { ascending: false });

	if (!error && data) {
		taskLists.set(data as TaskList[]);
	}
	taskListsLoading.set(false);
}

export async function createTaskList(
	collectiveId: string,
	name: string,
	userId: string
): Promise<TaskList | null> {
	const tempId = generateId();
	const optimistic: TaskList = {
		id: tempId,
		collective_id: collectiveId,
		name,
		created_by: userId,
		created_at: new Date().toISOString()
	};
	taskLists.update((ls) => [optimistic, ...ls]);

	const { data, error } = await getSupabase()
		.from('task_lists')
		.insert({ collective_id: collectiveId, name, created_by: userId })
		.select()
		.single();

	if (error || !data) {
		taskLists.update((ls) => ls.filter((l) => l.id !== tempId));
		return null;
	}

	const real = data as TaskList;
	taskLists.update((ls) => ls.map((l) => (l.id === tempId ? real : l)));
	return real;
}

export async function renameTaskList(id: string, name: string) {
	taskLists.update((ls) => ls.map((l) => (l.id === id ? { ...l, name } : l)));
	await getSupabase().from('task_lists').update({ name }).eq('id', id);
}

export async function deleteTaskList(id: string) {
	taskLists.update((ls) => ls.filter((l) => l.id !== id));
	await getSupabase().from('task_lists').delete().eq('id', id);
}

// ── Task operations (used by [id] page) ───────────────────────────────────────

export async function loadTasks(listId: string): Promise<Task[]> {
	const { data, error } = await getSupabase()
		.from('tasks')
		.select('*')
		.eq('list_id', listId)
		.order('sort_order', { ascending: true });

	if (error || !data) return [];
	return data as Task[];
}

export async function addTask(
	listId: string,
	title: string,
	userId: string,
	sortOrder: number
): Promise<Task | null> {
	const { data, error } = await getSupabase()
		.from('tasks')
		.insert({ list_id: listId, title, sort_order: sortOrder, created_by: userId })
		.select()
		.single();

	if (error || !data) return null;
	return data as Task;
}

export async function renameTask(id: string, title: string) {
	await getSupabase().from('tasks').update({ title }).eq('id', id);
}

export async function completeTask(id: string, userId: string, completed: boolean) {
	const patch = completed
		? { is_completed: true, completed_by: userId, completed_at: new Date().toISOString() }
		: { is_completed: false, completed_by: null, completed_at: null };
	await getSupabase().from('tasks').update(patch).eq('id', id);
}

export async function deleteTask(id: string) {
	await getSupabase().from('tasks').delete().eq('id', id);
}

export async function reorderTasks(tasks: Pick<Task, 'id'>[]) {
	await Promise.all(
		tasks.map((t, idx) => getSupabase().from('tasks').update({ sort_order: idx }).eq('id', t.id))
	);
}
