import client from '../client';
import type { PaginatedResponse } from '../types';

export type ActionType = 'ai_suggestion' | 'alert' | 'followup' | 'data_anomaly';
export type ActionPriority = 'urgent' | 'high' | 'medium' | 'low';
export type ActionStatus = 'pending' | 'in_progress' | 'completed' | 'dismissed';

export interface ActionItem {
  id: string;
  action_type: ActionType;
  priority: ActionPriority;
  status: ActionStatus;
  title: string;
  summary: string;
  patient_id: string;
  patient_name: string;
  source_ref: string;
  created_at: string;
  updated_at: string;
}

export interface ThreadEvent {
  step: string;
  label: string;
  status: ActionStatus;
  detail?: string;
  timestamp?: string;
  operator?: string;
  link_to?: string;
}

export interface ActionDefinition {
  key: string;
  label: string;
  variant: 'primary' | 'danger' | 'default';
  api_endpoint?: string;
}

export interface ThreadResponse {
  action_item: ActionItem;
  thread: ThreadEvent[];
  available_actions: ActionDefinition[];
}

export interface WorkbenchStats {
  total_pending: number;
  ai_suggestion_pending: number;
  urgent_alerts: number;
  followup_due: number;
  completion_rate: number | null;
}

export interface NursePatientSummary {
  patient_id: string;
  patient_name: string;
  pending_actions: number;
  highest_priority: ActionPriority;
}

export interface TeamMemberOverview {
  user_id: string;
  name: string;
  title: string;
  pending_count: number;
  completed_count: number;
  overdue_count: number;
  completion_rate: number;
}

export interface TeamOverview {
  members: TeamMemberOverview[];
  risk_distribution: {
    high: number;
    medium: number;
    low: number;
  };
  total_pending: number;
  total_completed: number;
}

export const actionInboxApi = {
  list: async (params?: {
    status?: string;
    type?: string;
    page?: number;
    page_size?: number;
    assigned_to_me?: boolean;
    patient_id?: string;
  }) => {
    const { data } = await client.get<{
      success: boolean;
      data: PaginatedResponse<ActionItem>;
    }>('/health/action-inbox', { params });
    return data.data;
  },

  getThread: async (sourceRef: string) => {
    const { data } = await client.get<{
      success: boolean;
      data: ThreadResponse;
    }>(`/health/action-inbox/${encodeURIComponent(sourceRef)}/thread`);
    return data.data;
  },

  stats: async (params?: { assigned_to_me?: boolean }) => {
    const { data } = await client.get<{
      success: boolean;
      data: WorkbenchStats;
    }>('/health/action-inbox/stats', { params });
    return data.data;
  },

  myPatients: async () => {
    const { data } = await client.get<{
      success: boolean;
      data: NursePatientSummary[];
    }>('/health/action-inbox/my-patients');
    return data.data;
  },

  team: async () => {
    const { data } = await client.get<{
      success: boolean;
      data: TeamOverview;
    }>('/health/action-inbox/team');
    return data.data;
  },
};
