import { Lead } from "@/types"

export function getPeriodDateRange(period: string): { start: Date; end: Date } {
  const end = new Date()
  const start = new Date()

  switch (period) {
    case "7days":
      start.setDate(start.getDate() - 7)
      break
    case "30days":
      start.setDate(start.getDate() - 30)
      break
    case "6months":
      start.setMonth(start.getMonth() - 6)
      break
    case "12months":
      start.setMonth(start.getMonth() - 12)
      break
    default:
      start.setMonth(start.getMonth() - 6)
  }

  return { start, end }
}

export function filterLeadsByPeriod(leads: Lead[], period: string): Lead[] {
  const { start, end } = getPeriodDateRange(period)
  return leads.filter((l) => {
    const d = new Date(l.createdAt)
    return d >= start && d <= end
  })
}

export function groupLeadsByInterval(
  leads: Lead[],
  period: string
): { label: string; leads: number; closed: number }[] {
  const { start, end } = getPeriodDateRange(period)

  if (period === "7days" || period === "30days") {
    return groupByDay(leads, start, end)
  }
  return groupByMonth(leads, start, end)
}

function groupByDay(
  leads: Lead[],
  start: Date,
  end: Date
): { label: string; leads: number; closed: number }[] {
  const result: { label: string; leads: number; closed: number }[] = []
  const current = new Date(start)

  while (current <= end) {
    const dateStr = current.toISOString().slice(0, 10)
    const dayLeads = leads.filter((l) => l.createdAt.startsWith(dateStr))
    const closedCount = dayLeads.filter((l) => l.status === "closed").length

    result.push({
      label: current.toLocaleDateString("en-US", { month: "short", day: "numeric" }),
      leads: dayLeads.length,
      closed: closedCount,
    })

    current.setDate(current.getDate() + 1)
  }

  return result
}

function groupByMonth(
  leads: Lead[],
  start: Date,
  end: Date
): { label: string; leads: number; closed: number }[] {
  const result: { label: string; leads: number; closed: number }[] = []
  const current = new Date(start.getFullYear(), start.getMonth(), 1)

  while (current <= end) {
    const yearMonth = `${current.getFullYear()}-${String(current.getMonth() + 1).padStart(2, "0")}`
    const monthLeads = leads.filter((l) => l.createdAt.startsWith(yearMonth))
    const closedCount = monthLeads.filter((l) => l.status === "closed").length

    result.push({
      label: current.toLocaleDateString("en-US", { month: "short", year: "2-digit" }),
      leads: monthLeads.length,
      closed: closedCount,
    })

    current.setMonth(current.getMonth() + 1)
  }

  return result
}
