"use client";

import { useMemo, useState } from "react";
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from "recharts";
import type { FinanceTransaction } from "@/types";

type TimeRange = "7d" | "30d" | "90d" | "1y" | "all";

const RANGE_LABELS: Record<TimeRange, string> = {
  "7d": "7 Tage",
  "30d": "30 Tage",
  "90d": "90 Tage",
  "1y": "1 Jahr",
  all: "Gesamt",
};

function formatMoney(cents: number) {
  return new Intl.NumberFormat("de-DE", {
    style: "currency",
    currency: "EUR",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(cents / 100);
}

function formatShortDate(dateStr: string) {
  const d = new Date(dateStr + "T00:00:00");
  return d.toLocaleDateString("de-DE", { day: "2-digit", month: "short" });
}

interface ChartDataPoint {
  date: string;
  label: string;
  income: number;
  expenses: number;
  net: number;
  cumulative: number;
}

function buildChartData(
  transactions: FinanceTransaction[],
  range: TimeRange
): ChartDataPoint[] {
  if (transactions.length === 0) return [];

  const now = new Date();
  let startDate: Date;

  switch (range) {
    case "7d":
      startDate = new Date(now);
      startDate.setDate(startDate.getDate() - 7);
      break;
    case "30d":
      startDate = new Date(now);
      startDate.setDate(startDate.getDate() - 30);
      break;
    case "90d":
      startDate = new Date(now);
      startDate.setDate(startDate.getDate() - 90);
      break;
    case "1y":
      startDate = new Date(now);
      startDate.setFullYear(startDate.getFullYear() - 1);
      break;
    default: {
      const sorted = [...transactions].sort(
        (a, b) => a.transaction_date.localeCompare(b.transaction_date)
      );
      startDate = new Date(sorted[0].transaction_date + "T00:00:00");
    }
  }

  const filtered = transactions.filter(
    (t) => new Date(t.transaction_date + "T00:00:00") >= startDate
  );

  // Group by date
  const byDate = new Map<string, { income: number; expenses: number }>();
  filtered.forEach((t) => {
    const existing = byDate.get(t.transaction_date) || {
      income: 0,
      expenses: 0,
    };
    if (t.type === "income") {
      existing.income += t.amount_cents;
    } else {
      existing.expenses += t.amount_cents;
    }
    byDate.set(t.transaction_date, existing);
  });

  // Fill dates
  const dates: string[] = [];
  const cursor = new Date(startDate);
  while (cursor <= now) {
    dates.push(cursor.toISOString().split("T")[0]);
    cursor.setDate(cursor.getDate() + 1);
  }

  let cumulative = 0;
  return dates.map((date) => {
    const day = byDate.get(date) || { income: 0, expenses: 0 };
    const net = day.income - day.expenses;
    cumulative += net;
    return {
      date,
      label: formatShortDate(date),
      income: day.income,
      expenses: day.expenses,
      net,
      cumulative,
    };
  });
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function CustomTooltip({ active, payload, label }: any) {
  if (!active || !payload?.length) return null;
  const data = payload[0]?.payload as ChartDataPoint | undefined;
  if (!data) return null;

  return (
    <div className="rounded-xl border border-border/60 bg-card/95 px-4 py-3 shadow-xl backdrop-blur-sm">
      <p className="text-xs font-medium text-muted-foreground">{label}</p>
      <div className="mt-2 space-y-1">
        <div className="flex items-center gap-2 text-sm">
          <span className="h-2 w-2 rounded-full bg-emerald-500" />
          <span className="text-muted-foreground">Einnahmen:</span>
          <span className="font-semibold text-emerald-500">
            {formatMoney(data.income)}
          </span>
        </div>
        <div className="flex items-center gap-2 text-sm">
          <span className="h-2 w-2 rounded-full bg-rose-500" />
          <span className="text-muted-foreground">Ausgaben:</span>
          <span className="font-semibold text-rose-500">
            {formatMoney(data.expenses)}
          </span>
        </div>
        <div className="flex items-center gap-2 text-sm border-t border-border/40 pt-1">
          <span className="h-2 w-2 rounded-full bg-indigo-500" />
          <span className="text-muted-foreground">Kumuliert:</span>
          <span
            className={`font-semibold ${data.cumulative >= 0 ? "text-emerald-500" : "text-rose-500"}`}
          >
            {formatMoney(data.cumulative)}
          </span>
        </div>
      </div>
    </div>
  );
}

interface PnLChartProps {
  transactions: FinanceTransaction[];
}

export function PnLChart({ transactions }: PnLChartProps) {
  const [range, setRange] = useState<TimeRange>("30d");

  const data = useMemo(
    () => buildChartData(transactions, range),
    [transactions, range]
  );

  const totalIncome = useMemo(
    () => data.reduce((s, d) => s + d.income, 0),
    [data]
  );
  const totalExpenses = useMemo(
    () => data.reduce((s, d) => s + d.expenses, 0),
    [data]
  );
  const totalNet = totalIncome - totalExpenses;

  return (
    <div className="rounded-2xl border border-border/60 bg-card p-5">
      {/* Header */}
      <div className="flex flex-wrap items-start justify-between gap-4 mb-6">
        <div>
          <div className="flex items-center gap-2.5">
            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-gradient-to-br from-indigo-500 to-violet-600">
              <svg
                className="h-4 w-4 text-white"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 013 19.875v-6.75zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V8.625zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z"
                />
              </svg>
            </div>
            <div>
              <h2 className="text-sm font-semibold">Performance</h2>
              <p className="text-xs text-muted-foreground">
                Einnahmen vs. Ausgaben
              </p>
            </div>
          </div>
        </div>
        {/* Range selector */}
        <div className="flex items-center gap-1 rounded-xl border border-border/60 bg-background/60 p-1">
          {(Object.entries(RANGE_LABELS) as [TimeRange, string][]).map(
            ([key, label]) => (
              <button
                key={key}
                onClick={() => setRange(key)}
                className={`rounded-lg px-3 py-1.5 text-xs font-medium transition-all ${
                  range === key
                    ? "bg-foreground text-background shadow-sm"
                    : "text-muted-foreground hover:text-foreground"
                }`}
              >
                {label}
              </button>
            )
          )}
        </div>
      </div>

      {/* Summary row */}
      <div className="flex flex-wrap gap-6 mb-6">
        <div>
          <p className="text-xs text-muted-foreground">Einnahmen</p>
          <p className="text-lg font-bold text-emerald-500">
            {formatMoney(totalIncome)}
          </p>
        </div>
        <div>
          <p className="text-xs text-muted-foreground">Ausgaben</p>
          <p className="text-lg font-bold text-rose-500">
            {formatMoney(totalExpenses)}
          </p>
        </div>
        <div>
          <p className="text-xs text-muted-foreground">Netto</p>
          <p
            className={`text-lg font-bold ${totalNet >= 0 ? "text-emerald-500" : "text-rose-500"}`}
          >
            {formatMoney(totalNet)}
          </p>
        </div>
      </div>

      {/* Chart */}
      {data.length === 0 ? (
        <div className="flex h-[260px] items-center justify-center rounded-xl border border-dashed border-border/60">
          <p className="text-sm text-muted-foreground">
            Noch keine Transaktionen in diesem Zeitraum
          </p>
        </div>
      ) : (
        <div className="h-[260px] min-w-0">
          <ResponsiveContainer width="100%" height="100%" minWidth={0}>
            <AreaChart
              data={data}
              margin={{ top: 4, right: 4, left: 0, bottom: 0 }}
            >
              <defs>
                <linearGradient id="incomeGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#10b981" stopOpacity={0.3} />
                  <stop offset="100%" stopColor="#10b981" stopOpacity={0} />
                </linearGradient>
                <linearGradient id="expenseGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#f43f5e" stopOpacity={0.2} />
                  <stop offset="100%" stopColor="#f43f5e" stopOpacity={0} />
                </linearGradient>
                <linearGradient
                  id="cumulativeGrad"
                  x1="0"
                  y1="0"
                  x2="0"
                  y2="1"
                >
                  <stop offset="0%" stopColor="#6366f1" stopOpacity={0.25} />
                  <stop offset="100%" stopColor="#6366f1" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid
                strokeDasharray="3 3"
                stroke="var(--border)"
                opacity={0.4}
              />
              <XAxis
                dataKey="label"
                tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
                axisLine={false}
                tickLine={false}
                interval="preserveStartEnd"
              />
              <YAxis
                tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
                axisLine={false}
                tickLine={false}
                tickFormatter={(v: number) => `${Math.round(v / 100)}`}
                width={50}
              />
              <Tooltip content={<CustomTooltip />} />
              <Area
                type="monotone"
                dataKey="income"
                stroke="#10b981"
                strokeWidth={2}
                fill="url(#incomeGrad)"
                dot={false}
                activeDot={{ r: 4, strokeWidth: 0 }}
              />
              <Area
                type="monotone"
                dataKey="expenses"
                stroke="#f43f5e"
                strokeWidth={2}
                fill="url(#expenseGrad)"
                dot={false}
                activeDot={{ r: 4, strokeWidth: 0 }}
              />
              <Area
                type="monotone"
                dataKey="cumulative"
                stroke="#6366f1"
                strokeWidth={2.5}
                fill="url(#cumulativeGrad)"
                dot={false}
                activeDot={{ r: 5, strokeWidth: 0, fill: "#6366f1" }}
              />
            </AreaChart>
          </ResponsiveContainer>
        </div>
      )}
    </div>
  );
}
