import {
  ResponsiveContainer, BarChart, Bar, LineChart, Line, AreaChart, Area,
  PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
} from 'recharts'

export interface ChartData {
  labels?: string[]
  series?: { name: string; data: number[] }[]
  meta?: Record<string, any>
}

const PALETTE = ['#00a0c8', '#3ddc97', '#f59e0b', '#ef4444', '#8b5cf6', '#06b6d4', '#ec4899']

const axisStyle = { fontSize: 11, fill: '#94a3b8' }
const tooltipStyle = {
  background: '#0f172a', border: '1px solid #26304a', borderRadius: 8, fontSize: 12, color: '#e2e8f0',
}

/** {labels, series} → recharts rows [{name, s0, s1, ...}] */
function toRows(d: ChartData) {
  const labels = d.labels || []
  const series = d.series || []
  return labels.map((label, i) => {
    const row: Record<string, any> = { name: label }
    series.forEach(s => { row[s.name] = s.data?.[i] ?? 0 })
    return row
  })
}

export default function Chart({ type = 'BAR', data, height = 240 }:
  { type?: string; data?: ChartData; height?: number }) {
  const d = data || {}
  const series = d.series || []
  const rows = toRows(d)

  if (!rows.length) {
    return <div className="flex items-center justify-center text-slate-500 text-sm" style={{ height }}>데이터 없음</div>
  }

  const t = (type || 'BAR').toUpperCase()

  if (t === 'PIE') {
    const s = series[0]
    const pieRows = (d.labels || []).map((label, i) => ({ name: label, value: s?.data?.[i] ?? 0 }))
    return (
      <ResponsiveContainer width="100%" height={height}>
        <PieChart>
          <Pie data={pieRows} dataKey="value" nameKey="name" outerRadius={height / 2.8} innerRadius={height / 5}>
            {pieRows.map((_, i) => <Cell key={i} fill={PALETTE[i % PALETTE.length]} />)}
          </Pie>
          <Tooltip contentStyle={tooltipStyle} />
          <Legend wrapperStyle={{ fontSize: 11 }} />
        </PieChart>
      </ResponsiveContainer>
    )
  }

  if (t === 'LINE') {
    return (
      <ResponsiveContainer width="100%" height={height}>
        <LineChart data={rows}>
          <CartesianGrid strokeDasharray="3 3" stroke="#26304a" />
          <XAxis dataKey="name" tick={axisStyle} /><YAxis tick={axisStyle} />
          <Tooltip contentStyle={tooltipStyle} /><Legend wrapperStyle={{ fontSize: 11 }} />
          {series.map((s, i) => (
            <Line key={s.name} type="monotone" dataKey={s.name} stroke={PALETTE[i % PALETTE.length]} strokeWidth={2} dot={false} />
          ))}
        </LineChart>
      </ResponsiveContainer>
    )
  }

  if (t === 'AREA') {
    return (
      <ResponsiveContainer width="100%" height={height}>
        <AreaChart data={rows}>
          <CartesianGrid strokeDasharray="3 3" stroke="#26304a" />
          <XAxis dataKey="name" tick={axisStyle} /><YAxis tick={axisStyle} />
          <Tooltip contentStyle={tooltipStyle} /><Legend wrapperStyle={{ fontSize: 11 }} />
          {series.map((s, i) => (
            <Area key={s.name} type="monotone" dataKey={s.name} stroke={PALETTE[i % PALETTE.length]}
              fill={PALETTE[i % PALETTE.length]} fillOpacity={0.18} strokeWidth={2} />
          ))}
        </AreaChart>
      </ResponsiveContainer>
    )
  }

  // default BAR
  return (
    <ResponsiveContainer width="100%" height={height}>
      <BarChart data={rows}>
        <CartesianGrid strokeDasharray="3 3" stroke="#26304a" />
        <XAxis dataKey="name" tick={axisStyle} /><YAxis tick={axisStyle} />
        <Tooltip contentStyle={tooltipStyle} cursor={{ fill: '#26304a55' }} /><Legend wrapperStyle={{ fontSize: 11 }} />
        {series.map((s, i) => (
          <Bar key={s.name} dataKey={s.name} fill={PALETTE[i % PALETTE.length]} radius={[3, 3, 0, 0]} />
        ))}
      </BarChart>
    </ResponsiveContainer>
  )
}
