import { apiRequest, getApiBaseUrl } from './api';

export type DashboardPeriod = 'today' | 'yesterday' | 'week' | 'month' | 'quarter' | 'year' | 'all' | 'custom';

export interface DashboardFilterParams {
  period?: DashboardPeriod;
  startDate?: string;
  endDate?: string;
}

export interface ReportsFilterParams {
  period?: DashboardPeriod;
  startDate?: string;
  endDate?: string;
}

export interface ReportsSummary {
  wonRevenue: number;
  openPipeline: number;
  winRate: number;
  totalLeads: number;
  qualifiedLeads: number;
  wonDealsCount: number;
  lostDealsCount: number;
}

export interface DashboardKpis {
  revenueWon: number;
  openPipeline: number;
  weightedPipeline: number;
  winRate: number;
  wonCount: number;
  lostCount: number;
  newLeadsCount: number;
  qualifiedLeadsCount: number;
}

export interface PipelineStageMetric {
  stage: string;
  count: number;
  value: number;
}

export interface LeadSourceMetric {
  source: string;
  count: number;
}

export interface AttentionDeal {
  id: string;
  title: string;
  dealNumber: string;
  stage: string;
  amount: number;
  daysInStage: number;
  stageChangedAt: string;
  closeDate: string | null;
  account: { id: string; name: string } | null;
}

export interface TodayTaskItem {
  id: string;
  title: string;
  priority: string;
  dueDate: string;
  completed: boolean;
  deal: { id: string; title: string } | null;
  account: { id: string; name: string } | null;
  contact?: { id: string; name: string } | null;
  lead?: { id: string; name: string } | null;
  project?: { id: string; name: string } | null;
}

export interface DeliverySummary {
  activeProjectsCount: number;
  atRiskProjectsCount: number;
  teamHoursThisWeek: number;
  billableHoursThisWeek: number;
}

export interface RecentActivityItem {
  id: string;
  type: string;
  title: string;
  performedAt: string;
  owner: { id: string; name: string } | null;
  lead: { id: string; name: string } | null;
  contact: { id: string; name: string } | null;
  account: { id: string; name: string } | null;
  deal: { id: string; title: string } | null;
}

export interface RevenueAgainstTargetItem {
  month: string;
  fullMonth: string;
  revenue: number;
  target: number;
}

export interface SalesLeaderboardItem {
  userId: string;
  name: string;
  dealsCount: number;
  wonRevenue: number;
}

export interface DashboardAccess {
  deals: boolean;
  leads: boolean;
  tasks: boolean;
  projects: boolean;
  activities: boolean;
}

export interface DashboardResponse {
  period: DashboardPeriod;
  access?: DashboardAccess;
  kpis: DashboardKpis;
  kpi?: DashboardKpis;
  pipelineStages: PipelineStageMetric[];
  stageBreakdown?: PipelineStageMetric[];
  leadSources: LeadSourceMetric[];
  todayTasks: TodayTaskItem[];
  attentionDeals: AttentionDeal[];
  revenueAgainstTarget?: RevenueAgainstTargetItem[];
  leaderboard?: SalesLeaderboardItem[];
  delivery: DeliverySummary;
  recentActivities: RecentActivityItem[];
}

export interface FunnelStep {
  step: string;
  count: number;
}

export interface RepRevenueMetric {
  repId: string;
  name: string;
  wonRevenue: number;
  openPipeline: number;
}

export interface WinLossAnalytics {
  wonCount: number;
  lostCount: number;
  wonAmount: number;
  lostAmount: number;
  winRate: number;
  lossReasons: Array<{ reason: string; count: number }>;
}

export interface LeadSourceQualityMetric {
  source: string;
  total: number;
  qualified: number;
  converted: number;
  conversionRate: number;
}

export interface MonthlyBookingItem {
  month: string;
  year: number;
  bookings: number;
}

export interface ForecastItem {
  month: string;
  dealsCount: number;
  commit: number;
  bestCase: number;
  pipeline: number;
  weighted: number;
}

export interface ReportsResponse {
  period: DashboardPeriod;
  periodLabel?: string;
  dateRange?: {
    start: string;
    end: string;
  };
  summary?: ReportsSummary;
  funnel: FunnelStep[];
  revenueByRep: RepRevenueMetric[];
  monthlyBookings?: MonthlyBookingItem[];
  forecast?: ForecastItem[];
  winLoss: WinLossAnalytics;
  leadSourceQuality: LeadSourceQualityMetric[];
}

