'use client';

import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
} from 'recharts';
import { DailyMetrics } from '@/services/analytics/metrics';
import { parseDate, formatDateShort } from '@/lib/date-utils';

interface DailyStatusChartProps {
  data: DailyMetrics[];
  className?: string;
}

export function DailyStatusChart({ data, className }: DailyStatusChartProps) {
  // Transformer les données pour le graphique
  const chartData = data.map((day) => ({
    day: day.dayName.substring(0, 3), // Lun, Mar, etc.
    date: formatDateShort(parseDate(day.date)),
    Complétées: day.completed,
    'En cours': day.inProgress,
    Bloquées: day.blocked,
    'En attente': day.pending,
    Nouvelles: day.newTasks,
  }));

  const CustomTooltip = ({
    active,
    payload,
    label,
  }: {
    active?: boolean;
    payload?: Array<{
      dataKey: string;
      value: number;
      color: string;
      payload: {
        day: string;
        date: string;
        Complétées: number;
        'En cours': number;
        Bloquées: number;
        'En attente': number;
        Nouvelles: number;
      };
    }>;
    label?: string;
  }) => {
    if (active && payload && payload.length) {
      return (
        <div className="bg-[var(--card)] border border-[var(--border)] rounded-lg p-3 shadow-lg">
          <p className="font-medium mb-2">{`${label} (${payload[0]?.payload?.date})`}</p>
          {payload.map(
            (
              entry: { dataKey: string; value: number; color: string },
              index: number
            ) => (
              <p key={index} style={{ color: entry.color }} className="text-sm">
                {`${entry.dataKey}: ${entry.value}`}
              </p>
            )
          )}
        </div>
      );
    }
    return null;
  };

  return (
    <div className={className}>
      <ResponsiveContainer width="100%" height={300}>
        <BarChart
          data={chartData}
          margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
        >
          <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
          <XAxis dataKey="day" stroke="var(--muted-foreground)" fontSize={12} />
          <YAxis stroke="var(--muted-foreground)" fontSize={12} />
          <Tooltip content={<CustomTooltip />} />
          <Legend />
          <Bar dataKey="Complétées" fill="#10b981" radius={[2, 2, 0, 0]} />
          <Bar dataKey="En cours" fill="#3b82f6" radius={[2, 2, 0, 0]} />
          <Bar dataKey="Bloquées" fill="#ef4444" radius={[2, 2, 0, 0]} />
          <Bar dataKey="En attente" fill="#94a3b8" radius={[2, 2, 0, 0]} />
          <Bar dataKey="Nouvelles" fill="#8b5cf6" radius={[2, 2, 0, 0]} />
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}
