import { useMemo } from 'react';
import { trpc } from '@/lib/trpc';
import { ProjectTimelineBox, type ProjectGroup } from '@/components/timeline/ProjectTimelineBox';
import type { TimelineEvent } from '@/components/timeline/ProjectTimeline';
import type { TimelineBlockData } from '../../../../../shared/api-types';

export function ChatTimelineBlock({ data }: { data: TimelineBlockData }) {
  const { events: rawEvents } = data;

  const { data: allProjects } = trpc.projects.list.useQuery({ includeArchived: true });

  const events = useMemo<TimelineEvent[]>(() => {
    return rawEvents
      .map((event) => ({
        id: event.id,
        title: event.title,
        date: event.date,
        endDate: event.endDate ?? null,
        type: ((event as { type?: string }).type ?? 'milestone') as TimelineEvent['type'],
        projectId: event.projectId ?? null,
        isCompleted: event.isCompleted ?? 0,
        isAiSuggested: event.isAiSuggested ?? 0,
      }))
      .filter((event) => Number.isFinite(event.date));
  }, [rawEvents]);

  const groups = useMemo<ProjectGroup[]>(() => {
    const PAD_MS = 3 * 24 * 60 * 60 * 1000;
    const now = Date.now();

    const byProject = new Map<string, TimelineEvent[]>();
    for (const event of events) {
      const key = event.projectId ?? '__unassigned__';
      const current = byProject.get(key);
      if (current) {
        current.push(event);
      } else {
        byProject.set(key, [event]);
      }
    }

    const builtGroups: ProjectGroup[] = [];
    for (const [key, projectEvents] of byProject.entries()) {
      const projectId = key === '__unassigned__' ? null : key;
      const project = projectId
        ? allProjects?.find((p) => p.id === projectId)
        : undefined;

      const dates = projectEvents.flatMap((event) => (event.endDate ? [event.date, event.endDate] : [event.date]));
      const minDate = Math.min(...dates, now);
      const maxDate = Math.max(...dates, now);

      builtGroups.push({
        projectId,
        projectName: project?.name ?? 'Timeline',
        projectStatus: project?.status ?? 'active',
        breadcrumb: [],
        events: projectEvents,
        startDate: new Date(minDate - PAD_MS),
        endDate: new Date(maxDate + PAD_MS),
      });
    }

    return builtGroups.sort((a, b) => a.projectName.localeCompare(b.projectName));
  }, [events, allProjects]);

  if (!events.length) return null;

  return (
    <div className="w-full flex flex-col gap-3">
      {groups.map((group) => (
        <ProjectTimelineBox
          key={group.projectId ?? 'unassigned'}
          group={group}
        />
      ))}
    </div>
  );
}
