import {
  AreaChart, Area, XAxis, YAxis, Tooltip, ResponsiveContainer,
  CartesianGrid,
} from 'recharts'
import type { SalesStatsBucket } from '@/lib/types'

interface Props {
  series: SalesStatsBucket[]
  currencyCode?: string
}

const fmt = new Intl.NumberFormat('ru', { maximumFractionDigits: 0 })
const fmtDay = (s: string) => {
  const d = new Date(s)
  return `${String(d.getDate()).padStart(2, '0')}.${String(d.getMonth() + 1).padStart(2, '0')}`
}

export function SalesChart({ series, currencyCode = 'KZT' }: Props) {
  const data = series.map((b) => ({
    day: fmtDay(b.bucket),
    revenue: b.revenue,
    transactions: b.transactions,
  }))

  return (
    <div className="h-72 w-full">
      <ResponsiveContainer width="100%" height="100%">
        <AreaChart data={data} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
          <defs>
            <linearGradient id="revenue-fill" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor="var(--color-brand)" stopOpacity={0.35} />
              <stop offset="95%" stopColor="var(--color-brand)" stopOpacity={0} />
            </linearGradient>
          </defs>
          <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false} />
          <XAxis
            dataKey="day"
            stroke="#94a3b8"
            fontSize={11}
            interval="preserveStartEnd"
            tickLine={false}
          />
          <YAxis
            stroke="#94a3b8"
            fontSize={11}
            tickFormatter={(v) => fmt.format(v)}
            tickLine={false}
            axisLine={false}
            width={70}
          />
          <Tooltip
            contentStyle={{
              backgroundColor: 'rgba(15, 23, 42, 0.95)',
              border: 'none',
              borderRadius: '8px',
              color: '#f1f5f9',
              fontSize: '12px',
            }}
            labelStyle={{ color: '#94a3b8', marginBottom: 4 }}
            formatter={(value, name) => {
              const num = typeof value === 'number' ? value : Number(value ?? 0)
              if (name === 'revenue') return [`${fmt.format(num)} ${currencyCode}`, 'Выручка']
              return [String(value), String(name)]
            }}
          />
          <Area
            type="monotone"
            dataKey="revenue"
            stroke="var(--color-brand)"
            strokeWidth={2}
            fill="url(#revenue-fill)"
          />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  )
}
