import { getYearToDateRange } from '../utils/dateUtils';

export const TECHNICIAN_WORK_SUMMARY_REPORT = 'Technician Work Order Summary';

export type TechnicianWorkSummaryRow = {
  custom_assign_to_contractor?: string;
  assigned_technician?: string;
  total?: number;
  completed?: number;
  in_progress?: number;
  open?: number;
};

export type TechnicianWorkSummaryFilters = {
  work_order_type?: string;
  from_date?: string;
  to_date?: string;
  company?: string;
  site_name?: string;
};

export type TechnicianWorkSummaryChartData = {
  labels: string[];
  datasets: Array<{ name: string; values: number[]; color: string }>;
  totals: { completed: number; in_progress: number; open: number; total: number };
  rows: TechnicianWorkSummaryRow[];
};

const DATASET_COLORS = {
  completed: '#10B981',
  in_progress: '#3B82F6',
  open: '#F59E0B',
} as const;

export const getDefaultTechnicianSummaryDateRange = () => getYearToDateRange();

export const getTechnicianLabel = (row: TechnicianWorkSummaryRow): string =>
  (row.custom_assign_to_contractor || row.assigned_technician || 'Unknown').trim() || 'Unknown';

export const buildTechnicianWorkSummaryChartData = (
  rows: TechnicianWorkSummaryRow[]
): TechnicianWorkSummaryChartData | null => {
  if (!rows.length) return null;

  const labels = rows.map(getTechnicianLabel);
  const datasets = [
    { name: 'completed', values: rows.map(r => Number(r.completed) || 0), color: DATASET_COLORS.completed },
    { name: 'in_progress', values: rows.map(r => Number(r.in_progress) || 0), color: DATASET_COLORS.in_progress },
    { name: 'open', values: rows.map(r => Number(r.open) || 0), color: DATASET_COLORS.open },
  ].filter(ds => ds.values.some(v => v > 0));

  const totals = rows.reduce(
    (acc, row) => {
      acc.completed += Number(row.completed) || 0;
      acc.in_progress += Number(row.in_progress) || 0;
      acc.open += Number(row.open) || 0;
      acc.total += Number(row.total) || 0;
      return acc;
    },
    { completed: 0, in_progress: 0, open: 0, total: 0 }
  );

  return { labels, datasets, totals, rows };
};

export const runTechnicianWorkSummaryReport = async (
  filters: TechnicianWorkSummaryFilters
): Promise<TechnicianWorkSummaryRow[]> => {
  const csrfToken =
    typeof window !== 'undefined' && (window as any).csrf_token && (window as any).csrf_token !== 'None'
      ? (window as any).csrf_token
      : null;

  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    Accept: 'application/json',
  };
  if (csrfToken) {
    headers['X-Frappe-CSRF-Token'] = csrfToken;
  }

  const cleanedFilters: Record<string, string> = {};
  Object.entries(filters).forEach(([key, value]) => {
    if (value) cleanedFilters[key] = value;
  });

  const response = await fetch('/api/method/frappe.desk.query_report.run', {
    method: 'POST',
    headers,
    credentials: 'include',
    body: JSON.stringify({
      report_name: TECHNICIAN_WORK_SUMMARY_REPORT,
      filters: cleanedFilters,
      ignore_prepared_report: 1,
    }),
  });

  const payload = await response.json();
  if (!response.ok) {
    throw new Error(payload?.message || payload?.exc || 'Failed to load technician work summary');
  }

  const result = payload?.message?.result || payload?.message?.message?.result || [];
  return Array.isArray(result) ? result : [];
};

export const fetchTechnicianWorkSummaryChart = async (
  filters: TechnicianWorkSummaryFilters
): Promise<TechnicianWorkSummaryChartData | null> => {
  const rows = await runTechnicianWorkSummaryReport(filters);
  return buildTechnicianWorkSummaryChartData(rows);
};
