import { leads, leadSources, leadStages } from "@/constants/leads";

export const leadCalculateStatistics = () => {
  // Lead stage counts
  const stageCount: Record<string, number> = {};
  leadStages.forEach((stage) => {
    stageCount[stage] = leads.filter((l) => l.leadStage === stage).length;
  });

  // Lead source counts
  const sourceCount: Record<string, number> = {};
  leadSources.forEach((source) => {
    sourceCount[source] = leads.filter((l) => l.source === source).length;
  });

  // Project interest counts
  const projectCount: Record<string, number> = {};
  leads.forEach((lead) => {
    projectCount[lead.project] = (projectCount[lead.project] || 0) + 1;
  });

  // Lead score distribution
  const highScoreLeads = leads.filter((l) => l.leadScore >= 75).length;
  const mediumScoreLeads = leads.filter(
    (l) => l.leadScore >= 50 && l.leadScore < 75
  ).length;
  const lowScoreLeads = leads.filter((l) => l.leadScore < 50).length;

  // New leads this month
  const currentMonth = new Date().getMonth();
  const currentYear = new Date().getFullYear();
  const newLeadsThisMonth = leads.filter(
    (l) =>
      l.createdOn.getMonth() === currentMonth &&
      l.createdOn.getFullYear() === currentYear
  ).length;

  // Conversion rate (assuming Closed Won leads are converted)
  const closedWonLeads = leads.filter(
    (l) => l.leadStage === "Closed Won"
  ).length;
  const conversionRate =
    leads.length > 0 ? (closedWonLeads / leads.length) * 100 : 0;

  return {
    totalLeads: leads.length,
    stageCount,
    sourceCount,
    projectCount,
    highScoreLeads,
    mediumScoreLeads,
    lowScoreLeads,
    newLeadsThisMonth,
    conversionRate,
  };
};

type ResponseDataType = {
  leadTrendData: {
    month: string;
    leads: number;
    change: number;
    changeDirection: string;
  }[];
  conversionTrendData: {
    month: string;
    total: number;
    change: number;
    changeDirection: string;
  }[];
  stageCounts: {
    totalCount: number;
    stages: { stageName: string; count: number, stageColor: string }[];
    topStageName: string;
    topStageCount: number;
  }[];
  leadScores: { label: string; count: number }[];
};

export const transformLeadAnalyticsData = (responseData: ResponseDataType) => {
  const leadTrendData = (responseData?.leadTrendData || [])?.map((item) => ({
    month: item.month,
    leads: item.leads,
    change: item.change,
    changeDirection: item.changeDirection,
  }));
  
  const conversionTrendData = (responseData.conversionTrendData || []).map(
    (item) => ({
      month: item.month,
      rate: item.total,
      change: item.change,
      changeDirection: item.changeDirection,
    })
  );

  const stageCount: Record<
    string,
    { count: number; color: string | undefined }
  > = {};

  (responseData.stageCounts?.[0]?.stages || []).forEach((stage) => {
    stageCount[stage.stageName] = {
      count: stage.count,
      color: stage.stageColor,
    };
  });

  const totalLeadStageCount = responseData.stageCounts?.[0]?.totalCount || 0;
  const topStageName = responseData.stageCounts?.[0]?.topStageName || "";
  const topStageCount = responseData.stageCounts?.[0]?.topStageCount || 0;

  const scoreBuckets = {
    highScoreLeads: 0,
    mediumScoreLeads: 0,
    lowScoreLeads: 0,
  };

  (responseData.leadScores || []).forEach((bucket) => {
    if (bucket.label === "high") scoreBuckets.highScoreLeads = bucket.count;
    else if (bucket.label === "medium")
      scoreBuckets.mediumScoreLeads = bucket.count;
    else if (bucket.label === "low") scoreBuckets.lowScoreLeads = bucket.count;
    else scoreBuckets.lowScoreLeads += bucket.count;
  });

  const stats = {
    totalLeads: responseData.stageCounts?.[0]?.totalCount || 0,
    newLeadsThisMonth: leadTrendData.at(-1)?.leads || 0,
    leadsLastMonthChange: leadTrendData.at(-1)?.change || 0,
    leadsLastMonthChangeDirection: leadTrendData.at(-1)?.changeDirection || "",
    ...scoreBuckets,
    stageCount,
    totalLeadStageCount,
    topStageName,
    topStageCount,
    conversionRate: conversionTrendData.at(-1)?.rate || 0,
    conversionLastMonthChange: conversionTrendData.at(-1)?.change || 0,
    conversionLastMonthChangeDirection:
      conversionTrendData.at(-1)?.changeDirection || "",
  };

  return { stats, leadTrendData, conversionTrendData };
};
