import { createMemo } from "solid-js";
import { useI18n } from "../../providers/i18n-provider";

interface DataPoint {
  label: string;
  value: number;
}

export function RevenueChart(props: { data?: DataPoint[]; bookings?: any[] }) {
  const i18n = useI18n();

  const chartData = createMemo(() => {
    if (props.data && props.data.length > 0) return props.data;

    // Build last 7 days from bookings
    const days: DataPoint[] = [];
    const bookings = props.bookings ?? [];
    const today = new Date();
    for (let i = 6; i >= 0; i--) {
      const d = new Date(today);
      d.setDate(d.getDate() - i);
      const dateStr = d.toISOString().split("T")[0];
      const count = bookings.filter((b: any) => {
        const bd = new Date(b.startsAt).toISOString().split("T")[0];
        return bd === dateStr;
      }).length;
      days.push({
        label: d.toLocaleDateString(i18n.locale() === "cs" ? "cs-CZ" : "en-US", { weekday: "short" }),
        value: count,
      });
    }
    return days;
  });

  const maxValue = createMemo(() => Math.max(1, ...chartData().map((d) => d.value)));
  const total = createMemo(() => chartData().reduce((s, d) => s + d.value, 0));

  return (
    <div class="surface-card p-6">
      <div class="flex items-start justify-between mb-6">
        <div>
          <h3 class="text-lg font-semibold text-ink">{i18n.t("dashboard.revenueTitle")}</h3>
          <p class="text-sm text-ink-muted mt-0.5">{i18n.t("dashboard.revenueSubtitle")}</p>
        </div>
        <div class="text-right">
          <p class="text-2xl font-bold text-ink tracking-tight">{total()}</p>
          <p class="text-xs text-ink-muted">{i18n.t("dashboard.totalBookings")}</p>
        </div>
      </div>

      <div class="flex items-end gap-2 sm:gap-3 h-40">
        {chartData().map((point, i) => {
          const heightPct = Math.round((point.value / maxValue()) * 100);
          return (
            <div class="flex-1 flex flex-col items-center gap-2">
              <div class="w-full flex-1 flex items-end">
                <div
                  class="w-full rounded-t-md bg-accent/80 hover:bg-accent transition-all duration-300 relative group"
                  style={{ height: `${Math.max(heightPct, 4)}%` }}
                >
                  <div class="absolute -top-7 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-md bg-ink text-canvas text-xs font-medium opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none">
                    {point.value}
                  </div>
                </div>
              </div>
              <span class="text-[10px] sm:text-xs text-ink-muted font-medium uppercase">{point.label}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}
