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

import type { IOverviewTrendPoint } 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" });
}

export function OverviewBookingTrendChart({ data }: { data: IOverviewTrendPoint[] }) {
  const hasData = data.some((point) => point.count > 0);

  return (
    <Paper p="md" radius="lg" withBorder h="100%" style={{ minHeight: 260 }}>
      <Stack gap="sm" h="100%">
        <Text fw={600}>Booking trend</Text>
        {!hasData ? (
          <Text size="sm" c="dimmed" ta="center" py="xl">
            No bookings in this period
          </Text>
        ) : (
          <ResponsiveContainer width="100%" height={210}>
            <AreaChart data={data} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
              <defs>
                <linearGradient id="bookingTrendFill" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor={overviewChartColors.primary} stopOpacity={0.35} />
                  <stop offset="95%" stopColor={overviewChartColors.primary} stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
              <XAxis
                dataKey="date"
                tickFormatter={formatDateLabel}
                tick={{ fontSize: 12 }}
                stroke="#94a3b8"
              />
              <YAxis allowDecimals={false} tick={{ fontSize: 12 }} stroke="#94a3b8" />
              <Tooltip
                labelFormatter={(value) => formatDateLabel(String(value))}
                formatter={(value) => [value, "Bookings"]}
              />
              <Area
                type="monotone"
                dataKey="count"
                stroke={overviewChartColors.primary}
                fill="url(#bookingTrendFill)"
                strokeWidth={2}
              />
            </AreaChart>
          </ResponsiveContainer>
        )}
      </Stack>
    </Paper>
  );
}
