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

export type ContactLifecycle = 'Customer' | 'Prospect' | 'Partner';
export type ContactView = 'all' | 'mine' | 'cust' | 'prosp';
export type ContactSort = 'name' | 'account' | 'title' | 'lifecycle' | 'owner' | 'lastActivityAt' | 'createdAt';

export interface Contact {
  id: string;
  name: string;
  email: string;
  phone: string | null;
  title: string | null;
  lifecycle: ContactLifecycle;
  lastActivityAt: string;
  accountId: string | null;
  account: {
    id: string;
    name: string;
    city: string | null;
    industry: string | null;
  } | null;
  owner: { id: string; name: string } | null;
  createdAt: string;
  updatedAt: string;
}

export interface ContactDetail extends Contact {
  deals: Array<{
    id: string;
    dealNumber?: string;
    title: string;
    stage: string;
    amount: number;
  }>;
}

export type ContactCounts = Record<ContactView, number>;

export interface ContactPage {
  items: Contact[];
  total: number;
  page: number;
  pageSize: number;
  counts: ContactCounts;
  accountsCount: number;
}

export interface ContactDuplicate {
  id: string;
  name: string;
  email: string;
  account: { id: string; name: string } | null;
}

export interface ContactInput {
  name: string;
  accountId: string;
  email?: string | null;
  title?: string | null;
  phone?: string | null;
  lifecycle?: ContactLifecycle;
  ownerId?: string | null;
}

export interface ContactQuery {
  view: ContactView;
  q?: string;
  lifecycle?: ContactLifecycle;
  accountId?: string;
  ownerId?: string;
  createdFrom?: string;
  createdTo?: string;
  sort?: ContactSort;
  dir?: 'asc' | 'desc';
  page?: number;
  pageSize?: number;
}

export const LIFECYCLE_TONE: Record<ContactLifecycle, BadgeTone> = {
  Customer: 'green',
  Prospect: 'blue',
  Partner: 'indigo',
};

export const CONTACT_VIEWS: Array<{ key: ContactView; label: string }> = [
  { key: 'all', label: 'All contacts' },
  { key: 'mine', label: 'My contacts' },
  { key: 'cust', label: 'Customers' },
  { key: 'prosp', label: 'Prospects' },
];

function toQueryString(q: ContactQuery): string {
  const p = new URLSearchParams();
  p.set('view', q.view);
  if (q.q) p.set('q', q.q);
  if (q.lifecycle) p.set('lifecycle', q.lifecycle);
  if (q.accountId) p.set('accountId', q.accountId);
  if (q.ownerId) p.set('ownerId', q.ownerId);
  if (q.createdFrom) p.set('createdFrom', q.createdFrom);
  if (q.createdTo) p.set('createdTo', q.createdTo);
  if (q.sort) p.set('sort', q.sort);
  if (q.dir) p.set('dir', q.dir);
  if (q.page) p.set('page', String(q.page));
  if (q.pageSize) p.set('pageSize', String(q.pageSize));
  return p.toString();
}

export const CONTACTS_CHANGED_EVENT = 'tcx:contacts-changed';
export function notifyContactsChanged() {
  if (typeof window !== 'undefined') {
    window.dispatchEvent(new Event(CONTACTS_CHANGED_EVENT));
  }
}

export const contactsApi = {
  list: (q: ContactQuery) => apiRequest<ContactPage>(`/contacts?${toQueryString(q)}`),
  summary: () => apiRequest<ContactCounts>('/contacts/summary'),
  checkDuplicate: (params: { email?: string; excludeId?: string }) => {
    const p = new URLSearchParams();
    if (params.email) p.set('email', params.email);
    if (params.excludeId) p.set('excludeId', params.excludeId);
    return apiRequest<ContactDuplicate[]>(`/contacts/check-duplicate?${p.toString()}`);
  },
  get: (id: string) => apiRequest<ContactDetail>(`/contacts/${encodeURIComponent(id)}`),
  create: (body: ContactInput) =>
    apiRequest<Contact>('/contacts', {
      method: 'POST',
      body: JSON.stringify(body),
    }),
  update: (id: string, body: Partial<ContactInput>) =>
    apiRequest<ContactDetail>(`/contacts/${encodeURIComponent(id)}`, {
      method: 'PATCH',
      body: JSON.stringify(body),
    }),
  remove: (id: string) =>
    apiRequest<{ id: string }>(`/contacts/${encodeURIComponent(id)}`, {
      method: 'DELETE',
    }),
  notes: (id: string) => apiRequest<CrmNote[]>(`/contacts/${encodeURIComponent(id)}/notes`),
  addNote: (id: string, body: string) =>
    apiRequest<CrmNote>(`/contacts/${encodeURIComponent(id)}/notes`, {
      method: 'POST',
      body: JSON.stringify({ body }),
    }),
};
