'use client';

import React from 'react';
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer
} from 'recharts';
import { ChartConfig } from '../types';

interface AreaChartComponentProps {
  data: any[];
  config: ChartConfig;
  width?: number;
  height?: number;
}

/**
 * 영역 차트 컴포넌트
 * - Recharts AreaChart 사용
 * - 추세 파악에 적합
 * - 다중 시리즈 지원
 */
export function AreaChartComponent({ data, config, width = 250, height = 200 }: AreaChartComponentProps) {
  const {
    xAxis = 'x',
    yAxis = 'y',
    colors = ['#3B82F6', '#EF4444', '#10B981', '#F59E0B'],
    title,
    showLegend = true
  } = config;

  // Y축 필드들 (단일 또는 다중)
  const yFields = Array.isArray(yAxis) ? yAxis : [yAxis];
  const yKeys = yFields.filter(field => field && field !== 'y');

  return (
    <div className="w-full h-full p-2">
      {title && (
        <div className="text-center text-sm font-semibold text-gray-700 mb-2">
          {title}
        </div>
      )}
      
      <ResponsiveContainer width="100%" height="100%">
        <AreaChart
          data={data}
          margin={{
            top: 5,
            right: 30,
            left: 20,
            bottom: 5,
          }}
        >
          <defs>
            {yKeys.map((key, index) => (
              <linearGradient key={key} id={`color${index}`} x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor={colors[index % colors.length]} stopOpacity={0.8}/>
                <stop offset="95%" stopColor={colors[index % colors.length]} stopOpacity={0.1}/>
              </linearGradient>
            ))}
          </defs>
          <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
          <XAxis 
            dataKey={xAxis}
            tick={{ fontSize: 12 }}
            stroke="#666"
          />
          <YAxis 
            tick={{ fontSize: 12 }}
            stroke="#666"
          />
          <Tooltip 
            contentStyle={{
              backgroundColor: 'white',
              border: '1px solid #ccc',
              borderRadius: '4px',
              fontSize: '12px'
            }}
            formatter={(value: any, name: string) => [
              typeof value === 'number' ? value.toLocaleString() : value,
              name
            ]}
          />
          {showLegend && yKeys.length > 1 && (
            <Legend 
              wrapperStyle={{ fontSize: '12px' }}
            />
          )}
          
          {yKeys.map((key, index) => (
            <Area
              key={key}
              type="monotone"
              dataKey={key}
              stroke={colors[index % colors.length]}
              fill={`url(#color${index})`}
              strokeWidth={2}
            />
          ))}
        </AreaChart>
      </ResponsiveContainer>
    </div>
  );
}
