"use client"

import { useState, useMemo } from "react"
import { motion } from "framer-motion"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"

interface IntervalData {
  label: string
  leads: number
  closed: number
}

interface LeadsPerMonthChartProps {
  data: IntervalData[]
}

const BAR_GRADIENT_TOP = "#3B6AB8"
const NEW_LEADS = "#1e3c72"
const CLOSED = "#457fca"

export function LeadsPerMonthChart({ data }: LeadsPerMonthChartProps) {
  const [hovered, setHovered] = useState<number | null>(null)

  const width = 880
  const height = 620
  const padding = { top: 128, right: 24, bottom: 48, left: 44 }
  const chartW = width - padding.left - padding.right
  const chartH = height - padding.top - padding.bottom

  const maxVal = useMemo(() => {
    const max = Math.max(...data.map((d) => Math.max(d.leads, d.closed)))
    return Math.ceil(max / 7) * 7
  }, [data])

  const ticks = useMemo(() => {
    const steps = 4
    return Array.from({ length: steps + 1 }, (_, i) => Math.round((maxVal / steps) * i))
  }, [maxVal])

  const groupW = chartW / data.length
  const barW = groupW * 0.28
  const gap = groupW * 0.06

  const yScale = (v: number) => chartH - (v / maxVal) * chartH

  const active = hovered
  const activeDatum = active !== null ? data[active] : null

  const totalNew = data.reduce((s, d) => s + d.leads, 0)
  const totalClosed = data.reduce((s, d) => s + d.closed, 0)
  const closeRate = totalNew > 0 ? Math.round((totalClosed / totalNew) * 100) : 0

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3, delay: 0.3 }}
      className="h-full"
    >
      <Card className="h-full">
        <CardHeader>
          <div className="flex items-start justify-between">
            <div>
              <CardTitle>Leads Per Month</CardTitle>
              <p className="mt-1 text-sm text-muted-foreground">
                {totalNew} new &middot; {totalClosed} closed &middot; {closeRate}% close rate
              </p>
            </div>
            <div className="flex items-center gap-4">
              <div className="flex items-center gap-1.5">
                <span className="inline-block h-2.5 w-2.5 rounded-sm" style={{ background: NEW_LEADS }} />
                <span className="text-xs text-muted-foreground">New Leads</span>
              </div>
              <div className="flex items-center gap-1.5">
                <span className="inline-block h-2.5 w-2.5 rounded-sm" style={{ background: CLOSED }} />
                <span className="text-xs text-muted-foreground">Closed</span>
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent className="flex flex-1 flex-col">
          <div className="relative flex-1">
            <svg
              viewBox={`0 0 ${width} ${height}`}
              width="100%"
              height="100%"
              className="block overflow-visible"
            >
              <defs>
                <linearGradient id="newLeadsGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor={BAR_GRADIENT_TOP} />
                  <stop offset="100%" stopColor={NEW_LEADS} />
                </linearGradient>
                <linearGradient id="closedGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#5691c8" />
                  <stop offset="100%" stopColor={CLOSED} />
                </linearGradient>
                <filter id="shadowBlue">
                  <feDropShadow dx="0" dy="2" stdDeviation="4" floodColor={NEW_LEADS} floodOpacity="0.4" />
                </filter>
                <filter id="shadowClosed">
                  <feDropShadow dx="0" dy="2" stdDeviation="4" floodColor={CLOSED} floodOpacity="0.4" />
                </filter>
              </defs>

              <g transform={`translate(${padding.left}, ${padding.top})`}>
                {/* Grid lines */}
                {ticks.map((t, i) => (
                  <g key={i}>
                    <line
                      x1={0}
                      x2={chartW}
                      y1={yScale(t)}
                      y2={yScale(t)}
                      stroke="hsl(var(--border))"
                      strokeDasharray={t === 0 ? "0" : "3 5"}
                      strokeWidth={1}
                    />
                    <text
                      x={-12}
                      y={yScale(t)}
                      fill="hsl(var(--muted-foreground))"
                      fontSize={12}
                      textAnchor="end"
                      dominantBaseline="middle"
                    >
                      {t}
                    </text>
                  </g>
                ))}

                {/* Bars */}
                {data.map((d, i) => {
                  const groupX = i * groupW
                  const isActive = active === i
                  const newH = chartH - yScale(d.leads)
                  const closedH = chartH - yScale(d.closed)

                  return (
                    <g
                      key={d.label}
                      onMouseEnter={() => setHovered(i)}
                      onMouseLeave={() => setHovered(null)}
                      style={{ cursor: "pointer" }}
                    >
                      {/* Hover highlight band */}
                      <rect
                        x={groupX}
                        y={0}
                        width={groupW}
                        height={chartH}
                        fill={isActive ? "hsl(var(--muted) / 0.5)" : "transparent"}
                        rx={6}
                      />

                      {/* New Leads bar */}
                      <rect
                        x={groupX + groupW / 2 - barW - gap / 2}
                        y={yScale(d.leads)}
                        width={barW}
                        height={newH}
                        rx={4}
                        fill="url(#newLeadsGrad)"
                        filter={isActive ? "url(#shadowBlue)" : undefined}
                        opacity={hovered !== null && !isActive ? 0.35 : 1}
                        style={{ transition: "opacity 0.15s ease" }}
                      />

                      {/* Closed bar */}
                      <rect
                        x={groupX + groupW / 2 + gap / 2}
                        y={yScale(d.closed)}
                        width={barW}
                        height={closedH}
                        rx={4}
                        fill="url(#closedGrad)"
                        filter={isActive ? "url(#shadowClosed)" : undefined}
                        opacity={hovered !== null && !isActive ? 0.35 : 1}
                        style={{ transition: "opacity 0.15s ease" }}
                      />

                      {/* Month label */}
                      <text
                        x={groupX + groupW / 2}
                        y={chartH + 26}
                        fill={isActive ? "hsl(var(--foreground))" : "hsl(var(--muted-foreground))"}
                        fontSize={12.5}
                        fontWeight={isActive ? 600 : 400}
                        textAnchor="middle"
                      >
                        {d.label}
                      </text>
                    </g>
                  )
                })}
              </g>
            </svg>

            {/* Tooltip */}
            {activeDatum && (
              <div
                className="pointer-events-none absolute top-0"
                style={{
                  left: `${((active! + 0.5) / data.length) * 100}%`,
                  transform: active! > data.length - 2
                    ? "translate(-100%, 0)"
                    : "translate(-12%, 0)",
                  transition: "left 0.15s ease",
                }}
              >
                <div
                  className="min-w-[150px] rounded-xl border p-3 shadow-xl"
                  style={{
                    background: "hsl(var(--popover))",
                    borderColor: "hsl(var(--border))",
                  }}
                >
                  <div className="mb-1.5 text-xs font-semibold" style={{ color: "hsl(var(--foreground))" }}>
                    {activeDatum.label}
                  </div>
                  <div className="mb-1 flex items-center justify-between gap-4 text-xs" style={{ color: "hsl(var(--muted-foreground))" }}>
                    <span className="flex items-center gap-1.5">
                      <span className="inline-block h-2 w-2 rounded-sm" style={{ background: NEW_LEADS }} />
                      New Leads
                    </span>
                    <span className="font-semibold" style={{ color: "hsl(var(--foreground))" }}>{activeDatum.leads}</span>
                  </div>
                  <div className="mb-1 flex items-center justify-between gap-4 text-xs" style={{ color: "hsl(var(--muted-foreground))" }}>
                    <span className="flex items-center gap-1.5">
                      <span className="inline-block h-2 w-2 rounded-sm" style={{ background: CLOSED }} />
                      Closed
                    </span>
                    <span className="font-semibold" style={{ color: "hsl(var(--foreground))" }}>{activeDatum.closed}</span>
                  </div>
                  <div
                    className="mt-1.5 border-t pt-1.5 text-[11px]"
                    style={{ borderColor: "hsl(var(--border))", color: "hsl(var(--muted-foreground))" }}
                  >
                    {activeDatum.leads > 0
                      ? `${Math.round((activeDatum.closed / activeDatum.leads) * 100)}% close rate`
                      : "No leads"}
                  </div>
                </div>
              </div>
            )}
          </div>
        </CardContent>
      </Card>
    </motion.div>
  )
}