export const dashboardApi = {
  getDashboard: (filter: DashboardPeriod | DashboardFilterParams = 'today') => {
    let query = '';
    if (typeof filter === 'string') {
      query = `period=${encodeURIComponent(filter)}`;
    } else {
      const p = new URLSearchParams();
      if (filter.period) p.set('period', filter.period);
      if (filter.startDate) p.set('startDate', filter.startDate);
      if (filter.endDate) p.set('endDate', filter.endDate);
      query = p.toString();
    }
    return apiRequest<DashboardResponse>(`/dashboard?${query}`);
  },
  getReports: (filter: DashboardPeriod | ReportsFilterParams = 'month') => {
    let query = '';
    if (typeof filter === 'string') {
      query = `period=${encodeURIComponent(filter)}`;
    } else {
      const p = new URLSearchParams();
      if (filter.period) p.set('period', filter.period);
      if (filter.startDate) p.set('startDate', filter.startDate);
      if (filter.endDate) p.set('endDate', filter.endDate);
      query = p.toString();
    }
    return apiRequest<ReportsResponse>(`/reports?${query}`);
  },

  // Exports standard sales reports as a real downloadable .pdf file
  downloadReportsPdf: async (filter: DashboardPeriod | ReportsFilterParams = 'quarter'): Promise<void> => {
    let query = '';
    let label = 'quarter';
    if (typeof filter === 'string') {
      query = `period=${encodeURIComponent(filter)}`;
      label = filter;
    } else {
      const p = new URLSearchParams();
      if (filter.period) p.set('period', filter.period);
      if (filter.startDate) p.set('startDate', filter.startDate);
      if (filter.endDate) p.set('endDate', filter.endDate);
      query = p.toString();
      label = filter.period || 'custom';
    }
    const token = typeof window !== 'undefined' ? localStorage.getItem('tcx_access_token') : null;
    const baseUrl = getApiBaseUrl();
    const res = await fetch(`${baseUrl}/reports/pdf?${query}`, {
      headers: token ? { Authorization: `Bearer ${token}` } : {},
      credentials: 'include',
    });
    if (!res.ok) {
      const err = await res.json().catch(() => ({ message: 'Failed to download reports PDF' }));
      throw new Error(err.message || `PDF export failed with status ${res.status}`);
    }
    const blob = await res.blob();
    const disposition = res.headers.get('content-disposition') || '';
    const match = disposition.match(/filename="?([^";]+)"?/);
    const filename = match ? match[1] : `sales-report-${label}-${new Date().toISOString().slice(0, 10)}.pdf`;

    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(url);
  },

  // Exports custom builder report as a real downloadable .pdf file
  downloadCustomReportPdf: async (payload: { name: string; object: string; group: string; measure: string; chart?: string; rows: [string, number][] }): Promise<void> => {
    const token = typeof window !== 'undefined' ? localStorage.getItem('tcx_access_token') : null;
    const baseUrl = getApiBaseUrl();
    const res = await fetch(`${baseUrl}/reports/custom/pdf`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(token ? { Authorization: `Bearer ${token}` } : {}),
      },
      credentials: 'include',
      body: JSON.stringify(payload),
    });
    if (!res.ok) {
      const err = await res.json().catch(() => ({ message: 'Failed to download custom report PDF' }));
      throw new Error(err.message || `PDF export failed with status ${res.status}`);
    }
    const blob = await res.blob();
    const disposition = res.headers.get('content-disposition') || '';
    const match = disposition.match(/filename="?([^";]+)"?/);
    const slug = payload.name.toLowerCase().replace(/[^a-z0-9]+/g, '-');
    const filename = match ? match[1] : `custom-report-${slug}-${new Date().toISOString().slice(0, 10)}.pdf`;

    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(url);
  },

  // Saved Custom Reports in database
  getCustomReports: async (): Promise<Array<{ id: string; name: string; object: 'Deals' | 'Leads'; group: string; measure: string; chart: 'Bar' | 'Donut' | 'Table'; createdAt?: string }>> => {
    return apiRequest('/reports/custom');
  },

  createCustomReport: async (payload: { name: string; object: string; group: string; measure: string; chart: string }): Promise<{ id: string; name: string; object: 'Deals' | 'Leads'; group: string; measure: string; chart: 'Bar' | 'Donut' | 'Table'; createdAt?: string }> => {
    return apiRequest('/reports/custom', {
      method: 'POST',
      body: JSON.stringify(payload),
    });
  },

  updateCustomReport: async (id: string, payload: Partial<{ name: string; object: string; group: string; measure: string; chart: string }>): Promise<{ id: string; name: string; object: 'Deals' | 'Leads'; group: string; measure: string; chart: 'Bar' | 'Donut' | 'Table'; createdAt?: string }> => {
    return apiRequest(`/reports/custom/${id}`, {
      method: 'PATCH',
      body: JSON.stringify(payload),
    });
  },

  deleteCustomReport: async (id: string): Promise<{ success: boolean; message: string }> => {
    return apiRequest(`/reports/custom/${id}`, {
      method: 'DELETE',
    });
  },
};
