'use client';

import { useEffect, useMemo } from 'react';
import { useProductStore } from '@/stores/useProductStore';
import { useVersionPlanStore } from '@/stores/useVersionPlanStore';
import { useRequirementStore } from '@/stores/useRequirementStore';
import { useDevTaskStore } from '@/stores/useDevTaskStore';
import { useTestCaseStore } from '@/stores/useTestCaseStore';
import { useBugStore } from '@/stores/useBugStore';
import { useAuthStore } from '@/stores/useAuthStore';
import { flattenVersions } from '@/lib/derive';
import { aggregateWorkItems } from '@/lib/workspace-engine';

export function useWorkspaceWorkItems({ autoFetch = true }: { autoFetch?: boolean } = {}) {
  const { overview, fetchOverview } = useProductStore();
  const { plans, fetchPlans } = useVersionPlanStore();
  const { requirements, fetchRequirements } = useRequirementStore();
  const { tasks: devTasks, fetchTasks } = useDevTaskStore();
  const { testCases, fetchTestCases } = useTestCaseStore();
  const { bugs, fetchBugs } = useBugStore();
  const user = useAuthStore((s) => s.user);

  useEffect(() => { if (autoFetch) fetchOverview(); }, [autoFetch, fetchOverview]);
  useEffect(() => { if (autoFetch) fetchPlans(); }, [autoFetch, fetchPlans]);
  useEffect(() => { if (autoFetch) fetchRequirements(); }, [autoFetch, fetchRequirements]);
  useEffect(() => { if (autoFetch) fetchTasks(); }, [autoFetch, fetchTasks]);
  useEffect(() => { if (autoFetch) fetchTestCases(); }, [autoFetch, fetchTestCases]);
  useEffect(() => { if (autoFetch) fetchBugs(); }, [autoFetch, fetchBugs]);

  const userName = user?.name ?? '';
  const allVersions = useMemo(() => flattenVersions(overview), [overview]);

  const versionMap = useMemo(() => {
    const map = new Map<string, { id: string; name: string; productName: string; projectName: string }>();
    allVersions.forEach((version) => {
      map.set(version.id, {
        id: version.id,
        name: version.name,
        productName: version.productName,
        projectName: version.projectName,
      });
    });
    return map;
  }, [allVersions]);

  const requirementVersionMap = useMemo(() => {
    const map = new Map<string, string>();
    requirements.forEach((requirement) => {
      if (requirement.versionId) map.set(requirement.id, requirement.versionId);
    });
    return map;
  }, [requirements]);

  const workItems = useMemo(
    () => aggregateWorkItems(userName, plans, devTasks, testCases, bugs, versionMap, requirementVersionMap),
    [userName, plans, devTasks, testCases, bugs, versionMap, requirementVersionMap],
  );

  return {
    userName,
    allVersions,
    versionMap,
    requirementVersionMap,
    workItems,
    devTasks,
    testCases,
    bugs,
  };
}
