import type { AutoLeadNotificationList, ConfiguredCampaign, RotationRow, SalesTeamRotationResponse } from './interface';
import { getCities } from '@/app/cities/service';
import axiosInstance from '@/utills/axiosInstance';

export interface ActiveCity {
  id: number;
  name: string;
}

/* Real API — same active-cities endpoint used by MasterCities.tsx elsewhere in the app. */
export async function getActiveCities(): Promise<ActiveCity[]> {
  const res = await getCities({ is_default: true, sortColumn: 'name', sortOrder: 'asc' });
  return (res?.data?.data || []).map((c: { id: string | number; name: string }) => ({
    id: Number(c.id),
    name: c.name,
  }));
}

/* Which backend a rotation belongs to — picks the /facebook-campaigns or /google-campaigns API. */
// eslint-disable-next-line spellcheck/spell-checker
export type RotationSource = 'facebook' | 'google' | 'sms';

const campaignApi = (source: RotationSource): string => `/api/v1/${source}-campaigns`;

/*
  Real backend API — GET /api/v1/{facebook|google}-campaigns (see the
  autoLeadAssignment / autoLeadAssignmentGoogle campaign controllers). Returns
  the raw axios response — callers read the actual body at res.data.
 */
export async function getCampaigns(source: RotationSource, params: { page?: number; pageSize?: number; search?: string }): Promise<any> {
  return axiosInstance.get(campaignApi(source), { params });
}

/*
  Real backend API — POST /api/v1/google-campaigns/refresh. The Google "Refresh" button: re-reads the
  campaigns and their microsites from Google into the saved list (the only call that talks to Google;
  the list above reads what it saved). Rejects with HTTP 429 when Google's quota is used up.
 */
export async function refreshGoogleCampaigns(): Promise<any> {
  return axiosInstance.post('/api/v1/google-campaigns/refresh');
}

export interface ConfiguredCampaignsResult {
  data: ConfiguredCampaign[];
  total: number;
  page: number;
  pageSize: number;
}

/*
  Real backend API — GET /api/v1/facebook-campaigns/configured. One row per
  distinct campaign/city combination that already has a saved rotation in
  auto_lead_round_robin — this is what the Campaigns list page shows.
  Filtering (source/city/search) and pagination are both applied server-side.
 */
export async function getConfiguredCampaigns(params: {
  page?: number;
  pageSize?: number;
  source?: string;
  city_id?: number;
  search?: string;
}): Promise<ConfiguredCampaignsResult> {
  const res = await axiosInstance.get('/api/v1/facebook-campaigns/configured', { params });
  const body = res?.data || {};
  const rows = body.data || [];
  return {
    data: rows.map((r: any) => ({
      campaign_id: r.campaign_id,
      name: r.campaign_name,
      source: r.source,
      city_id: r.city_id,
      city_name: r.city_name,
      is_active: r.is_active === undefined ? true : !!r.is_active,
    })),
    total: body.total ?? rows.length,
    page: body.page ?? params.page ?? 1,
    pageSize: body.pageSize ?? params.pageSize ?? 5,
  };
}

/* Longest DuplicateLeadNotifier waits for one answer before giving up on that call. */
const AUTO_LEAD_NOTIFICATIONS_TIMEOUT_MS = 15000;

/*
  Real backend API — GET /api/v1/auto-lead-assignment/notifications. The newest
  unread Auto Lead Assignment notifications for the logged-in sales person (the
  backend sends at most 20 at a time); polled by DuplicateLeadNotifier.
  `enabled` is false while the pop-ups are switched off on the Feature Control
  page — the list is then always empty. A backend that does not send the flag
  counts as switched on.
 */
export async function getAutoLeadNotifications(): Promise<AutoLeadNotificationList> {
  const res = await axiosInstance.get('/api/v1/auto-lead-assignment/notifications', {
    timeout: AUTO_LEAD_NOTIFICATIONS_TIMEOUT_MS,
  });
  return {
    enabled: res?.data?.enabled !== false,
    data: res?.data?.data || [],
  };
}

/* Real backend API — POST /api/v1/auto-lead-assignment/notifications/{id}/read. */
export async function markAutoLeadNotificationRead(id: number): Promise<{ is_current_owner: boolean }> {
  const res = await axiosInstance.post(`/api/v1/auto-lead-assignment/notifications/${id}/read`);
  // An answer without the flag (an older backend) is treated as "still the owner": the lead opens as before.
  return { is_current_owner: res?.data?.is_current_owner !== false };
}

