import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Legend,
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';
import { formatCount } from '@/lib/formatters';

export type ChartDatum = { label: string; value: number };

export const CHART_PALETTE = [
  '#0EA678', '#0EA5E9', '#8B5CF6', '#F59E0B',
  '#EF4444', '#14B8A6', '#6366F1', '#EC4899',
];

const AXIS_STYLE = { fontFamily: 'Estedad, Tahoma, sans-serif', fontSize: 11, fill: '#94A3B8' };

function FaTooltip({ active, payload, label }: { active?: boolean; payload?: Array<{ value: number; name?: string }>; label?: string }) {
  if (!active || !payload || payload.length === 0) return null;
  return (
    <div
      dir="rtl"
      style={{
        background: '#1E293B',
        borderRadius: 10,
        boxShadow: '0 12px 32px rgba(15,23,42,0.3)',
        color: '#F1F5F9',
        fontFamily: 'Estedad, Tahoma, sans-serif',
        fontSize: '0.8rem',
        padding: '0.5rem 0.75rem',
      }}
    >
      <div style={{ color: '#94A3B8', marginBottom: 2 }}>{label ?? payload[0].name}</div>
      <strong>{formatCount(payload[0].value)}</strong>
    </div>
  );
}

const faTick = (value: number) => formatCount(value);

/** نمودار روند با گرادیان — برای سری‌های زمانی. */
export function TrendAreaChart({ data, color = '#0EA678', height = 220 }: { data: ChartDatum[]; color?: string; height?: number }) {
  const gradientId = `trend-${color.replace('#', '')}`;
  return (
    <ResponsiveContainer width="100%" height={height}>
      <AreaChart data={data} margin={{ top: 8, right: 8, left: 8, bottom: 0 }}>
        <defs>
          <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity={0.32} />
            <stop offset="100%" stopColor={color} stopOpacity={0.02} />
          </linearGradient>
        </defs>
        <CartesianGrid strokeDasharray="4 4" stroke="#E2E8F0" vertical={false} />
        <XAxis dataKey="label" tick={AXIS_STYLE} axisLine={false} tickLine={false} />
        <YAxis tick={AXIS_STYLE} tickFormatter={faTick} axisLine={false} tickLine={false} width={42} orientation="right" />
        <Tooltip content={<FaTooltip />} cursor={{ stroke: '#CBD5E1' }} />
        <Area type="monotone" dataKey="value" stroke={color} strokeWidth={2.5} fill={`url(#${gradientId})`} />
      </AreaChart>
    </ResponsiveContainer>
  );
}

/** نمودار میله‌ای با گوشه گرد. */
export function BarsChart({ data, color = '#0EA678', height = 220 }: { data: ChartDatum[]; color?: string; height?: number }) {
  return (
    <ResponsiveContainer width="100%" height={height}>
      <BarChart data={data} margin={{ top: 8, right: 8, left: 8, bottom: 0 }}>
        <CartesianGrid strokeDasharray="4 4" stroke="#E2E8F0" vertical={false} />
        <XAxis dataKey="label" tick={AXIS_STYLE} axisLine={false} tickLine={false} />
        <YAxis tick={AXIS_STYLE} tickFormatter={faTick} axisLine={false} tickLine={false} width={42} orientation="right" />
        <Tooltip content={<FaTooltip />} cursor={{ fill: 'rgba(148,163,184,0.1)' }} />
        <Bar dataKey="value" fill={color} radius={[6, 6, 0, 0]} maxBarSize={42} />
      </BarChart>
    </ResponsiveContainer>
  );
}

/** نمودار دایره‌ای (دونات) با راهنمای فارسی. */
export function DonutChart({ data, height = 220 }: { data: ChartDatum[]; height?: number }) {
  return (
    <ResponsiveContainer width="100%" height={height}>
      <PieChart>
        <Pie
          data={data}
          dataKey="value"
          nameKey="label"
          innerRadius="58%"
          outerRadius="82%"
          paddingAngle={3}
          stroke="none"
        >
          {data.map((entry, index) => (
            <Cell key={entry.label} fill={CHART_PALETTE[index % CHART_PALETTE.length]} />
          ))}
        </Pie>
        <Tooltip content={<FaTooltip />} />
        <Legend
          formatter={(value: string) => (
            <span style={{ fontFamily: 'Estedad, Tahoma, sans-serif', fontSize: '0.8rem', color: '#64748B' }}>{value}</span>
          )}
        />
      </PieChart>
    </ResponsiveContainer>
  );
}
