import React, { useMemo } from 'react';
import { useParams } from 'react-router-dom';
import { PageSection } from '@/shared/components/layout/PageSection';
import { PanelLoadingState } from '@/shared/components/ui/PageState';
import { useLocale } from '@/app/providers/LocaleProvider';
import { ProjectPageShell } from '@/features/projects/components/ProjectPageShell';
import { GanttTimeline } from '@/features/projects/components/GanttTimeline';
import { useProjectGantt } from '@/features/projects/hooks/useProjectGantt';

const DAY_MS = 86400000;

const ProjectGanttPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const { t } = useLocale();

  const projectGantt = useProjectGantt(id);

  // Derive the visible window from the project's actual schedule so the only
  // control the user touches is the timeline zoom (no duplicate range strip).
  const { rangeStart, rangeEnd } = useMemo(() => {
    const items = [
      ...(projectGantt.data?.timeline ?? []),
      ...(projectGantt.data?.milestones ?? []),
    ];
    const times: number[] = [];
    items.forEach((item) => {
      const start = item.start_date ? new Date(item.start_date).getTime() : NaN;
      const end = item.end_date ? new Date(item.end_date).getTime() : NaN;
      if (!Number.isNaN(start)) times.push(start);
      if (!Number.isNaN(end)) times.push(end);
    });

    const now = new Date();
    if (times.length === 0) {
      return {
        rangeStart: new Date(now.getFullYear(), 0, 1),
        rangeEnd: new Date(now.getFullYear(), 11, 31),
      };
    }

    const min = Math.min(...times);
    const max = Math.max(...times);
    // Pad by a week on each side for breathing room, and always include "today".
    return {
      rangeStart: new Date(Math.min(min, now.getTime()) - 7 * DAY_MS),
      rangeEnd: new Date(Math.max(max, now.getTime()) + 7 * DAY_MS),
    };
  }, [projectGantt.data]);

  if (!id) {
    return null;
  }

  return (
    <ProjectPageShell projectId={id}>
      {() => (
        <PageSection title={t('projects:nav.projectGantt')}>
          <p style={{ marginBottom: '1.5rem', fontSize: '0.875rem', color: 'var(--text-secondary, #666)' }}>
            {t('projects:gantt.projectSubtitle')}
          </p>
          {projectGantt.isLoading ? (
            <PanelLoadingState label={t('projects:states.loading')} />
          ) : projectGantt.data ? (
            <GanttTimeline
              variant="project"
              data={projectGantt.data}
              rangeStart={rangeStart}
              rangeEnd={rangeEnd}
            />
          ) : null}
        </PageSection>
      )}
    </ProjectPageShell>
  );
};

export default ProjectGanttPage;
