"use client";

import { useState } from "react";
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { CategoryIcon } from "@/components/ui/category-icon";
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer } from "recharts";
import { Layers, List, ChevronDown, ChevronUp } from "lucide-react";
import type { Category } from "@/lib/types";

export interface CategoryChartData {
  name: string;
  value: number;
  color: string;
  icon: string;
  categoryId?: string | null; // null for "Non catégorisé"
  [key: string]: string | number | null | undefined;
}

interface CategoryPieChartProps {
  data: CategoryChartData[];
  dataByParent?: CategoryChartData[];
  categories?: Category[];
  formatCurrency: (amount: number) => string;
  title?: string;
  height?: number;
  innerRadius?: number;
  outerRadius?: number;
  emptyMessage?: string;
}

export function CategoryPieChart({
  data,
  dataByParent,
  categories: _categories = [],
  formatCurrency,
  title = "Répartition par catégorie",
  height = 300,
  innerRadius = 60,
  outerRadius = 100,
  emptyMessage = "Pas de données pour cette période",
}: CategoryPieChartProps) {
  const [groupByParent, setGroupByParent] = useState(true);
  const [isExpanded, setIsExpanded] = useState(false);
  const hasParentData = dataByParent && dataByParent.length > 0;
  const baseData = groupByParent && hasParentData ? dataByParent : data;

  // Limit to top 8 by default, show all if expanded
  const maxItems = 8;
  const currentData = isExpanded ? baseData : baseData.slice(0, maxItems);

  return (
    <Card className="card-hover">
      <CardHeader className="flex flex-col md:flex-row md:items-center md:justify-between space-y-2 md:space-y-0 pb-2">
        <CardTitle className="text-sm md:text-base">{title}</CardTitle>
        <div className="flex flex-col md:flex-row gap-2 w-full md:w-auto">
          {hasParentData && (
            <Button
              variant={groupByParent ? "default" : "ghost"}
              size="sm"
              onClick={() => setGroupByParent(!groupByParent)}
              title={
                groupByParent
                  ? "Afficher toutes les catégories"
                  : "Regrouper par catégories parentes"
              }
              className="w-full md:w-auto text-xs md:text-sm"
            >
              {groupByParent ? (
                <>
                  <List className="w-3 h-3 md:w-4 md:h-4 mr-1" />
                  Par catégorie
                </>
              ) : (
                <>
                  <Layers className="w-3 h-3 md:w-4 md:h-4 mr-1" />
                  Par parent
                </>
              )}
            </Button>
          )}
          {baseData.length > maxItems && (
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsExpanded(!isExpanded)}
              className="w-full md:w-auto text-xs md:text-sm"
            >
              {isExpanded ? (
                <>
                  <ChevronUp className="w-3 h-3 md:w-4 md:h-4 mr-1" />
                  Réduire
                </>
              ) : (
                <>
                  <ChevronDown className="w-3 h-3 md:w-4 md:h-4 mr-1" />
                  Voir tout ({baseData.length})
                </>
              )}
            </Button>
          )}
        </div>
      </CardHeader>
      <CardContent>
        {currentData.length > 0 ? (
          <div className="flex flex-col lg:flex-row gap-6">
            {/* Graphique */}
            <div className="flex-1" style={{ minHeight: height }}>
              <ResponsiveContainer width="100%" height={height}>
                <PieChart>
                  <Pie
                    data={currentData}
                    cx="50%"
                    cy="50%"
                    innerRadius={innerRadius}
                    outerRadius={outerRadius}
                    paddingAngle={2}
                    dataKey="value"
                  >
                    {currentData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip
                    content={({ active, payload }) => {
                      if (!active || !payload?.length) return null;
                      const item = payload[0].payload as CategoryChartData;
                      return (
                        <div
                          className="px-3 py-2 rounded-lg shadow-lg"
                          style={{
                            backgroundColor: "var(--card)",
                            border: "1px solid var(--border)",
                          }}
                        >
                          <div className="flex items-center gap-2">
                            <CategoryIcon
                              icon={item.icon}
                              color={item.color}
                              size={16}
                            />
                            <span
                              className="font-medium"
                              style={{ color: item.color }}
                            >
                              {item.name}
                            </span>
                          </div>
                          <div className="text-foreground font-semibold mt-1">
                            {formatCurrency(item.value)}
                          </div>
                        </div>
                      );
                    }}
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>

            {/* Légende */}
            <div className="lg:w-[280px] lg:min-w-[280px]">
              <div className="text-sm font-medium mb-3 text-muted-foreground">
                Légende
              </div>
              <div className="max-h-[300px] overflow-y-auto overflow-x-hidden pr-2 space-y-2">
                {currentData.map((item, index) => {
                  const href =
                    item.categoryId === null || item.categoryId === undefined
                      ? "/transactions?includeUncategorized=true"
                      : `/transactions?categoryIds=${item.categoryId}`;

                  return (
                    <Link
                      key={`legend-${index}`}
                      href={href}
                      className="flex items-center gap-2 text-sm hover:opacity-80 transition-opacity cursor-pointer"
                    >
                      <CategoryIcon
                        icon={item.icon}
                        color={item.color}
                        size={16}
                      />
                      <span className="text-foreground flex-1 min-w-0 truncate">
                        {item.name}
                      </span>
                      <span className="text-foreground font-semibold tabular-nums whitespace-nowrap">
                        {formatCurrency(item.value)}
                      </span>
                    </Link>
                  );
                })}
              </div>
            </div>
          </div>
        ) : (
          <div
            style={{ height }}
            className="flex items-center justify-center text-muted-foreground"
          >
            {emptyMessage}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
