"use client";

import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { AreaChart, CalendarRange, Check, Download, Table2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { withParams } from "@/lib/admin/list";
import { adminReportsTexts as t } from "@/lib/i18n/admin-reports";
import { cn } from "@/lib/utils";

export type ReportTabItem = { key: string; label: string };

const PERIODS: ReportTabItem[] = [
  { key: "today", label: t.period.today },
  { key: "week", label: t.period.week },
  { key: "month", label: t.period.month },
  { key: "custom", label: t.period.custom },
];

const DEFAULT_PERIOD = "month";
const DEFAULT_TAB = "payments";
const DEFAULT_VIEW = "chart";

/**
 * One control strip for the whole reports page: tab pills, the period picker
 * (Today / This week / This month / Custom), the Chart/Table toggle and the
 * per-tab CSV export. Every control is a real link so the server refetches.
 */
export function ReportToolbar({
  basePath,
  query,
  tabs,
  tab,
  period,
  view,
  from,
  to,
  rangeLabel,
  exportHref,
  showViewToggle = true,
}: {
  basePath: string;
  query: Record<string, string>;
  tabs: ReportTabItem[];
  tab: string;
  period: string;
  view: string;
  from: string;
  to: string;
  rangeLabel: string;
  exportHref: string;
  showViewToggle?: boolean;
}) {
  const router = useRouter();
  const [, startTransition] = React.useTransition();
  const [fromValue, setFromValue] = React.useState(from);
  const [toValue, setToValue] = React.useState(to);

  React.useEffect(() => setFromValue(from), [from]);
  React.useEffect(() => setToValue(to), [to]);

  const go = React.useCallback(
    (patch: Record<string, string | null>) => {
      startTransition(() => {
        router.push(withParams(basePath, query, { page: null, ...patch }), {
          scroll: false,
        });
      });
    },
    [basePath, query, router],
  );

  return (
    <div className="mb-3 space-y-2.5 rounded-2xl border bg-card p-2.5 shadow-sm">
      <div className="-mx-0.5 flex items-center gap-1 overflow-x-auto px-0.5">
        {tabs.map((item) => {
          const active = tab === item.key;
          return (
            <Link
              key={item.key}
              href={withParams(basePath, query, {
                tab: item.key === DEFAULT_TAB ? null : item.key,
                page: null,
                dataset: null,
                sort: null,
                dir: null,
              })}
              aria-current={active ? "page" : undefined}
              className={cn(
                "inline-flex shrink-0 items-center rounded-lg border px-3 py-1 text-sm font-medium transition-colors",
                active
                  ? "border-blue-600/40 bg-blue-600/10 text-blue-700 dark:text-blue-400"
                  : "border-transparent text-muted-foreground hover:bg-muted hover:text-foreground",
              )}
            >
              {item.label}
            </Link>
          );
        })}
      </div>

      <div className="flex flex-wrap items-center gap-2 border-t pt-2.5">
        <span className="hidden items-center gap-1.5 text-[11px] font-medium tracking-wider text-muted-foreground uppercase sm:inline-flex">
          <CalendarRange className="size-3.5" />
          {t.period.label}
        </span>

        <div className="flex items-center gap-1 rounded-lg border p-0.5">
          {PERIODS.map((p) => {
            const active = period === p.key;
            return (
              <Link
                key={p.key}
                href={withParams(basePath, query, {
                  period: p.key === DEFAULT_PERIOD ? null : p.key,
                  page: null,
                })}
                className={cn(
                  "rounded-md px-2 py-1 text-xs font-medium transition-colors",
                  active
                    ? "bg-blue-600 text-white"
                    : "text-muted-foreground hover:bg-muted hover:text-foreground",
                )}
              >
                {p.label}
              </Link>
            );
          })}
        </div>

        {period === "custom" ? (
          <form
            className="flex items-center gap-1.5"
            onSubmit={(e) => {
              e.preventDefault();
              go({ from: fromValue || null, to: toValue || null, period: "custom" });
            }}
          >
            <Input
              type="date"
              value={fromValue}
              onChange={(e) => setFromValue(e.target.value)}
              aria-label={t.period.from}
              className="h-7 w-[8.5rem] text-sm"
            />
            <span className="text-xs text-muted-foreground">–</span>
            <Input
              type="date"
              value={toValue}
              onChange={(e) => setToValue(e.target.value)}
              aria-label={t.period.to}
              className="h-7 w-[8.5rem] text-sm"
            />
            <Button type="submit" size="icon-sm" variant="outline" aria-label={t.period.apply}>
              <Check className="size-3.5" />
            </Button>
          </form>
        ) : (
          <span className="font-mono text-xs text-muted-foreground tabular-nums">
            {rangeLabel}
          </span>
        )}

        <div className="ml-auto flex items-center gap-2">
          {showViewToggle ? (
            <div className="flex items-center gap-1 rounded-lg border p-0.5">
              <Link
                href={withParams(basePath, query, { view: null })}
                aria-current={view === "chart" ? "page" : undefined}
                className={cn(
                  "inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors",
                  view === "chart"
                    ? "bg-blue-600 text-white"
                    : "text-muted-foreground hover:bg-muted hover:text-foreground",
                )}
              >
                <AreaChart className="size-3.5" />
                {t.view.chart}
              </Link>
              <Link
                href={withParams(basePath, query, { view: "table" })}
                aria-current={view === "table" ? "page" : undefined}
                className={cn(
                  "inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors",
                  view === "table"
                    ? "bg-blue-600 text-white"
                    : "text-muted-foreground hover:bg-muted hover:text-foreground",
                )}
              >
                <Table2 className="size-3.5" />
                {t.view.table}
              </Link>
            </div>
          ) : null}

          <Button asChild size="sm" variant="outline">
            <a href={exportHref}>
              <Download className="size-3.5" />
              <span className="hidden sm:inline">{t.export}</span>
            </a>
          </Button>
        </div>
      </div>
    </div>
  );
}

export { DEFAULT_PERIOD, DEFAULT_TAB, DEFAULT_VIEW };
export default ReportToolbar;
