import { apiRequest } from './api';
import type { CrmNote } from './leads';

export type CustomerView = 'all' | 'mine';
export type CustomerSort = 'name' | 'customerNumber' | 'industry' | 'city' | 'owner' | 'createdAt' | 'phone';

export interface Customer {
  id: string;
  customerNumber: string | null;
  name: string;
  contactPerson: string | null;
  email: string | null;
  contactTitle: string | null;
  industry: string | null;
  city: string | null;
  website: string | null;
  phone: string | null;
  techStack: string | null;
  owner: { id: string; name: string } | null;
  contactsCount: number;
  openPipeline: number;
  openDealsCount: number;
  wonToDate: number;
  createdAt: string;
  updatedAt: string;
}

export interface CustomerContactSummary {
  id: string;
  name: string;
  title: string | null;
  email: string;
  phone: string | null;
  lifecycle: string;
}

export interface CustomerDealSummary {
  id: string;
  dealNumber?: string;
  title: string;
  stage: string;
  amount: number;
}

export interface CustomerProjectSummary {
  id: string;
  projectNumber: string;
  name: string;
  status: string;
  startDate: string | null;
  targetEndDate: string | null;
  budgetAmount: number;
  owner?: { id: string; name: string } | null;
}

export interface CustomerDetail extends Customer {
  contacts: CustomerContactSummary[];
  deals: CustomerDealSummary[];
  projects?: CustomerProjectSummary[];
}

export type CustomerCounts = Record<CustomerView, number>;

export interface CustomerPage {
  items: Customer[];
  total: number;
  page: number;
  pageSize: number;
  counts: CustomerCounts;
  cities: string[];
}

export interface CustomerOption {
  id: string;
  name: string;
  city: string | null;
  customerNumber: string | null;
}

/** What deleting a customer would remove, and what blocks it. */
export interface CustomerDeleteCheck {
  canDelete: boolean;
  blockers: { deals: number; projects: number; quotes: number; invoices: number };
  willDelete: { contacts: number; notes: number; tasks: number; files: number };
  reason: string | null;
}

export interface CustomerDuplicate {
  id: string;
  name: string;
  city: string | null;
  website: string | null;
  customerNumber: string | null;
}

export interface CustomerInput {
  name: string;
  contactPerson?: string | null;
  email?: string | null;
  contactTitle?: string | null;
  phone?: string | null;
  city?: string | null;
  industry?: string | null;
  website?: string | null;
  techStack?: string | null;
  ownerId?: string | null;
}

export interface CustomerQuery {
  view: CustomerView;
  q?: string;
  industry?: string;
  city?: string;
  ownerId?: string;
  createdFrom?: string;
  createdTo?: string;
  sort?: CustomerSort;
  dir?: 'asc' | 'desc';
  page?: number;
  pageSize?: number;
}

function toQueryString(q: CustomerQuery): string {
  const p = new URLSearchParams();
  p.set('view', q.view);
  if (q.q) p.set('q', q.q);
  if (q.industry) p.set('industry', q.industry);
  if (q.city) p.set('city', q.city);
  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 CUSTOMERS_CHANGED_EVENT = 'tcx:customers-changed';
export function notifyCustomersChanged() {
  if (typeof window !== 'undefined') {
    window.dispatchEvent(new Event(CUSTOMERS_CHANGED_EVENT));
    window.dispatchEvent(new Event('tcx:accounts-changed'));
  }
}

export const customersApi = {
  list: (q: CustomerQuery) => apiRequest<CustomerPage>(`/customers?${toQueryString(q)}`),
  summary: () => apiRequest<CustomerCounts>('/customers/summary'),
  options: () => apiRequest<CustomerOption[]>('/customers/options'),
  checkDuplicate: (params: { name?: string; website?: string; excludeId?: string }) => {
    const p = new URLSearchParams();
    if (params.name) p.set('name', params.name);
    if (params.website) p.set('website', params.website);
    if (params.excludeId) p.set('excludeId', params.excludeId);
    return apiRequest<CustomerDuplicate[]>(`/customers/check-duplicate?${p.toString()}`);
  },
  get: (id: string) => apiRequest<CustomerDetail>(`/customers/${encodeURIComponent(id)}`),
  create: (body: CustomerInput) =>
    apiRequest<Customer>('/customers', {
      method: 'POST',
      body: JSON.stringify(body),
    }),
  update: (id: string, body: Partial<CustomerInput>) =>
    apiRequest<CustomerDetail>(`/customers/${encodeURIComponent(id)}`, {
      method: 'PATCH',
      body: JSON.stringify(body),
    }),
  deleteCheck: (id: string) => apiRequest<CustomerDeleteCheck>(`/customers/${encodeURIComponent(id)}/delete-check`),
  remove: (id: string) =>
    apiRequest<{ id: string }>(`/customers/${encodeURIComponent(id)}`, {
      method: 'DELETE',
    }),
  notes: (id: string) => apiRequest<CrmNote[]>(`/customers/${encodeURIComponent(id)}/notes`),
  addNote: (id: string, body: string) =>
    apiRequest<CrmNote>(`/customers/${encodeURIComponent(id)}/notes`, {
      method: 'POST',
      body: JSON.stringify({ body }),
    }),
};

// Aliases for legacy compatibility
export type Account = Customer;
export type AccountDetail = CustomerDetail;
export type AccountContactSummary = CustomerContactSummary;
export type AccountDealSummary = CustomerDealSummary;
export type AccountView = CustomerView;
export type AccountSort = CustomerSort;
export type AccountPage = CustomerPage;
export type AccountCounts = CustomerCounts;
export type AccountOption = CustomerOption;
export type AccountDeleteCheck = CustomerDeleteCheck;
export type AccountDuplicate = CustomerDuplicate;
export type AccountInput = CustomerInput;
export type AccountQuery = CustomerQuery;
export const ACCOUNTS_CHANGED_EVENT = CUSTOMERS_CHANGED_EVENT;
export const notifyAccountsChanged = notifyCustomersChanged;
export const accountsApi = customersApi;
