import { useMemo } from 'react';
import { useSearchParams } from 'react-router-dom';

import { endOfMonth, isValid, parseISO, startOfMonth } from 'date-fns';

import { Incidence } from 'src/types/timeTracking';

export type TimesheetDeeplinkState = {
  deeplinkRange: { from: Date; to: Date } | null;
  deeplinkDate: string | null;
  deeplinkIncidenceType: Incidence | null;
};

export const useTimesheetDeeplink = (): TimesheetDeeplinkState => {
  const [searchParams] = useSearchParams();

  const dateParam = searchParams.get('date');
  const incidenceTypeParam = searchParams.get('incidenceType');

  const deeplink = useMemo(() => {
    if (!dateParam) return { range: null, deeplinkDate: null };
    const parsed = parseISO(dateParam);
    // Invalid date param → still treat as a deeplink intent, fall back to the
    // current month so the table is populated. No target row.
    const target = isValid(parsed) ? parsed : new Date();
    return {
      range: { from: startOfMonth(target), to: endOfMonth(target) },
      deeplinkDate: isValid(parsed) ? dateParam : null,
    };
  }, [dateParam]);

  const deeplinkIncidenceType = useMemo<Incidence | null>(() => {
    if (!incidenceTypeParam) return null;
    return Object.values(Incidence).find(v => v === incidenceTypeParam) ?? null;
  }, [incidenceTypeParam]);

  return {
    deeplinkRange: deeplink.range,
    deeplinkDate: deeplink.deeplinkDate,
    deeplinkIncidenceType,
  };
};