/*
  Real backend API — GET /api/v1/{facebook|google}-campaigns/{campaignId}. Reads
  from the local cache table, no live Graph/Google Ads call, so it works for the
  edit/view screens even if the campaign is no longer active.
 */
export async function getCampaignById(source: RotationSource, campaignId: string): Promise<any> {
  return axiosInstance.get(`${campaignApi(source)}/${campaignId}`);
}

/* What a rotation is tied to under a campaign: a lead form (Facebook) or a microsite URL (Google). */
export interface FormOption {
  key: string;
  label: string;
}

/*
  Real backend API — GET /api/v1/facebook-campaigns/{campaignId}/forms, or
  /api/v1/google-campaigns/{campaignId}/microsites. Same shape for both sources.
 */
export async function getCampaignForms(source: RotationSource, campaignId: string): Promise<FormOption[]> {
  if (source === 'google') {
    const res = await axiosInstance.get(`${campaignApi(source)}/${campaignId}/microsites`);
    return (res?.data?.data || []).map((m: { microsite_url: string }) => ({ key: m.microsite_url, label: m.microsite_url }));
  }
  const res = await axiosInstance.get(`${campaignApi(source)}/${campaignId}/forms`);
  return (res?.data?.data || []).map((f: { form_id: string; name: string }) => ({ key: f.form_id, label: f.name }));
}

export interface CampaignLaunchMappingRow {
  /** False when the campaign's saved rotation is inactive (the campaign can then be used for a new rotation). */
  rotation_active: boolean;
  form_key: string;
  city_id: number;
  launch_id: number;
  launch_name: string;
  /** The project the rotation is tied to — null for rotations saved before projects were added. */
  project_id: number | null;
  project_name: string | null;
}

/*
  Real backend API — GET /api/v1/{facebook|google}-campaigns/{campaignId}/launch-mapping.
  What the incoming-lead webhook reads to know which launch(es) a campaign+form
  (or microsite) routes a lead to. Used to restore the saved form/launch
  selection on the edit/view screens.
 */
export async function getCampaignLaunchMapping(source: RotationSource, campaignId: string): Promise<CampaignLaunchMappingRow[]> {
  const res = await axiosInstance.get(`${campaignApi(source)}/${campaignId}/launch-mapping`);
  return (res?.data?.data || []).map((r: any) => ({
    rotation_active: r.rotation_active !== false,
    form_key: source === 'google' ? r.microsite_url : r.form_id,
    city_id: r.city_id,
    launch_id: r.launch_id,
    launch_name: r.launch_name,
    project_id: r.project_id ?? null,
    project_name: r.project_name ?? null,
  }));
}

/*
  Real backend API — GET /api/v1/projects (same endpoint the Launches page uses).
  Paginated + searchable;
 */
export async function getProjectOptions(params: { cityId: number; search?: string; page?: number; pageSize?: number }): Promise<Array<{ id: number; name: string }>> {
  const res = await axiosInstance.get('/api/v1/projects', {
    params: { city_id: params.cityId, search: params.search || undefined, page: params.page, pageSize: params.pageSize },
  });
  return (res?.data?.data || []).map((p: { id: number; name: string }) => ({ id: Number(p.id), name: p.name }));
}

/*
  Real backend API — GET /api/v1/projects/by-city. Feeds ProjectByCitySelect,
  the rotation's project dropdown. Deliberately separate from getProjectOptions/
  GET /api/v1/projects This endpoint only matches
  the project's own name within one city.
 */
export async function getProjectOptionsByCity(params: { cityId: number; search?: string; page?: number; pageSize?: number }): Promise<Array<{ id: number; name: string }>> {
  const res = await axiosInstance.get('/api/v1/projects/by-city', {
    params: { city_id: params.cityId, search: params.search || undefined, page: params.page, pageSize: params.pageSize },
  });
  return (res?.data?.data || []).map((p: { id: number; name: string }) => ({ id: Number(p.id), name: p.name }));
}

/*
  Real backend API — GET /api/v1/facebook-campaigns/cities/{cityId}/launches.
  Paginated (10 per page by default) — a city can have hundreds of launches,
  so LaunchMultiSelect loads them incrementally via scroll.
 */
export async function getLaunchesByCity(
  cityId: number,
  params: { page?: number; pageSize?: number; search?: string } = {}
): Promise<any> {
  return axiosInstance.get(`/api/v1/facebook-campaigns/cities/${cityId}/launches`, { params });
}

