import { axiosInstance } from './client';

// ─── Types ────────────────────────────────────────────────────────────────

export type LeadStatus =
  | 'new'
  | 'accepted'
  | 'responded'
  | 'contacted'
  | 'scheduled'
  | 'won'
  | 'lost'
  | 'expired'
  | 'rejected';

export type LeadPriority = 'high' | 'medium' | 'low';

export type LeadActionType =
  | 'received'
  | 'responded'
  | 'status_change'
  | 'note'
  | 'accepted'
  | 'rejected';

export interface AngiLeadAction {
  id: string;
  lead_id: string;
  company_id: string;
  action_type: LeadActionType;
  details: string;
  message_content?: string;
  performed_by: string;
  created_at: string;
}

export interface AngiLead {
  id: string;
  company_id: string;
  angi_lead_id: string;
  connector_id: string;
  first_name: string;
  last_name: string;
  email: string;
  phone: string;
  project_type: string;
  description: string;
  budget: string;
  budget_value: number;
  timeline: string;
  address: string;
  city: string;
  state: string;
  zip_code: string;
  status: LeadStatus;
  priority: LeadPriority;
  is_premium: boolean;
  is_duplicate: boolean;
  response_time_minutes: number;
  responded_at: string | null;
  last_contacted_at: string | null;
  cost_per_lead: number;
  internal_notes: string;
  received_at: string;
  created_at: string;
  updated_at: string;
  actions?: AngiLeadAction[];
}

export interface LeadsListResponse {
  success: boolean;
  data: {
    items: AngiLead[];
    total: number;
    page: number;
    per_page: number;
  };
}

export interface LeadDetailResponse {
  success: boolean;
  data: AngiLead;
}

export interface LeadUpdatePayload {
  status?: LeadStatus;
  priority?: LeadPriority;
  internal_notes?: string;
}

export interface LeadRespondPayload {
  message: string;
}

export interface LeadAnalytics {
  success: boolean;
  data: {
    total_leads: number;
    new_leads: number;
    responded: number;
    contacted: number;
    scheduled: number;
    won: number;
    lost: number;
    expired: number;
    rejected: number;
    avg_response_time: number;
    conversion_rate: number;
    total_budget: number;
    avg_budget: number;
    premium_leads: number;
    duplicate_leads: number;
    daily_trend?: { date: string; count: number }[];
    by_project_type?: { project_type: string; count: number }[];
    by_status?: { status: string; count: number }[];
  };
}

export interface SyncResponse {
  success: boolean;
  data: { message: string; leads_synced: number };
}

// ─── API ──────────────────────────────────────────────────────────────────

const baseUrl = (companyId: string) => `/api/company/${companyId}/angi/leads`;

export const angiLeadsApi = {
  /**
   * List leads with optional filters
   */
  async getAll(
    companyId: string,
    params?: {
      status?: string;
      date_range?: string;
      project_type?: string;
      search?: string;
      page?: number;
      per_page?: number;
      priority?: string;
    }
  ): Promise<LeadsListResponse> {
    const response = await axiosInstance.get<LeadsListResponse>(baseUrl(companyId), { params });
    return response.data;
  },

  /**
   * Get a single lead with its action history
   */
  async getOne(
    companyId: string,
    leadId: string
  ): Promise<LeadDetailResponse> {
    const response = await axiosInstance.get<LeadDetailResponse>(`${baseUrl(companyId)}/${leadId}`);
    return response.data;
  },

  /**
   * Update lead status / priority / notes
   */
  async update(
    companyId: string,
    leadId: string,
    payload: LeadUpdatePayload
  ): Promise<LeadDetailResponse> {
    const response = await axiosInstance.put<LeadDetailResponse>(
      `${baseUrl(companyId)}/${leadId}`,
      payload
    );
    return response.data;
  },

  /**
   * Respond to a lead (sends message)
   */
  async respond(
    companyId: string,
    leadId: string,
    payload: LeadRespondPayload
  ): Promise<LeadDetailResponse> {
    const response = await axiosInstance.post<LeadDetailResponse>(
      `${baseUrl(companyId)}/${leadId}/respond`,
      payload
    );
    return response.data;
  },

  /**
   * Accept a lead
   */
  async accept(
    companyId: string,
    leadId: string
  ): Promise<LeadDetailResponse> {
    const response = await axiosInstance.post<LeadDetailResponse>(
      `${baseUrl(companyId)}/${leadId}/accept`
    );
    return response.data;
  },

  /**
   * Reject a lead
   */
  async reject(
    companyId: string,
    leadId: string
  ): Promise<LeadDetailResponse> {
    const response = await axiosInstance.post<LeadDetailResponse>(
      `${baseUrl(companyId)}/${leadId}/reject`
    );
    return response.data;
  },

  /**
   * Get lead analytics / summary
   */
  async getAnalytics(companyId: string): Promise<LeadAnalytics> {
    const response = await axiosInstance.get<LeadAnalytics>(`${baseUrl(companyId)}/analytics`);
    return response.data;
  },

  /**
   * Trigger manual lead sync
   */
  async sync(companyId: string): Promise<SyncResponse> {
    const response = await axiosInstance.post<SyncResponse>(`${baseUrl(companyId)}/sync`);
    return response.data;
  },
};