'use client';

import { useEffect, useMemo, useState } 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';
import { loadV22WorkspaceData, type V22WorkspaceData } from '@/lib/v22-api';
import { selectWorkspaceCollections } from '@/lib/workspace-v22-source';

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);
  const [v22WorkspaceData, setV22WorkspaceData] = useState<V22WorkspaceData | null>(null);
  const [v22WorkspaceLoaded, setV22WorkspaceLoaded] = useState(false);
  const [v22WorkspaceFailed, setV22WorkspaceFailed] = useState(false);

  useEffect(() => { if (autoFetch) fetchOverview(); }, [autoFetch, fetchOverview]);

  const userName = user?.name ?? '';
  const workspaceUserKey = userName || user?.id || '';
  useEffect(() => {
    if (!autoFetch || !workspaceUserKey.trim()) {
      setV22WorkspaceData(null);
      setV22WorkspaceLoaded(false);
      setV22WorkspaceFailed(false);
      return;
    }

    let cancelled = false;
    setV22WorkspaceLoaded(false);
    setV22WorkspaceFailed(false);
    loadV22WorkspaceData(workspaceUserKey)
      .then((data) => {
        if (cancelled) return;
        setV22WorkspaceData(data);
        setV22WorkspaceLoaded(true);
      })
      .catch(() => {
        if (cancelled) return;
        setV22WorkspaceData(null);
        setV22WorkspaceFailed(true);
      });

    return () => {
      cancelled = true;
    };
  }, [autoFetch, workspaceUserKey]);

  useEffect(() => {
    if (!autoFetch || !workspaceUserKey.trim() || !v22WorkspaceFailed) return;
    void fetchPlans();
    void fetchRequirements();
    void fetchTasks();
    void fetchTestCases();
    void fetchBugs();
  }, [
    autoFetch,
    fetchBugs,
    fetchPlans,
    fetchRequirements,
    fetchTasks,
    fetchTestCases,
    v22WorkspaceFailed,
    workspaceUserKey,
  ]);

  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 workspaceCollections = useMemo(
    () => selectWorkspaceCollections({
      v22Loaded: v22WorkspaceLoaded,
      v22Failed: v22WorkspaceFailed,
      v22Data: v22WorkspaceData,
      appData: { plans, devTasks, testCases, bugs },
    }),
    [bugs, devTasks, plans, testCases, v22WorkspaceData, v22WorkspaceFailed, v22WorkspaceLoaded],
  );

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

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