import * as React from "react";
import Link from "next/link";
import { ArrowRight, ChevronLeft, ChevronRight } from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { StatusBadge } from "@/components/shared/status-badge";
import { formatDateTime, timeAgo } from "@/lib/format";
import { cn } from "@/lib/utils";
import { servicesTexts as tx } from "@/lib/i18n/services";
import type { ServiceUpdateRowDTO } from "./types";

function href(base: string, params: Record<string, string | number | undefined>): string {
  const search = new URLSearchParams();
  for (const [key, value] of Object.entries(params)) {
    if (value === undefined || value === "" || value === null) continue;
    search.set(key, String(value));
  }
  const qs = search.toString();
  return qs ? `${base}?${qs}` : base;
}

export function UpdatesFilterBar({
  basePath,
  active,
  types,
}: {
  basePath: string;
  active: string | null;
  types: readonly string[];
}) {
  const items: { key: string | null; label: string }[] = [
    { key: null, label: tx.updatesFilterAll },
    ...types.map((type) => ({
      key: type,
      label:
        type === "RATE_UP"
          ? tx.typeRateUp
          : type === "RATE_DOWN"
            ? tx.typeRateDown
            : type === "NEW"
              ? tx.typeNew
              : type === "ENABLED"
                ? tx.typeEnabled
                : tx.typeDisabled,
    })),
  ];

  return (
    <div className="flex flex-wrap items-center gap-1.5">
      {items.map((item) => {
        const isActive = (item.key ?? null) === active;
        return (
          <Link
            key={item.key ?? "all"}
            href={href(basePath, { type: item.key ?? undefined })}
            aria-current={isActive ? "page" : undefined}
            className={cn(
              "inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors",
              isActive
                ? "border-primary bg-primary text-primary-foreground"
                : "border-border bg-card text-muted-foreground hover:bg-muted hover:text-foreground",
            )}
          >
            {item.label}
          </Link>
        );
      })}
    </div>
  );
}

function RateCell({ value, tone }: { value: string | null; tone?: "up" | "down" }) {
  if (!value) {
    return <span className="font-mono text-xs text-muted-foreground">—</span>;
  }
  return (
    <span
      className={cn(
        "font-mono text-sm",
        tone === "up" && "font-semibold text-rose-600 dark:text-rose-400",
        tone === "down" && "font-semibold text-emerald-600 dark:text-emerald-400",
      )}
    >
      {value}
    </span>
  );
}

export function UpdatesTable({ rows }: { rows: ServiceUpdateRowDTO[] }) {
  return (
    <div className="overflow-hidden rounded-2xl border bg-card shadow-sm">
      <Table className="[&_td]:px-3 [&_td]:py-3 [&_td:first-child]:pl-5 [&_td:last-child]:pr-5 [&_th]:px-3 [&_th]:text-xs [&_th]:font-medium [&_th]:text-muted-foreground [&_th:first-child]:pl-5 [&_th:last-child]:pr-5">
        <TableHeader>
          <TableRow className="hover:bg-transparent">
            <TableHead className="min-w-[150px]">{tx.updatesColDate}</TableHead>
            <TableHead className="min-w-[240px]">{tx.updatesColService}</TableHead>
            <TableHead className="w-32">{tx.updatesColType}</TableHead>
            <TableHead className="text-right whitespace-nowrap">
              {tx.updatesColOldRate}
            </TableHead>
            <TableHead className="w-8" />
            <TableHead className="text-right whitespace-nowrap">
              {tx.updatesColNewRate}
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {rows.map((row) => (
            <TableRow key={row.id}>
              <TableCell className="align-top">
                <div className="text-sm whitespace-nowrap">
                  {formatDateTime(row.createdAt)}
                </div>
                <div className="text-xs text-muted-foreground">
                  {timeAgo(row.createdAt)}
                </div>
              </TableCell>

              <TableCell className="align-top">
                <Link
                  href={`/?service=${row.serviceId}`}
                  className="font-medium transition-colors hover:text-primary"
                >
                  {row.serviceName}
                </Link>
                <div className="mt-0.5 text-xs text-muted-foreground">
                  <span className="font-mono">#{row.serviceId}</span>
                  {row.categoryName ? ` · ${row.categoryName}` : null}
                </div>
              </TableCell>

              <TableCell className="align-top">
                <StatusBadge status={row.type} label={row.typeLabel} />
              </TableCell>

              <TableCell className="text-right align-top">
                <RateCell value={row.oldRate} />
              </TableCell>

              <TableCell className="px-0! text-center align-top">
                <ArrowRight className="mx-auto size-3.5 text-muted-foreground/60" />
              </TableCell>

              <TableCell className="text-right align-top">
                <RateCell
                  value={row.newRate}
                  tone={
                    row.type === "RATE_UP"
                      ? "up"
                      : row.type === "RATE_DOWN"
                        ? "down"
                        : undefined
                  }
                />
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
}

export function Pager({
  basePath,
  page,
  pages,
  params,
}: {
  basePath: string;
  page: number;
  pages: number;
  params?: Record<string, string | number | undefined>;
}) {
  if (pages <= 1) return null;
  const rest = params ?? {};

  return (
    <div className="flex items-center justify-between gap-3">
      {page > 1 ? (
        <Button asChild variant="outline" size="lg">
          <Link
            href={href(basePath, {
              ...rest,
              page: page - 1 > 1 ? page - 1 : undefined,
            })}
          >
            <ChevronLeft className="size-4" />
            {tx.pagerPrevious}
          </Link>
        </Button>
      ) : (
        <Button variant="outline" size="lg" disabled>
          <ChevronLeft className="size-4" />
          {tx.pagerPrevious}
        </Button>
      )}

      <span className="font-mono text-xs text-muted-foreground">
        {tx.pagerPage(page, pages)}
      </span>

      {page < pages ? (
        <Button asChild variant="outline" size="lg">
          <Link href={href(basePath, { ...rest, page: page + 1 })}>
            {tx.pagerNext}
            <ChevronRight className="size-4" />
          </Link>
        </Button>
      ) : (
        <Button variant="outline" size="lg" disabled>
          {tx.pagerNext}
          <ChevronRight className="size-4" />
        </Button>
      )}
    </div>
  );
}
