import type { TodayWidgetKey } from '@/types/today';

/**
 * Feature domains for Today dashboard gadgets, ordered like app permissions:
 * owner-only → staff → organizations → patients → appointments → treatment → cases → tasks
 */
export type TodayGadgetFeature =
  | 'owner'
  | 'staff'
  | 'organizations'
  | 'patients'
  | 'appointments'
  | 'treatment'
  | 'cases'
  | 'tasks';

export const TODAY_GADGET_FEATURE_SORT_ORDER: Record<TodayGadgetFeature, number> = {
  owner: 0,
  staff: 10,
  organizations: 20,
  patients: 30,
  appointments: 40,
  treatment: 50,
  cases: 60,
  tasks: 70,
};

/** KPI widgets — keyed by TodayWidgetKey. */
export const TODAY_KPI_GADGET_FEATURE: Record<TodayWidgetKey, TodayGadgetFeature> = {
  appointmentsToday: 'appointments',
  patientsToday: 'patients',
  treatmentsToday: 'treatment',
  labCasesPendingSend: 'treatment',
  providersWithoutWorkingHours: 'staff',
  casesReceivedToday: 'cases',
  casesInProgress: 'cases',
  tasksInProgress: 'tasks',
  importantTasks: 'tasks',
  overdueCases: 'tasks',
  unassignedTasks: 'tasks',
  pendingConnections: 'organizations',
  pendingStaffInvites: 'staff',
};

/** Charts and composite gadgets — keyed by stable cell id. */
export const TODAY_GADGET_ID_FEATURE: Record<string, TodayGadgetFeature> = {
  subscription: 'owner',
  'case-completion': 'cases',
  'treatment-plan-completion': 'treatment',
  'upcoming-appointments': 'treatment',
  'chart-efficiency-report': 'owner',
  'chart-appointments-week-all': 'appointments',
  'chart-appointments-week-mine': 'treatment',
  'chart-appointments-by-provider': 'appointments',
  'chart-treatment-mix': 'treatment',
  'chart-lab-task-activity': 'cases',
  'chart-tasks-by-prosthesis': 'tasks',
  'chart-cases-due-week': 'cases',
  'chart-case-partners-month': 'treatment',
};

export function todayGadgetFeatureSortRank(feature: TodayGadgetFeature): number {
  return TODAY_GADGET_FEATURE_SORT_ORDER[feature];
}

export function getTodayGadgetFeatureOrder(gadgetId: string): number {
  const direct = TODAY_GADGET_ID_FEATURE[gadgetId];
  if (direct) {
    return todayGadgetFeatureSortRank(direct);
  }

  if (gadgetId.startsWith('kpi-')) {
    const key = gadgetId.slice(4) as TodayWidgetKey;
    const feature = TODAY_KPI_GADGET_FEATURE[key];
    if (feature) {
      return todayGadgetFeatureSortRank(feature);
    }
  }

  return Number.MAX_SAFE_INTEGER;
}
