import { apiRequest } from './api';
import type { BadgeTone } from '../components/platform/platformTypes';
import type { CrmNote } from './leads';

export type DealStage = 'QUALIFICATION' | 'NEEDS_ANALYSIS' | 'PROPOSAL' | 'NEGOTIATION' | 'CLOSED_WON' | 'CLOSED_LOST';

export type DealTabView = 'all' | 'mine' | 'closing' | 'won' | 'lost';
export type DealView = DealTabView | 'board';
export type DealSort = 'title' | 'stage' | 'amount' | 'closeDate' | 'stageChangedAt' | 'owner' | 'createdAt';

export const STAGE_META: Record<
  DealStage,
  {
    label: string;
    tone: BadgeTone;
    color: string;
  }
> = {
  QUALIFICATION: {
    label: 'Qualification',
    tone: 'gray',
    color: '#64748B',
  },
  NEEDS_ANALYSIS: {
    label: 'Needs analysis',
    tone: 'blue',
    color: '#2563EB',
  },
  PROPOSAL: {
    label: 'Proposal',
    tone: 'indigo',
    color: '#7C3AED',
  },
  NEGOTIATION: {
    label: 'Negotiation',
    tone: 'amber',
    color: '#D97706',
  },
  CLOSED_WON: {
    label: 'Closed won',
    tone: 'green',
    color: '#059669',
  },
  CLOSED_LOST: {
    label: 'Closed lost',
    tone: 'red',
    color: '#DC2626',
  },
};

export const DEAL_VIEWS: Array<{ key: DealTabView; label: string }> = [
  { key: 'all', label: 'Open deals' },
  { key: 'mine', label: 'My deals' },
  { key: 'won', label: 'Won' },
  { key: 'lost', label: 'Lost' },
];

export interface Deal {
  id: string;
  dealNumber: string;
  title: string;
  amount: number;
  stage: DealStage;
  closeDate: string | null;
  engagementModel: string | null;
  estimatedHours: number | null;
  stageChangedAt: string;
  closedAt: string | null;
  lossReason: string | null;
  competitor: string | null;
  lostNotes: string | null;
  accountId: string;
  contactId: string | null;
  ownerId: string | null;
  account: { id: string; name: string };
  contact: { id: string; name: string; email: string } | null;
  owner: { id: string; name: string } | null;
  probability: number;
  weightedAmount: number;
  daysInStage: number;
  createdAt: string;
  updatedAt: string;
}

export interface DealStageHistoryEntry {
  id: string;
  fromStage: DealStage | null;
  toStage: DealStage;
  note: string | null;
  createdAt: string;
  changedBy: { id: string; name: string } | null;
}

export interface DealDetail extends Deal {
  stageHistory: DealStageHistoryEntry[];
  convertedLeads: Array<{ id: string; name: string }>;
}

export type DealCounts = Record<DealTabView, number>;

export interface DealStats {
  openPipeline: number;
  weightedForecast: number;
  wonValue: number;
  averageDealSize: number;
  openCount: number;
  totalDeals: number;
}

export interface DealSummary {
  counts: DealCounts;
  stats: DealStats;
}

export interface DealPage {
  items: Deal[];
  total: number;
  page: number;
  pageSize: number;
  counts: DealCounts;
  stats: DealStats;
}

export interface DealInput {
  title: string;
  accountId: string;
  contactId?: string | null;
  amount: number;
  stage?: DealStage;
  closeDate?: string | null;
  engagementModel?: string | null;
  estimatedHours?: number | null;
  ownerId?: string | null;
  lossReason?: string | null;
  competitor?: string | null;
  lostNotes?: string | null;
}

export interface MoveDealStageInput {
  stage: DealStage;
  note?: string | null;
  lossReason?: string | null;
  competitor?: string | null;
  lostNotes?: string | null;
}

export interface DealQuery {
  view: DealView;
  q?: string;
  stage?: DealStage;
  ownerId?: string;
  createdFrom?: string;
  createdTo?: string;
  closeDateFrom?: string;
  closeDateTo?: string;
  sort?: DealSort;
  dir?: 'asc' | 'desc';
  page?: number;
  pageSize?: number;
}

export type DealPulseStatus = 'won' | 'lost' | 'risk' | 'slow' | 'ok';

export interface DealPulseState {
  status: DealPulseStatus;
  litBars: number;
  label: string;
}

/** Computes prototype-aligned 5-bar Deal Pulse indicator state; open stages come from the API in pipeline order. */
export function computeDealPulse(stage: DealStage, daysInStage: number, openStages: readonly DealStage[], short = false): DealPulseState {
  if (stage === 'CLOSED_WON') {
    return { status: 'won', litBars: 5, label: 'Won' };
  }
  if (stage === 'CLOSED_LOST') {
    return { status: 'lost', litBars: 1, label: 'Lost' };
  }
  const idx = openStages.indexOf(stage);
  const litBars = Math.max(1, idx + 1);
  if (daysInStage > 30) {
    return {
      status: 'risk',
      litBars,
      label: short ? `${daysInStage}d stalled` : `${daysInStage} days in stage, stalled`,
    };
  }
  if (daysInStage > 14) {
    return {
      status: 'slow',
      litBars,
      label: short ? `${daysInStage}d slowing` : `${daysInStage} days in stage, slowing`,
    };
  }
  return {
    status: 'ok',
    litBars,
    label: short ? `${daysInStage}d` : `${daysInStage} days in stage`,
  };
}

export const DEALS_CHANGED_EVENT = 'tcx:deals-changed';
export function notifyDealsChanged() {
  if (typeof window !== 'undefined') {
    window.dispatchEvent(new Event(DEALS_CHANGED_EVENT));
  }
}

function toQueryString(q: DealQuery): string {
  const params = new URLSearchParams();
  Object.entries(q).forEach(([k, v]) => {
    if (v !== undefined && v !== null && v !== '') params.set(k, String(v));
  });
  return params.toString();
}

export const dealsApi = {
  list: (q: DealQuery) => apiRequest<DealPage>(`/deals?${toQueryString(q)}`),
  summary: () => apiRequest<DealSummary>('/deals/summary'),
  get: (id: string) => apiRequest<DealDetail>(`/deals/${encodeURIComponent(id)}`),
  create: (input: DealInput) =>
    apiRequest<Deal>('/deals', {
      method: 'POST',
      body: JSON.stringify(input),
    }),
  update: (id: string, input: Partial<DealInput>) =>
    apiRequest<Deal>(`/deals/${encodeURIComponent(id)}`, {
      method: 'PATCH',
      body: JSON.stringify(input),
    }),
  moveStage: (id: string, input: MoveDealStageInput) =>
    apiRequest<Deal>(`/deals/${encodeURIComponent(id)}/stage`, {
      method: 'PATCH',
      body: JSON.stringify(input),
    }),
  remove: (id: string) =>
    apiRequest<{ id: string }>(`/deals/${encodeURIComponent(id)}`, {
      method: 'DELETE',
    }),
  notes: (id: string) => apiRequest<CrmNote[]>(`/deals/${encodeURIComponent(id)}/notes`),
  addNote: (id: string, body: string) =>
    apiRequest<CrmNote>(`/deals/${encodeURIComponent(id)}/notes`, {
      method: 'POST',
      body: JSON.stringify({ body }),
    }),
};
