import type { Metadata } from "next";
import Link from "next/link";
import { Prisma, RefillStatus } from "@prisma/client";
import { RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { EmptyState } from "@/components/shared/empty-state";
import { PageHeader } from "@/components/shared/page-header";
import { PaginationBar } from "@/components/panel/orders/pagination-bar";
import { RefillTable } from "@/components/panel/orders/refill-table";
import { TabLinks, type TabItem } from "@/components/panel/orders/tab-links";
import { TableCard } from "@/components/panel/orders/table-card";
import { readPage, readParam } from "@/components/panel/orders/query";
import type { RefillRow } from "@/components/panel/orders/types";
import { db } from "@/lib/db";
import { requireUser } from "@/lib/guards";
import { iso } from "@/lib/serialize";
import { ordersTexts } from "@/lib/i18n/orders";

export const dynamic = "force-dynamic";

export const metadata: Metadata = { title: "Refill" };

const PATHNAME = "/refill";
const PER_PAGE = 20;

type RefillTab = { value: string; label: string; statuses: RefillStatus[] | null };

const REFILL_TABS: RefillTab[] = [
  { value: "", label: ordersTexts.tabAll, statuses: null },
  {
    value: "pending",
    label: ordersTexts.refillStatusPending,
    statuses: [RefillStatus.PENDING],
  },
  {
    value: "in-progress",
    label: ordersTexts.refillStatusInProgress,
    statuses: [RefillStatus.IN_PROGRESS],
  },
  {
    value: "completed",
    label: ordersTexts.refillStatusCompleted,
    statuses: [RefillStatus.COMPLETED],
  },
  {
    value: "rejected",
    label: ordersTexts.refillStatusRejected,
    statuses: [RefillStatus.REJECTED],
  },
  { value: "error", label: ordersTexts.refillStatusError, statuses: [RefillStatus.ERROR] },
];

function shortId(id: string): string {
  return id.length <= 10 ? id : `…${id.slice(-8)}`;
}

export default async function RefillPage(props: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const searchParams = await props.searchParams;
  const user = await requireUser();

  const statusParam = readParam(searchParams.status).toLowerCase();
  const activeTab = REFILL_TABS.find((t) => t.value === statusParam) ?? REFILL_TABS[0];
  const requestedPage = readPage(searchParams.page);
  const params = { status: activeTab.value || undefined };

  const baseWhere: Prisma.RefillWhereInput = { userId: user.id };
  const where: Prisma.RefillWhereInput = activeTab.statuses
    ? { ...baseWhere, status: { in: activeTab.statuses } }
    : baseWhere;

  const [total, grouped] = await Promise.all([
    db.refill.count({ where }),
    db.refill.groupBy({ by: ["status"], where: baseWhere, _count: { _all: true } }),
  ]);

  const countByStatus = new Map<string, number>(
    grouped.map((g) => [g.status as string, g._count._all]),
  );
  const totalAll = grouped.reduce((sum, g) => sum + g._count._all, 0);

  const pages = Math.max(1, Math.ceil(total / PER_PAGE));
  const page = Math.min(requestedPage, pages);

  const refills = await db.refill.findMany({
    where,
    orderBy: { createdAt: "desc" },
    skip: (page - 1) * PER_PAGE,
    take: PER_PAGE,
    select: {
      id: true,
      createdAt: true,
      status: true,
      reason: true,
      orderId: true,
      order: {
        select: {
          serviceId: true,
          service: { select: { id: true, name: true } },
        },
      },
    },
  });

  const rows: RefillRow[] = refills.map((refill) => ({
    id: refill.id,
    shortId: shortId(refill.id),
    createdAt: iso(refill.createdAt),
    orderId: refill.orderId,
    serviceId: refill.order?.service?.id ?? refill.order?.serviceId ?? 0,
    serviceName: refill.order?.service?.name ?? "—",
    status: refill.status,
    reason: refill.reason ?? null,
  }));

  const tabs: TabItem[] = REFILL_TABS.map((tab) => ({
    value: tab.value,
    label: tab.label,
    count: tab.statuses
      ? tab.statuses.reduce((sum, s) => sum + (countByStatus.get(s) ?? 0), 0)
      : totalAll,
  }));

  return (
    <div className="space-y-6">
      <PageHeader
        title={ordersTexts.refillTitle}
        description={ordersTexts.refillSubtitle}
        icon={RotateCcw}
      />

      <TableCard
        toolbar={
          <TabLinks
            pathname={PATHNAME}
            params={params}
            active={activeTab.value}
            tabs={tabs}
          />
        }
        footer={
          rows.length ? (
            <PaginationBar
              pathname={PATHNAME}
              params={params}
              page={page}
              perPage={PER_PAGE}
              total={total}
            />
          ) : null
        }
      >
        {rows.length ? (
          <RefillTable rows={rows} />
        ) : (
          <EmptyState
            className="m-4 border-0"
            icon={RotateCcw}
            title={ordersTexts.refillEmptyTitle}
            hint={ordersTexts.refillEmptyHint}
            action={
              <Button asChild size="sm" className="rounded-lg">
                <Link href="/orders">{ordersTexts.refillEmptyCta}</Link>
              </Button>
            }
          />
        )}
      </TableCard>
    </div>
  );
}
