import {
  Bar,
  BarChart,
  CartesianGrid,
  Legend,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { Paper, Stack, Text } from "@mantine/core";

import type { IOverviewPaymentTrendPoint } from "@/types/overview";
import { overviewChartColors } from "./overview.styles";

function formatDateLabel(date: string) {
  const parsed = new Date(`${date}T00:00:00`);
  return parsed.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}

function formatAmount(value: number, currency: "ETB" | "USD") {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency,
    maximumFractionDigits: 0,
  }).format(value);
}

export function OverviewPaymentChart({ data }: { data: IOverviewPaymentTrendPoint[] }) {
  const hasData = data.some((point) => point.amountEtb > 0 || point.amountUsd > 0);

  return (
    <Paper p="md" radius="lg" withBorder h="100%" style={{ minHeight: 260 }}>
      <Stack gap="sm" h="100%">
        <Text fw={600}>Payment trend</Text>
        {!hasData ? (
          <Text size="sm" c="dimmed" ta="center" py="xl">
            No successful payments in this period
          </Text>
        ) : (
          <ResponsiveContainer width="100%" height={210}>
            <BarChart data={data} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
              <XAxis
                dataKey="date"
                tickFormatter={formatDateLabel}
                tick={{ fontSize: 12 }}
                stroke="#94a3b8"
              />
              <YAxis tick={{ fontSize: 12 }} stroke="#94a3b8" />
              <Tooltip
                labelFormatter={(value) => formatDateLabel(String(value))}
                formatter={(value, name) => [
                  formatAmount(Number(value), name === "amountUsd" ? "USD" : "ETB"),
                  name === "amountUsd" ? "USD" : "ETB",
                ]}
              />
              <Legend />
              <Bar
                dataKey="amountEtb"
                name="ETB"
                stackId="payments"
                fill={overviewChartColors.etb}
                radius={[0, 0, 0, 0]}
              />
              <Bar
                dataKey="amountUsd"
                name="USD"
                stackId="payments"
                fill={overviewChartColors.usd}
                radius={[4, 4, 0, 0]}
              />
            </BarChart>
          </ResponsiveContainer>
        )}
      </Stack>
    </Paper>
  );
}
