import type { LabTaskStatus, TaskSortField } from '@/types/cases';
import type { TasksViewState } from '@/components/lab/tasksViewDefaults';

/** Apply Tasks tab URL query params from Today deep links. */
export function parseTasksSearchParams(
  searchParams: URLSearchParams,
): Partial<TasksViewState> {
  const partial: Partial<TasksViewState> = {};

  if (searchParams.get('importantOnly') === '1') {
    partial.importantOnly = true;
  }
  if (searchParams.get('overdueOnly') === '1') {
    partial.overdueOnly = true;
  }
  if (searchParams.get('unassignedOnly') === '1') {
    partial.unassignedOnly = true;
  }
  const origin = searchParams.get('origin');
  if (origin === 'CLINIC_DISPATCH' || origin === 'LAB_INTERNAL') {
    partial.origin = origin;
  }

  const status = searchParams.get('status');
  if (status === 'IN_PROGRESS' || status === 'COMPLETED') {
    partial.statusFilter = status;
  } else if (status === 'all') {
    partial.statusFilter = '';
  }

  const prosthesisTypeCode = searchParams.get('prosthesisTypeCode')?.trim();
  if (prosthesisTypeCode) {
    partial.prosthesisTypeCode = prosthesisTypeCode;
    partial.sortBy = 'prosthesis';
    partial.sortDir = 'desc';
  }

  const sortBy = searchParams.get('sortBy');
  if (
    sortBy === 'date' ||
    sortBy === 'status' ||
    sortBy === 'clinic' ||
    sortBy === 'patient' ||
    sortBy === 'important' ||
    sortBy === 'prosthesis' ||
    sortBy === 'taskType' ||
    sortBy === 'dueDate'
  ) {
    partial.sortBy = sortBy as TaskSortField;
  }

  const sortDir = searchParams.get('sortDir');
  if (sortDir === 'asc' || sortDir === 'desc') {
    partial.sortDir = sortDir;
  }

  return partial;
}
