import { apiRequest } from './api';

export type CalendarEventType = 'Meeting' | 'Demo' | 'Call' | 'Follow-up' | 'Internal';

export interface CalendarEventRecord {
  id: string;
  title: string;
  type: CalendarEventType;
  date: string;
  startTime: string;
  durationMinutes: number;
  withWhom: string | null;
  description: string | null;
  ownerId: string | null;
  leadId: string | null;
  contactId: string | null;
  accountId: string | null;
  dealId: string | null;
  createdAt: string;
  updatedAt: string;
  owner?: { id: string; name: string; email: string } | null;
  lead?: { id: string; name: string; company: string } | null;
  contact?: { id: string; name: string; email: string } | null;
  account?: { id: string; name: string } | null;
  deal?: { id: string; title: string; dealNumber: string } | null;
}

export interface CalendarListResponse {
  data: CalendarEventRecord[];
  upcoming: CalendarEventRecord[];
  month: number;
  year: number;
}

export interface CreateCalendarEventInput {
  title: string;
  type?: CalendarEventType;
  date: string;
  startTime: string;
  durationMinutes?: number;
  withWhom?: string;
  description?: string;
  ownerId?: string;
  leadId?: string;
  contactId?: string;
  accountId?: string;
  dealId?: string;
}

export type UpdateCalendarEventInput = Partial<Omit<CreateCalendarEventInput, 'leadId' | 'contactId' | 'accountId' | 'dealId'>> & {
  leadId?: string | null;
  contactId?: string | null;
  accountId?: string | null;
  dealId?: string | null;
};

export const CALENDAR_CHANGED_EVENT = 'tcx:calendar-changed';
export function notifyCalendarChanged() {
  if (typeof window !== 'undefined') {
    window.dispatchEvent(new CustomEvent(CALENDAR_CHANGED_EVENT));
  }
}

export const calendarApi = {
  async list(params?: { year?: number; month?: number; from?: string; to?: string; type?: string; ownerId?: string }): Promise<CalendarListResponse> {
    const sp = new URLSearchParams();
    if (params?.year !== undefined) sp.set('year', String(params.year));
    if (params?.month !== undefined) sp.set('month', String(params.month));
    if (params?.from) sp.set('from', params.from);
    if (params?.to) sp.set('to', params.to);
    if (params?.type) sp.set('type', params.type);
    if (params?.ownerId) sp.set('ownerId', params.ownerId);

    const qs = sp.toString();
    return apiRequest<CalendarListResponse>(`/calendar${qs ? `?${qs}` : ''}`);
  },

  async get(id: string): Promise<CalendarEventRecord> {
    return apiRequest<CalendarEventRecord>(`/calendar/${id}`);
  },

  async create(input: CreateCalendarEventInput): Promise<CalendarEventRecord> {
    const res = await apiRequest<CalendarEventRecord>('/calendar', {
      method: 'POST',
      body: JSON.stringify(input),
    });
    notifyCalendarChanged();
    return res;
  },

  async update(id: string, input: UpdateCalendarEventInput): Promise<CalendarEventRecord> {
    const res = await apiRequest<CalendarEventRecord>(`/calendar/${id}`, {
      method: 'PATCH',
      body: JSON.stringify(input),
    });
    notifyCalendarChanged();
    return res;
  },

  async delete(id: string): Promise<{ success: boolean }> {
    const res = await apiRequest<{ success: boolean }>(`/calendar/${id}`, {
      method: 'DELETE',
    });
    notifyCalendarChanged();
    return res;
  },
};
