import { useMemo, useState } from 'react';
import { cn } from '@/lib/utils';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Activity } from 'lucide-react';
import { format, subDays } from 'date-fns';
import { fr } from 'date-fns/locale';

interface DataPoint {
  date: string;
  value: number;
  label: string;
}

// Génération de fausses données réalistes pour la démo
const generateData = (days: number): DataPoint[] => {
  const data: DataPoint[] = [];
  for (let i = days; i >= 0; i--) {
    const date = subDays(new Date(), i);
    // Tendance haussière aléatoire
    const base = 50 + Math.random() * 50;
    const trend = (days - i) * 2;
    data.push({
      date: date.toISOString(),
      label: format(date, 'd MMM', { locale: fr }),
      value: Math.min(100, Math.max(10, Math.floor(base + trend))),
    });
  }
  return data;
};

export function ActivityGraph() {
  const [period, setPeriod] = useState<7 | 30>(7);
  const [hoveredPoint, setHoveredPoint] = useState<number | null>(null);

  const data = useMemo(() => generateData(period), [period]);
  const maxValue = Math.max(...data.map(d => d.value));

  return (
    <Card variant="glass" className="h-full flex flex-col overflow-hidden">
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <div className="space-y-1">
          <CardTitle className="flex items-center gap-2 text-base font-medium">
            <Activity className="w-4 h-4 text-kodo-cyan" />
            Activité d'écoute
          </CardTitle>
          <p className="text-xs text-kodo-text-dim">
            +14.5% par rapport à la période précédente
          </p>
        </div>

        <div className="flex bg-kodo-ink/50 p-1 rounded-lg border border-white/5">
          <button
            onClick={() => setPeriod(7)}
            className={cn(
              "px-3 py-1 text-xs font-medium rounded-md transition-all",
              period === 7
                ? "bg-kodo-cyan/20 text-kodo-cyan shadow-sm"
                : "text-kodo-text-dim hover:text-white"
            )}
          >
            7J
          </button>
          <button
            onClick={() => setPeriod(30)}
            className={cn(
              "px-3 py-1 text-xs font-medium rounded-md transition-all",
              period === 30
                ? "bg-kodo-cyan/20 text-kodo-cyan shadow-sm"
                : "text-kodo-text-dim hover:text-white"
            )}
          >
            30J
          </button>
        </div>
      </CardHeader>

      <CardContent className="flex-1 flex items-end justify-between gap-2 pt-8 pb-4 px-6 relative">
        {/* Lignes de repère (Grid lines) */}
        <div className="absolute inset-0 px-6 pt-8 pb-10 flex flex-col justify-between pointer-events-none opacity-20">
          <div className="border-t border-dashed border-kodo-steel w-full h-0" />
          <div className="border-t border-dashed border-kodo-steel w-full h-0" />
          <div className="border-t border-dashed border-kodo-steel w-full h-0" />
        </div>

        {/* Barres Graphiques */}
        {data.map((point, i) => {
          const height = (point.value / maxValue) * 100;
          const isHovered = hoveredPoint === i;

          return (
            <div
              key={i}
              className="relative flex-1 h-full flex items-end group"
              onMouseEnter={() => setHoveredPoint(i)}
              onMouseLeave={() => setHoveredPoint(null)}
            >
              {/* Barre */}
              <div
                className={cn(
                  "w-full rounded-t-sm transition-all duration-300 relative z-10",
                  isHovered ? "bg-kodo-cyan opacity-100" : "bg-kodo-cyan/30 opacity-70",
                  // Animation d'entrée
                  "animate-slideUp"
                )}
                style={{
                  height: `${height}%`,
                  animationDelay: `${i * 50}ms`
                }}
              >
                {/* Glow Effect on Hover */}
                {isHovered && (
                  <div className="absolute inset-0 bg-kodo-cyan blur-md opacity-50" />
                )}
              </div>

              {/* Tooltip */}
              <div
                className={cn(
                  "absolute bottom-[110%] left-1/2 -translate-x-1/2 z-20 transition-all duration-200 pointer-events-none",
                  isHovered ? "opacity-100 translate-y-0" : "opacity-0 translate-y-2"
                )}
              >
                <div className="bg-kodo-ink border border-kodo-steel/50 px-3 py-2 rounded-lg shadow-xl whitespace-nowrap">
                  <div className="text-xs font-bold text-white mb-0.5">{point.value} écoutes</div>
                  <div className="text-[10px] text-kodo-text-dim font-mono">{point.label}</div>
                </div>
                {/* Triangle du tooltip */}
                <div className="w-2 h-2 bg-kodo-ink border-b border-r border-kodo-steel/50 rotate-45 absolute -bottom-1 left-1/2 -translate-x-1/2" />
              </div>

              {/* Label Axe X (tous les 3 ou 5 points selon densité) */}
              {(period === 7 || i % 5 === 0) && (
                <div className="absolute top-full mt-2 left-1/2 -translate-x-1/2 text-[10px] text-kodo-text-dim font-mono whitespace-nowrap">
                  {point.label.split(' ')[0]}
                </div>
              )}
            </div>
          );
        })}
      </CardContent>
    </Card>
  );
}
