'use client';

import { Card } from '@/components/ui/Card';
import {
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Tooltip,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  PieLabelRenderProps,
} from 'recharts';
import { TagDistributionMetrics } from '@/services/analytics/tag-analytics';

interface TagDistributionChartProps {
  metrics: TagDistributionMetrics;
  className?: string;
}

export function TagDistributionChart({
  metrics,
  className,
}: TagDistributionChartProps) {
  // Préparer les données pour le graphique en camembert
  const pieData = metrics.tagDistribution.slice(0, 8).map((tag) => ({
    name: tag.tagName,
    value: tag.count,
    percentage: tag.percentage,
    color: tag.tagColor, // Garder la couleur originale du tag
  }));

  // Préparer les données pour le graphique en barres (top tags)
  const barData = metrics.topTags.slice(0, 10).map((tag) => ({
    name:
      tag.tagName.length > 12
        ? `${tag.tagName.substring(0, 12)}...`
        : tag.tagName,
    usage: tag.usage,
    completionRate: tag.completionRate,
    avgPriority: tag.avgPriority,
    color: tag.tagColor, // Garder la couleur originale du tag
  }));

  // Tooltip personnalisé pour les tags (distribution)
  const TagTooltip = ({
    active,
    payload,
  }: {
    active?: boolean;
    payload?: Array<{
      payload: { name: string; value: number; percentage: number };
    }>;
  }) => {
    if (active && payload && payload.length) {
      const data = payload[0].payload;
      return (
        <div className="bg-[var(--card)] border border-[var(--border)] rounded-lg p-4 shadow-xl">
          <p className="font-semibold mb-2 text-[var(--foreground)]">
            {data.name}
          </p>
          <p className="text-sm text-[var(--muted-foreground)]">
            {data.value} tâches ({data.percentage.toFixed(1)}%)
          </p>
        </div>
      );
    }
    return null;
  };

  // Tooltip personnalisé pour les barres
  const BarTooltip = ({
    active,
    payload,
  }: {
    active?: boolean;
    payload?: Array<{
      payload: { name: string; usage: number; completionRate: number };
    }>;
  }) => {
    if (active && payload && payload.length) {
      const data = payload[0].payload;
      return (
        <div className="bg-[var(--card)] border border-[var(--border)] rounded-lg p-4 shadow-xl">
          <p className="font-semibold mb-2 text-[var(--foreground)]">
            {data.name}
          </p>
          <p className="text-sm text-[var(--muted-foreground)] mb-1">
            {data.usage} tâches
          </p>
          <p className="text-xs text-[var(--muted-foreground)]">
            Taux de completion: {data.completionRate.toFixed(1)}%
          </p>
        </div>
      );
    }
    return null;
  };

  // Légende personnalisée qui utilise directement les données du graphique
  const CustomLegend = () => {
    return (
      <div className="flex flex-wrap gap-4 mt-6">
        {pieData.map((entry, index) => (
          <div key={index} className="flex items-center gap-3">
            <div
              className="w-4 h-4 rounded-full border border-[var(--border)]"
              style={{ backgroundColor: entry.color }}
            />
            <span className="text-sm text-[var(--muted-foreground)]">
              {entry.name}
            </span>
          </div>
        ))}
      </div>
    );
  };

  return (
    <div className={className}>
      <div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
        {/* Distribution par tags - Camembert */}
        <Card variant="glass" className="p-6">
          <h3 className="text-lg font-semibold mb-4 text-[var(--foreground)]">
            Distribution par Tags
          </h3>

          <div className="h-60">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={pieData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={(props: PieLabelRenderProps) => {
                    const { percent } = props;
                    return typeof percent === 'number' && percent > 0.05
                      ? `${Math.round(percent * 100)}%`
                      : '';
                  }}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                  nameKey="name"
                >
                  {pieData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip content={<TagTooltip />} />
              </PieChart>
            </ResponsiveContainer>

            <CustomLegend />
          </div>
        </Card>

        {/* Top tags - Barres */}
        <Card variant="glass" className="p-6">
          <h3 className="text-lg font-semibold mb-4 text-[var(--foreground)]">
            Top Tags par Usage
          </h3>

          <div className="h-80">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart
                data={barData}
                margin={{ top: 20, right: 30, left: 20, bottom: 20 }}
              >
                <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
                <XAxis
                  dataKey="name"
                  tick={{ fontSize: 13, fill: 'var(--muted-foreground)' }}
                  angle={-45}
                  textAnchor="end"
                  height={80}
                  style={{
                    fontFamily: 'ui-monospace, SFMono-Regular, monospace',
                  }}
                />
                <YAxis
                  tick={{ fontSize: 13, fill: 'var(--foreground)' }}
                  style={{
                    fontFamily: 'ui-monospace, SFMono-Regular, monospace',
                  }}
                />
                <Tooltip content={<BarTooltip />} />
                <Bar dataKey="usage" radius={[4, 4, 0, 0]}>
                  {barData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </div>
        </Card>
      </div>

      {/* Statistiques des tags */}
      <Card variant="glass" className="p-6 mt-8">
        <h3 className="text-lg font-semibold mb-4 text-[var(--foreground)]">
          Statistiques des Tags
        </h3>

        <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
          <div className="text-center">
            <div className="text-2xl font-bold text-[var(--primary)]">
              {metrics.tagStats.totalTags}
            </div>
            <div className="text-sm text-[var(--muted-foreground)]">
              Tags totaux
            </div>
          </div>

          <div className="text-center">
            <div className="text-2xl font-bold text-[var(--success)]">
              {metrics.tagStats.activeTags}
            </div>
            <div className="text-sm text-[var(--muted-foreground)]">
              Tags actifs
            </div>
          </div>

          <div className="text-center">
            <div className="text-lg font-semibold text-[var(--foreground)] truncate">
              {metrics.tagStats.mostUsedTag}
            </div>
            <div className="text-sm text-[var(--muted-foreground)]">
              Plus utilisé
            </div>
          </div>

          <div className="text-center">
            <div className="text-lg font-semibold text-[var(--foreground)] truncate">
              {metrics.tagStats.leastUsedTag}
            </div>
            <div className="text-sm text-[var(--muted-foreground)]">
              Moins utilisé
            </div>
          </div>

          <div className="text-center">
            <div className="text-2xl font-bold text-[var(--accent)]">
              {metrics.tagStats.avgTasksPerTag.toFixed(1)}
            </div>
            <div className="text-sm text-[var(--muted-foreground)]">
              Moy. tâches/tag
            </div>
          </div>
        </div>
      </Card>
    </div>
  );
}
