import type { Metadata } from "next";
import { History } from "lucide-react";
import { requireUser } from "@/lib/guards";
import { getModuleSettings } from "@/lib/settings";
import { servicesTexts as tx } from "@/lib/i18n/services";
import { PageHeader } from "@/components/shared/page-header";
import { EmptyState } from "@/components/shared/empty-state";
import {
  UPDATE_TYPES,
  loadServiceUpdates,
  parseUpdateType,
} from "@/components/panel/services/queries";
import {
  Pager,
  UpdatesFilterBar,
  UpdatesTable,
} from "@/components/panel/services/updates-table";

export const dynamic = "force-dynamic";

export const metadata: Metadata = {
  title: "Updates",
};

const BASE_PATH = "/updates";

export default async function UpdatesPage(props: {
  searchParams: Promise<{ page?: string; type?: string }>;
}) {
  await requireUser();
  const searchParams = await props.searchParams;

  const modules = await getModuleSettings();
  if (!modules.updates.enabled) {
    return (
      <>
        <PageHeader title={tx.updatesTitle} description={tx.updatesSubtitle} icon={History} />
        <EmptyState
          icon={History}
          title={tx.updatesDisabledTitle}
          hint={tx.updatesDisabledHint}
        />
      </>
    );
  }

  const type = parseUpdateType(searchParams.type);
  const requestedPage = Number(searchParams.page);
  const { rows, total, page, pages } = await loadServiceUpdates({
    page: Number.isFinite(requestedPage) && requestedPage > 0 ? Math.trunc(requestedPage) : 1,
    type,
  });

  return (
    <>
      <PageHeader
        title={tx.updatesTitle}
        description={tx.updatesSubtitle}
        icon={History}
        actions={
          <span className="font-mono text-xs text-muted-foreground">
            {tx.updatesTotal(total)}
          </span>
        }
      />

      <div className="space-y-4">
        <UpdatesFilterBar basePath={BASE_PATH} active={type} types={UPDATE_TYPES} />

        {rows.length === 0 ? (
          <EmptyState
            icon={History}
            title={tx.updatesEmptyTitle}
            hint={tx.updatesEmptyHint}
          />
        ) : (
          <>
            <UpdatesTable rows={rows} />
            <Pager
              basePath={BASE_PATH}
              page={page}
              pages={pages}
              params={{ type: type ?? undefined }}
            />
          </>
        )}
      </div>
    </>
  );
}
