import { DashboardStats } from "@/types"
import { leads } from "./leads"

function getLeadsPerMonth() {
  const months: { month: string; leads: number; closed: number }[] = []
  const now = new Date()

  for (let i = 5; i >= 0; i--) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1)
    const monthStr = d.toLocaleDateString("en-US", { month: "short", year: "2-digit" })
    const yearMonth = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`

    const leadsCount = leads.filter((l) => l.createdAt.startsWith(yearMonth)).length
    const closedCount = leads.filter(
      (l) => l.status === "closed" && l.updatedAt.startsWith(yearMonth)
    ).length

    months.push({ month: monthStr, leads: leadsCount, closed: closedCount })
  }

  return months
}

function getStatusDistribution() {
  const statusCounts: Record<string, number> = { open: 0, contacted: 0, pending: 0, closed: 0, ignored: 0 }
  leads.forEach((l) => {
    statusCounts[l.status]++
  })

  return [
    { name: "Open", value: statusCounts.open, color: "#3b82f6" },
    { name: "Contacted", value: statusCounts.contacted, color: "#f59e0b" },
    { name: "Pending", value: statusCounts.pending, color: "#8b5cf6" },
    { name: "Closed", value: statusCounts.closed, color: "#10b981" },
    { name: "Ignored", value: statusCounts.ignored, color: "#71717a" },
  ]
}

export const dashboardStats: DashboardStats = {
  totalLeads: leads.length,
  openLeads: leads.filter((l) => l.status === "open").length,
  contactedLeads: leads.filter((l) => l.status === "contacted").length,
  pendingLeads: leads.filter((l) => l.status === "pending").length,
  closedLeads: leads.filter((l) => l.status === "closed").length,
  ignoredLeads: leads.filter((l) => l.status === "ignored").length,
  conversionRate: Math.round(
    (leads.filter((l) => l.status === "closed").length / leads.length) * 100
  ),
  leadsPerMonth: getLeadsPerMonth(),
  recentLeads: leads.slice(0, 10),
  statusDistribution: getStatusDistribution(),
}
