'use client';
import { create } from 'zustand';
import type { VersionPlan, PlanType } from '@/lib/version-plan';
import { loadServerData, saveServerData, SERVER_DATA_CACHE_MS } from '@/lib/server-data';
import { getPlanCompletionState } from '@/lib/version-plan-workflow';
import type { PlanResultPayload } from '@/lib/version-plan-workflow';
import {
  makeVersionPlanCompletedActivity,
  makeVersionPlanCreatedActivity,
  makeVersionPlanRequirementProgressActivity,
  makeVersionPlanResearchDirectionProgressActivity,
  makeVersionPlanStartedActivity,
} from '@/lib/work-activity-factory';
import type { WorkActivityDraft } from '@/lib/work-activity';
import { useWorkActivityStore } from './useWorkActivityStore';

const MOCK_PLANS: VersionPlan[] = [];
let lastPlansFetchAt = 0;

function saveStored(plans: VersionPlan[]) {
  saveServerData('version-plans', plans).catch(() => {});
}

async function loadStored(): Promise<VersionPlan[] | null> {
  try {
    return await loadServerData<VersionPlan[]>('version-plans');
  } catch {}
  return null;
}

interface VersionPlanState {
  plans: VersionPlan[];
  loaded: boolean;
  fetchPlans: (options?: { force?: boolean }) => Promise<void>;
  createPlan: (data: Omit<VersionPlan, 'id' | 'createdAt'>) => void;
  updatePlan: (id: string, data: Partial<VersionPlan>) => void;
  completePlan: (id: string, result: PlanResultPayload) => { ok: boolean; message?: string };
  deletePlan: (id: string) => void;
}

export const useVersionPlanStore = create<VersionPlanState>((set, get) => ({
  plans: MOCK_PLANS,
  loaded: false,

  fetchPlans: async (options) => {
    if (!options?.force && get().loaded && Date.now() - lastPlansFetchAt < SERVER_DATA_CACHE_MS) return;
    const cached = await loadStored();
    if (!options?.force && get().loaded && Date.now() - lastPlansFetchAt < SERVER_DATA_CACHE_MS) return;
    lastPlansFetchAt = Date.now();
    set({ plans: cached ?? MOCK_PLANS, loaded: true });
  },

  createPlan: (data) => {
    const plan: VersionPlan = { ...data, id: `plan-${Date.now()}`, createdAt: new Date().toISOString().slice(0, 10) };
    const plans = [...get().plans, plan];
    set({ plans, loaded: true });
    saveStored(plans);
    useWorkActivityStore.getState().addActivity(makeVersionPlanCreatedActivity(plan, plan.addedBy || plan.owner));
  },

  updatePlan: (id, data) => {
    const now = new Date().toISOString();
    const activities: WorkActivityDraft[] = [];
    const plans = get().plans.map((p) => {
      if (p.id !== id) return p;
      const patch = { ...data };
      if (patch.status === 'in_progress' && !p.actualStartAt) {
        (patch as any).actualStartAt = now;
      }
      if (patch.status === 'completed' && !p.completedAt) {
        (patch as any).completedAt = now;
      }
      const next = { ...p, ...patch };
      if (p.status !== 'in_progress' && next.status === 'in_progress') {
        activities.push(makeVersionPlanStartedActivity(next, next.owner));
      }
      if (p.status !== 'completed' && next.status === 'completed') {
        activities.push(makeVersionPlanCompletedActivity(next, next.owner));
      }
      const previousLogIds = new Set((p.logs ?? []).map((log) => log.id));
      for (const log of next.logs ?? []) {
        if (previousLogIds.has(log.id)) continue;
        const requirementActivity = makeVersionPlanRequirementProgressActivity(next, log);
        if (requirementActivity) activities.push(requirementActivity);
        const directionActivity = makeVersionPlanResearchDirectionProgressActivity(next, log);
        if (directionActivity) activities.push(directionActivity);
      }
      return next;
    });
    set({ plans, loaded: true });
    saveStored(plans);
    activities.forEach((activity) => useWorkActivityStore.getState().addActivity(activity));
  },

  completePlan: (id, result) => {
    let response: { ok: boolean; message?: string } = { ok: false, message: '计划不存在' };
    const plans = get().plans.map((p) => {
      if (p.id !== id) return p;
      const next = { ...p, ...result, status: 'completed' as const, completedAt: new Date().toISOString() };
      const state = getPlanCompletionState(next);
      if (!state.canComplete) {
        response = { ok: false, message: state.missingReasons.join('、') || '计划未满足完成条件' };
        return p;
      }
      response = { ok: true };
      useWorkActivityStore.getState().addActivity(makeVersionPlanCompletedActivity(next, next.owner));
      return next;
    });
    set({ plans, loaded: true });
    saveStored(plans);
    return response;
  },

  deletePlan: (id) => {
    const plans = get().plans.filter((p) => p.id !== id);
    set({ plans, loaded: true });
    saveStored(plans);
  },
}));
