import apiClient from './authApi';

export interface AdminConfiguration {
  configId: string;
  configKey: string;
  configCategory: string;
  configValue: string;
  valueType: 'STRING' | 'NUMBER' | 'BOOLEAN' | 'JSON' | 'ARRAY';
  displayName: string;
  description?: string;
  defaultValue?: string;
  isEditable: boolean;
  isSensitive: boolean;
  validationRules?: {
    min?: number;
    max?: number;
    regex?: string;
    required?: boolean;
  };
  uiComponent?: string;
  options?: any;
  sortOrder: number;
  requiresRestart: boolean;
  lastModifiedBy?: string;
  lastModifiedAt?: string;
}

export interface Holiday {
  holidayId: string;
  holidayDate: string;
  holidayName: string;
  description?: string;
  holidayType: 'NATIONAL' | 'REGIONAL' | 'ORGANIZATIONAL' | 'OPTIONAL';
  isRecurring: boolean;
  recurrenceRule?: string;
  isActive: boolean;
  appliesToDepartments?: string[];
  appliesToLocations?: string[];
}

export interface ActivityType {
  activityTypeId: string;
  title: string;
  itemCode?: string | null;
  taxationType?: string | null;
  sapRefNo?: string | null;
  creditPostingOn?: string | null;
  isActive?: boolean;
}

/**
 * Get public configurations (accessible to all authenticated users)
 * Returns non-sensitive configurations like DOCUMENT_POLICY, WORKFLOW_SHARING, TAT_SETTINGS
 */
export const getPublicConfigurations = async (category?: string): Promise<AdminConfiguration[]> => {
  const params = category ? { category } : {};
  const response = await apiClient.get('/users/configurations', { params });
  return response.data.data;
};

/**
 * Get all admin configurations (admin only)
 */
export const getAllConfigurations = async (category?: string): Promise<AdminConfiguration[]> => {
  const params = category ? { category } : {};
  const response = await apiClient.get('/admin/configurations', { params });
  return response.data.data;
};

/**
 * Update a configuration value
 */
export const updateConfiguration = async (
  configKey: string,
  configValue: string
): Promise<void> => {
  await apiClient.put(`/admin/configurations/${configKey}`, { configValue });
};

/**
 * Reset configuration to default
 */
export const resetConfiguration = async (configKey: string): Promise<void> => {
  await apiClient.post(`/admin/configurations/${configKey}/reset`);
};

export interface Form16NotificationItem {
  enabled: boolean;
  template?: string;
}

/** 26AS data added: separate message for RE users and for dealers */
export interface Form16Notification26AsItem {
  enabled: boolean;
  templateRe?: string;
  templateDealers?: string;
}

export interface Form16AdminConfig {
  submissionViewerEmails: string[];
  twentySixAsViewerEmails: string[];
  reminderEnabled: boolean;
  reminderDays: number;
  notification26AsDataAdded?: Form16NotificationItem | Form16Notification26AsItem;
  /** RE reminder to upload 26AS (quarter end + N days) */
  reminder26AsUploadEnabled?: boolean;
  reminder26AsUploadAfterQuarterEndDays?: number;
  notificationForm16SuccessCreditNote?: Form16NotificationItem;
  notificationForm16Unsuccessful?: Form16NotificationItem;
  alertSubmitForm16Enabled?: boolean;
  /** Dealer reminder to submit Form 16A (quarter end + N days, repeat every X days) */
  alertSubmitForm16AfterQuarterEndDays?: number;
  alertSubmitForm16EveryDays?: number;
  alertSubmitForm16FrequencyDays?: number;
  alertSubmitForm16FrequencyHours?: number;
  /** When to run the alert job daily (HH:mm, 24h, server timezone). */
  alertSubmitForm16RunAtTime?: string;
  alertSubmitForm16Template?: string;
  reminderNotificationEnabled?: boolean;
  reminderFrequencyDays?: number;
  reminderFrequencyHours?: number;
  /** When to run the reminder job daily (HH:mm, 24h, server timezone). */
  reminderRunAtTime?: string;
  reminderNotificationTemplate?: string;
}

/**
 * Get Form 16 admin configuration
 */
export const getForm16Config = async (): Promise<Form16AdminConfig> => {
  const response = await apiClient.get<{ data: Form16AdminConfig }>('/admin/form16-config');
  return response.data.data ?? response.data;
};

/**
 * Update Form 16 admin configuration
 */
export const putForm16Config = async (config: Partial<Form16AdminConfig>): Promise<void> => {
  await apiClient.put('/admin/form16-config', config);
};

/**
 * Get all holidays
 */
export const getAllHolidays = async (year?: number): Promise<Holiday[]> => {
  const params = year ? { year } : {};
  const response = await apiClient.get('/admin/holidays', { params });
  return response.data.data;
};

/**
 * Get holiday calendar for a year
 */
export const getHolidayCalendar = async (year: number): Promise<any> => {
  const response = await apiClient.get(`/admin/holidays/calendar/${year}`);
  return response.data;
};

/**
 * Create a new holiday
 */
export const createHoliday = async (holiday: Partial<Holiday>): Promise<Holiday> => {
  const response = await apiClient.post('/admin/holidays', holiday);
  return response.data.data;
};

/**
 * Update a holiday
 */
export const updateHoliday = async (
  holidayId: string,
  updates: Partial<Holiday>
): Promise<Holiday> => {
  const response = await apiClient.put(`/admin/holidays/${holidayId}`, updates);
  return response.data.data;
};

/**
 * Delete a holiday
 */
export const deleteHoliday = async (holidayId: string): Promise<void> => {
  await apiClient.delete(`/admin/holidays/${holidayId}`);
};

/**
 * Bulk import holidays
 */
export const bulkImportHolidays = async (holidays: Partial<Holiday>[]): Promise<any> => {
  const response = await apiClient.post('/admin/holidays/bulk-import', { holidays });
  return response.data;
};

/**
 * Get all active activity types (requires authentication)
 */
export const getActivityTypes = async (): Promise<ActivityType[]> => {
  const response = await apiClient.get('/config/activity-types');
  return response.data.data;
};

/**
 * Get all activity types (admin only - includes inactive)
 */
export const getAllActivityTypes = async (activeOnly?: boolean): Promise<ActivityType[]> => {
  const params = activeOnly !== undefined ? { activeOnly: activeOnly.toString() } : {};
  const response = await apiClient.get('/admin/activity-types', { params });
  return response.data.data;
};

/**
 * Get a single activity type by ID (admin only)
 */
export const getActivityTypeById = async (activityTypeId: string): Promise<ActivityType> => {
  const response = await apiClient.get(`/admin/activity-types/${activityTypeId}`);
  return response.data.data;
};

/**
 * Create a new activity type (admin only)
 */
export const createActivityType = async (activityType: Partial<ActivityType>): Promise<ActivityType> => {
  const response = await apiClient.post('/admin/activity-types', activityType);
  return response.data.data;
};

/**
 * Update an activity type (admin only)
 */
export const updateActivityType = async (
  activityTypeId: string,
  updates: Partial<ActivityType>
): Promise<ActivityType> => {
  const response = await apiClient.put(`/admin/activity-types/${activityTypeId}`, updates);
  return response.data.data;
};

/**
 * Delete (deactivate) an activity type (admin only)
 */
export const deleteActivityType = async (activityTypeId: string): Promise<void> => {
  await apiClient.delete(`/admin/activity-types/${activityTypeId}`);
};