/*
  Real backend API — GET /api/v1/{facebook|google}-campaigns/launches/{launchId}/roster.
  The active members of the launch's team (launch_sales), already de-duplicated
  and filtered on the backend (users.status = 'active') — this is the roster a
  new rotation gets seeded from before anything's been saved for it. Both
  sources return the same thing; `source` only picks which namespace to call.
 */
export async function getLaunchSalesRoster(launchId: number, source: RotationSource): Promise<RotationRow[]> {
  const res = await axiosInstance.get(`${campaignApi(source)}/launches/${launchId}/roster`);
  const members: Array<{ user_id: number; name: string; role: RotationRow['role'] }> = res?.data?.data || [];

  return members.map((m) => ({ user_id: m.user_id, name: m.name, role: m.role, leads_per_round: 0 }));
}

/*
  Real backend API — PATCH /api/v1/{facebook|google}-campaigns/{campaignId}/rotation-status.
  Switches a campaign's rotation on or off; while off it takes no new leads.
 */
export async function setRotationActive(source: RotationSource, campaignId: string, isActive: boolean): Promise<any> {
  return axiosInstance.patch(`${campaignApi(source)}/${campaignId}/rotation-status`, { is_active: isActive });
}

/*
  Real backend API — GET /api/v1/{facebook|google}-campaigns/launches/{launchId}/sales-team.
  The saved rotation of this launch under ONE campaign + form (or microsite) —
  the same launch can hold a different rotation in every campaign. Reshaped from
  the flat `auto_lead_round_robin` rows into the SalesTeamRotationResponse shape
  RotationList expects. Returns an empty rotation if nothing is saved yet.
 */
export async function getRotationSalesTeam(
  source: RotationSource,
  launchId: number | string,
  campaignId: string,
  formKey: string
): Promise<any> {
  const res = await axiosInstance.get(`${campaignApi(source)}/launches/${launchId}/sales-team`, {
    params: source === 'google' ? { campaign_id: campaignId, microsite_url: formKey } : { campaign_id: campaignId, form_id: formKey },
  });
  const body = res?.data || {};
  const salesTeam: Array<{
    seller_id: number;
    seller_name: string;
    role: string;
    lead_priority: number;
    no_of_lead: number;
    assigned_count: number;
  }> = body.sales_team || [];

  const response: SalesTeamRotationResponse = {
    launch_id: String(launchId),
    sales_team: salesTeam.map((s) => ({
      field_sales_id: s.seller_id,
      field_sales_name: s.seller_name,
      field_sales_leads: s.no_of_lead,
    })),
    rotation: {
      cycle: salesTeam.length ? 1 : 0,
      cycle_status: salesTeam.length ? 'in-progress' : 'not-started',
      target: salesTeam.map((s) => ({ user_id: s.seller_id, role: s.role as any, lead: s.no_of_lead, assigned: s.assigned_count })),
    },
    next_up: body.next_up ? { user_id: body.next_up.seller_id, role: body.next_up.role } : null,
  };

  return { success: true, ...response };
}

/*
  Real backend API — POST /api/v1/{facebook|google}-campaigns/launches/sales-team/bulk.
  Saves the campaign/form (or microsite)→launch mapping AND every listed
  launch's rotation in one request, one transaction. Only this campaign + form's
  rotation is replaced; other campaigns using the same launches are untouched.
 */
export async function saveRotation(
  source: RotationSource,
  data: {
    /** Omit when creating a new SMS campaign — the first save creates it. */
    campaign_id?: string;
    campaign_name?: string;
    form_key: string;
    city_id: number;
    /** True when creating a new rotation. */
    is_new: boolean;
    /** The project every lead from this rotation is saved against. */
    project_id?: number | null;
    launches: Array<{
      launch_id: number;
      sales_team: Array<{ user_id: number; role: string; leads_per_round: number }>;
    }>;
  }
): Promise<any> {
  const { form_key, ...rest } = data;
  const body = source === 'google' ? { ...rest, microsite_url: form_key } : { ...rest, source: 'Facebook', form_id: form_key };
  return axiosInstance.post(`${campaignApi(source)}/launches/sales-team/bulk`, body);
}

// SMS lead source (click-to-WhatsApp flow). Reuses all the functions above ('sms' is a valid RotationSource).

// Updates just the key_frame for an SMS campaign.
export async function saveSMSKeyFrame(campaignId: string | number, keyFrame: string): Promise<any> {
  return axiosInstance.patch(`/api/v1/sms-campaigns/${campaignId}/key-frame`, { key_frame: keyFrame });
}
