'use client';
import { create } from 'zustand';
import type { TaskWorklog } from '@/lib/task-worklog';
import { loadServerData, saveServerData, SERVER_DATA_CACHE_MS } from '@/lib/server-data';

function saveStored(items: TaskWorklog[]) {
  saveServerData('task-worklogs', items).catch(() => {});
}

let lastWorklogsFetchAt = 0;

async function loadStored(): Promise<TaskWorklog[] | null> {
  try {
    return await loadServerData<TaskWorklog[]>('task-worklogs');
  } catch {}
  return null;
}

interface TaskWorklogState {
  worklogs: TaskWorklog[];
  loaded: boolean;
  fetchWorklogs: (options?: { force?: boolean }) => Promise<void>;
  addWorklog: (data: Omit<TaskWorklog, 'id' | 'createdAt'>) => void;
  deleteWorklog: (id: string) => void;
  getActualHours: (taskId: string) => number;
}

export const useTaskWorklogStore = create<TaskWorklogState>((set, get) => ({
  worklogs: [],
  loaded: false,

  fetchWorklogs: async (options) => {
    if (!options?.force && get().loaded && Date.now() - lastWorklogsFetchAt < SERVER_DATA_CACHE_MS) return;
    const cached = await loadStored();
    if (!options?.force && get().loaded && Date.now() - lastWorklogsFetchAt < SERVER_DATA_CACHE_MS) return;
    lastWorklogsFetchAt = Date.now();
    set({ worklogs: cached ?? [], loaded: true });
  },

  addWorklog: (data) => {
    const item: TaskWorklog = {
      ...data,
      id: `wl-${Date.now()}`,
      createdAt: new Date().toISOString(),
    };
    const updated = [...get().worklogs, item];
    set({ worklogs: updated, loaded: true });
    saveStored(updated);
  },

  deleteWorklog: (id) => {
    const updated = get().worklogs.filter((w) => w.id !== id);
    set({ worklogs: updated, loaded: true });
    saveStored(updated);
  },

  getActualHours: (taskId) => {
    return get().worklogs
      .filter((w) => w.taskId === taskId)
      .reduce((sum, w) => sum + w.hours, 0);
  },
}));
