import { useEffect, useState } from 'react';
import { apiRequest } from './api';
import type { ActivityType } from './activities';
import type { CalendarEventType } from './calendar';
import type { DealStage } from './deals';
import type { LeadStatus } from './leads';
import type { ProjectStatus } from './projects';
import type { TaskPriority, TaskType } from './tasks';

export interface DealStageOption {
  value: DealStage;
  label: string;
  probability: number;
  isOpen: boolean;
}

/** Fixed choice lists owned by the API (GET /api/options). */
export interface CrmOptions {
  leadSources: string[];
  defaultServices: string[];
  leadStatuses: LeadStatus[];
  dealStages: DealStageOption[];
  engagementModels: string[];
  lossReasons: string[];
  contactLifecycles: string[];
  projectStatuses: ProjectStatus[];
  budgetTypes: string[];
  taskTypes: TaskType[];
  taskPriorities: TaskPriority[];
  calendarEventTypes: CalendarEventType[];
  activityTypes: ActivityType[];
  productCategories: string[];
  productUnits: string[];
  gstRates: number[];
  paymentMethods: string[];
}

export const EMPTY_OPTIONS: CrmOptions = {
  leadSources: [],
  defaultServices: [],
  leadStatuses: [],
  dealStages: [],
  engagementModels: [],
  lossReasons: [],
  contactLifecycles: [],
  projectStatuses: [],
  budgetTypes: [],
  taskTypes: [],
  taskPriorities: [],
  calendarEventTypes: [],
  activityTypes: [],
  productCategories: [],
  productUnits: [],
  gstRates: [],
  paymentMethods: [],
};

let cached: Promise<CrmOptions> | null = null;

/** Loads the choice lists once per page load; a failed request is retried on the next call. */
export function loadCrmOptions(): Promise<CrmOptions> {
  if (!cached) {
    cached = apiRequest<CrmOptions>('/options').catch((err: unknown) => {
      cached = null;
      throw err;
    });
  }
  return cached;
}

/** Returns the API choice lists, with empty lists until they arrive or if they cannot be loaded. */
export function useCrmOptions(): CrmOptions {
  const [options, setOptions] = useState<CrmOptions>(EMPTY_OPTIONS);
  useEffect(() => {
    let active = true;
    loadCrmOptions()
      .then((res) => {
        if (active) setOptions(res);
      })
      .catch((err: unknown) => {
        console.error('Choice lists could not be loaded', err);
      });
    return () => {
      active = false;
    };
  }, []);
  return options;
}

/** Returns true for a source picked from the list, false for "Other" or "Other: <text>" (same rule as the API). */
export function isListedLeadSource(source?: string | null): boolean {
  return Boolean(source) && !/^Other(:|$)/i.test(source as string);
}
