import React from 'react';
import { 
  LineChart, Line, BarChart, Bar, PieChart, Pie, Cell, AreaChart, Area,
  ResponsiveContainer, XAxis, YAxis, CartesianGrid, Tooltip, Legend, 
  RadialBarChart, RadialBar, LabelList
} from 'recharts';
import { motion } from 'framer-motion';
import { Maximize2 } from 'lucide-react';

const COLORS = ['#007E45', '#10b981', '#059669', '#047857', '#065f46', '#064e3b', '#022c22'];

// ============================================
// FORMATTERS
// ============================================

const formatToK = (value: number): string => {
  if (value >= 1000000) {
    return `${(value / 1000000).toFixed(1)}M€`;
  }
  if (value >= 1000) {
    return `${(value / 1000).toFixed(0)}K€`;
  }
  return `${value}€`;
};

const formatToKShort = (value: number): string => {
  if (value >= 1000000) {
    return `${(value / 1000000).toFixed(1)}M`;
  }
  if (value >= 1000) {
    return `${(value / 1000).toFixed(0)}K`;
  }
  return `${value}`;
};

const formatCurrency = (value: number): string => {
  return new Intl.NumberFormat('fr-FR', {
    style: 'currency',
    currency: 'EUR',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(value);
};

// ============================================
// CUSTOM TOOLTIP
// ============================================

interface TooltipProps {
  active?: boolean;
  payload?: any[];
  label?: string;
}

const CustomTooltip: React.FC<TooltipProps> = ({ active, payload, label }) => {
  if (active && payload && payload.length) {
    return (
      <div className="bg-white dark:bg-gray-900 p-3 border border-gray-200 dark:border-gray-800 rounded-xl shadow-lg text-sm z-50">
        <p className="font-semibold text-gray-900 dark:text-white mb-2">{label}</p>
        {payload.map((entry, index) => (
          <div key={index} className="flex items-center gap-2">
            <div 
              className="w-3 h-3 rounded-full" 
              style={{ backgroundColor: entry.color }}
            />
            <span className="text-gray-600 dark:text-gray-400">{entry.name}:</span>
            <span className="font-semibold" style={{ color: entry.color }}>
              {formatCurrency(entry.value)}
            </span>
          </div>
        ))}
      </div>
    );
  }
  return null;
};

// ============================================
// CUSTOM LABEL POUR LES VALEURS SUR LE GRAPHIQUE
// ============================================

const CustomLabel = (props: any) => {
  const { x, y, value, index } = props;
  return (
    <text
      x={x}
      y={y - 10}
      fill="#007E45"
      textAnchor="middle"
      fontSize={11}
      fontWeight={600}
    >
      {formatToK(value)}
    </text>
  );
};

// ============================================
// TYPES (exportés pour réutilisation)
// ============================================

interface ChartCardProps {
  title: string;
  type?: string;
  data: any[];
  height?: number;
  className?: string;
  showLabels?: boolean;   // Afficher les valeurs sur le graphique
  showTotal?: boolean;    // Afficher le total sous le titre
  showYAxisLabel?: boolean; // Afficher le label de l'axe Y
  yAxisLabel?: string;    // Label de l'axe Y (ex: "Montant en K€")
}

// ============================================
// COMPOSANT PRINCIPAL
// ============================================

const ChartCard: React.FC<ChartCardProps> = ({ 
  title, 
  type = 'line', 
  data, 
  height = 300, 
  className,
  showLabels = true,
  showTotal = true,
  showYAxisLabel = true,
  yAxisLabel = "Montant en K€"
}) => {
  // Guard clause
  if (!data || data.length === 0) {
    return (
      <div className={`bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-6 flex flex-col ${className}`}>
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">{title}</h3>
        <div className="h-full flex items-center justify-center text-gray-400 text-sm">
          Pas de données
        </div>
      </div>
    );
  }

  // Calculer le total pour l'afficher
  const total = data.reduce((sum, item) => sum + (item.value || 0), 0) / 1000

  return (
    <motion.div 
      initial={{ opacity: 0, y: 20 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      transition={{ duration: 0.5 }}
      className={`bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-6 flex flex-col ${className}`}
    >
      <div className="flex items-center justify-between mb-2">
        <div>
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">{title}</h3>
          {showTotal && (
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Total: <span className="font-semibold text-[#007E45]">{total.toFixed(0)} K €</span>
            </p>
          )}
        </div>
        <button className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg">
          <Maximize2 className="w-4 h-4" />
        </button>
      </div>

      {/* Label de l'axe Y */}
      {showYAxisLabel && (type === 'line' || type === 'area' || type === 'bar') && (
        <p className="text-xs text-gray-400 mb-4">{yAxisLabel}</p>
      )}
      
      <div style={{ width: '100%', height }}>
        <ResponsiveContainer>
          {type === 'line' && (
            <LineChart data={data} margin={{ top: 20, right: 20, left: 0, bottom: 5 }}>
              <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#e5e7eb" opacity={0.5} />
              <XAxis 
                dataKey="name" 
                stroke="#9ca3af" 
                fontSize={12} 
                tickLine={false} 
                axisLine={false} 
                dy={10} 
              />
              <YAxis 
                stroke="#9ca3af" 
                fontSize={11} 
                tickLine={false} 
                axisLine={false} 
                tickFormatter={formatToKShort}
                dx={-5}
                width={45}
              />
              <Tooltip content={<CustomTooltip />} />
              <Line 
                type="monotone" 
                dataKey="value" 
                name="CA"
                stroke="#007E45" 
                strokeWidth={3} 
                dot={{ r: 5, fill: '#fff', strokeWidth: 2, stroke: '#007E45' }} 
                activeDot={{ r: 7, stroke: '#007E45', strokeWidth: 2, fill: '#007E45' }}
              >
                {showLabels && (
                  <LabelList 
                    dataKey="value" 
                    position="top" 
                    formatter={formatToK}
                    style={{ fontSize: 11, fontWeight: 600, fill: '#007E45' }}
                  />
                )}
              </Line>
            </LineChart>
          )}

          {type === 'area' && (
            <AreaChart data={data} margin={{ top: 20, right: 20, left: 0, bottom: 5 }}>
              <defs>
                <linearGradient id="colorValue" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#007E45" stopOpacity={0.3}/>
                  <stop offset="95%" stopColor="#007E45" stopOpacity={0.05}/>
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#e5e7eb" opacity={0.5} />
              <XAxis 
                dataKey="name" 
                stroke="#9ca3af" 
                fontSize={12} 
                tickLine={false} 
                axisLine={false} 
                dy={10} 
              />
              <YAxis 
                stroke="#9ca3af" 
                fontSize={11} 
                tickLine={false} 
                axisLine={false} 
                tickFormatter={formatToKShort}
                dx={-5}
                width={45}
              />
              <Tooltip content={<CustomTooltip />} />
              <Area 
                type="monotone" 
                dataKey="value" 
                name="CA"
                stroke="#007E45" 
                strokeWidth={2}
                fillOpacity={1} 
                fill="url(#colorValue)"
              >
                {showLabels && (
                  <LabelList 
                    dataKey="value" 
                    position="top" 
                    formatter={formatToK}
                    style={{ fontSize: 11, fontWeight: 600, fill: '#007E45' }}
                  />
                )}
              </Area>
            </AreaChart>
          )}

          {type === 'bar' && (
            <BarChart data={data} margin={{ top: 20, right: 20, left: 0, bottom: 5 }}>
              <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#e5e7eb" opacity={0.5} />
              <XAxis 
                dataKey="name" 
                stroke="#9ca3af" 
                fontSize={12} 
                tickLine={false} 
                axisLine={false} 
                dy={10} 
              />
              <YAxis 
                stroke="#9ca3af" 
                fontSize={11} 
                tickLine={false} 
                axisLine={false} 
                tickFormatter={formatToKShort}
                dx={-5}
                width={45}
              />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="value" name="CA" radius={[4, 4, 0, 0]}>
                {data.map((entry, index) => (
                  <Cell key={`cell-${index}`} fill={entry.fill || COLORS[index % COLORS.length]} />
                ))}
                {showLabels && (
                  <LabelList 
                    dataKey="value" 
                    position="top" 
                    formatter={formatToK}
                    style={{ fontSize: 10, fontWeight: 600, fill: '#374151' }}
                  />
                )}
              </Bar>
            </BarChart>
          )}

          {type === 'donut' && (
              <PieChart>
                <Pie
                  data={data}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={80}
                  paddingAngle={5}
                  dataKey="value"
                >
                  {data.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.fill || COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip content={<CustomTooltip />} />
                <Legend verticalAlign="bottom" height={36} iconType="circle" />
              </PieChart>
          )}

          {type === 'radial' && (
            <RadialBarChart cx="50%" cy="50%" innerRadius="70%" outerRadius="100%" barSize={10} data={data}>
               <RadialBar
                 minAngle={15}
                 label={{ position: 'insideStart', fill: '#fff' }}
                 background
                 clockWise
                 dataKey="value"
               />
               <Legend iconSize={10} layout="vertical" verticalAlign="middle" wrapperStyle={{ top: '50%', right: 0, transform: 'translate(0, -50%)', lineHeight: '24px' }} />
             </RadialBarChart>
          )}
        </ResponsiveContainer>
      </div>
    </motion.div>
  );
};

export default ChartCard;
