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

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

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

interface TaskWorklogState {
  worklogs: TaskWorklog[];
  fetchWorklogs: () => 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: [],

  fetchWorklogs: async () => {
    const cached = await loadStored();
    if (cached) set({ worklogs: cached });
  },

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

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

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