"use client";

import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { CategoryIcon } from "@/components/ui/category-icon";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
} from "recharts";
import { ChevronDown, ChevronUp, Layers, List } from "lucide-react";
import type { Category } from "@/lib/types";

interface CategoryTrendDataPoint {
  month: string;
  [categoryId: string]: string | number;
}

interface CategoryTrendChartProps {
  data: CategoryTrendDataPoint[];
  dataByParent: CategoryTrendDataPoint[];
  categories: Category[];
  formatCurrency: (amount: number) => string;
  maxCategories?: number;
}

const CATEGORY_COLORS = [
  "#ef4444", // red
  "#f59e0b", // amber
  "#eab308", // yellow
  "#22c55e", // green
  "#06b6d4", // cyan
  "#3b82f6", // blue
  "#6366f1", // indigo
  "#8b5cf6", // violet
  "#ec4899", // pink
  "#f97316", // orange
];

export function CategoryTrendChart({
  data,
  dataByParent,
  categories,
  formatCurrency,
  maxCategories = 5,
}: CategoryTrendChartProps) {
  const [isExpanded, setIsExpanded] = useState(false);
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [groupByParent, setGroupByParent] = useState(true);

  // Use the appropriate dataset based on groupByParent
  const currentData = groupByParent ? dataByParent : data;

  // Get top categories by total amount
  const categoryTotals = new Map<string, number>();
  currentData.forEach((point) => {
    Object.keys(point).forEach((key) => {
      if (key !== "month" && typeof point[key] === "number") {
        const current = categoryTotals.get(key) || 0;
        categoryTotals.set(key, current + (point[key] as number));
      }
    });
  });

  const topCategories = Array.from(categoryTotals.entries())
    .sort((a, b) => b[1] - a[1])
    .slice(0, maxCategories)
    .map(([id]) => id);

  const displayCategories = isExpanded
    ? Array.from(categoryTotals.keys())
    : topCategories;

  const categoriesToShow =
    selectedCategories.length > 0 ? selectedCategories : displayCategories;

  // Helper function to get category name
  // When groupByParent is true, the categoryId in dataByParent is already the parent ID
  const getCategoryName = (categoryId: string): string => {
    if (categoryId === "uncategorized") return "Non catégorisé";
    const category = categories.find((c) => c.id === categoryId);
    return category?.name || "Inconnu";
  };

  // Helper function to get category info (for color, icon)
  // When groupByParent is true, the categoryId in dataByParent is already the parent ID
  const getCategoryInfo = (categoryId: string): Category | null => {
    if (categoryId === "uncategorized") return null;
    return categories.find((c) => c.id === categoryId) || null;
  };

  return (
    <Card className="card-hover">
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <CardTitle>Évolution des dépenses par catégorie</CardTitle>
        <div className="flex gap-2">
          <Button
            variant={groupByParent ? "default" : "ghost"}
            size="sm"
            onClick={() => setGroupByParent(!groupByParent)}
            title={
              groupByParent
                ? "Afficher toutes les catégories"
                : "Regrouper par catégories parentes"
            }
          >
            {groupByParent ? (
              <>
                <List className="w-4 h-4 mr-1" />
                Par catégorie
              </>
            ) : (
              <>
                <Layers className="w-4 h-4 mr-1" />
                Par parent
              </>
            )}
          </Button>
          {categoryTotals.size > maxCategories && (
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsExpanded(!isExpanded)}
            >
              {isExpanded ? (
                <>
                  <ChevronUp className="w-4 h-4 mr-1" />
                  Réduire
                </>
              ) : (
                <>
                  <ChevronDown className="w-4 h-4 mr-1" />
                  Voir tout ({categoryTotals.size})
                </>
              )}
            </Button>
          )}
        </div>
      </CardHeader>
      <CardContent>
        {currentData.length > 0 && categoriesToShow.length > 0 ? (
          <div className="h-[350px]">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={currentData}>
                <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                <XAxis
                  dataKey="month"
                  className="text-xs"
                  interval="preserveStartEnd"
                />
                <YAxis
                  className="text-xs"
                  width={80}
                  tickFormatter={(v) => {
                    if (Math.abs(v) >= 1000) {
                      return `${(v / 1000).toFixed(1)}k€`;
                    }
                    return `${Math.round(v)}€`;
                  }}
                  tick={{ fill: "var(--muted-foreground)" }}
                />
                <Tooltip
                  formatter={(value: number) => formatCurrency(value)}
                  contentStyle={{
                    backgroundColor: "var(--card)",
                    border: "1px solid var(--border)",
                    borderRadius: "8px",
                  }}
                />
                <Legend
                  content={() => {
                    // Get all category IDs from data
                    const allCategoryIds = Array.from(categoryTotals.keys());

                    return (
                      <div className="flex flex-wrap justify-center gap-x-4 gap-y-1 mt-2">
                        {allCategoryIds.map((categoryId) => {
                          const categoryInfo = getCategoryInfo(categoryId);
                          const categoryName = getCategoryName(categoryId);
                          if (!categoryInfo && categoryId !== "uncategorized")
                            return null;

                          const isInDisplayCategories =
                            displayCategories.includes(categoryId);
                          const isSelected =
                            selectedCategories.length === 0
                              ? isInDisplayCategories
                              : selectedCategories.includes(categoryId);
                          return (
                            <button
                              key={`legend-${categoryId}`}
                              className={`flex items-center gap-1.5 text-sm cursor-pointer transition-opacity px-2 py-1 rounded ${
                                isSelected
                                  ? "opacity-100"
                                  : "opacity-30 hover:opacity-60"
                              }`}
                              onClick={() => {
                                if (selectedCategories.includes(categoryId)) {
                                  setSelectedCategories(
                                    selectedCategories.filter(
                                      (id) => id !== categoryId,
                                    ),
                                  );
                                } else {
                                  setSelectedCategories([
                                    ...selectedCategories,
                                    categoryId,
                                  ]);
                                }
                              }}
                            >
                              {categoryInfo ? (
                                <CategoryIcon
                                  icon={categoryInfo.icon}
                                  color={categoryInfo.color}
                                  size={14}
                                />
                              ) : (
                                <div
                                  className="w-3.5 h-3.5 rounded-full"
                                  style={{ backgroundColor: "#94a3b8" }}
                                />
                              )}
                              <span className="text-foreground">
                                {categoryName}
                              </span>
                            </button>
                          );
                        })}
                      </div>
                    );
                  }}
                />
                {categoriesToShow.map((categoryId, index) => {
                  const categoryInfo = getCategoryInfo(categoryId);
                  const categoryName = getCategoryName(categoryId);
                  if (!categoryInfo && categoryId !== "uncategorized")
                    return null;

                  const isSelected =
                    selectedCategories.length === 0 ||
                    selectedCategories.includes(categoryId);
                  return (
                    <Line
                      key={categoryId}
                      type="monotone"
                      dataKey={categoryId}
                      name={categoryName}
                      stroke={
                        categoryInfo?.color ||
                        CATEGORY_COLORS[index % CATEGORY_COLORS.length]
                      }
                      strokeWidth={isSelected ? 2 : 1}
                      strokeOpacity={isSelected ? 1 : 0.3}
                      dot={false}
                      hide={!isSelected && selectedCategories.length > 0}
                    />
                  );
                })}
              </LineChart>
            </ResponsiveContainer>
          </div>
        ) : (
          <div className="h-[350px] flex items-center justify-center text-muted-foreground">
            Pas de données pour cette période
          </div>
        )}
      </CardContent>
    </Card>
  );
}
