import { clampPageNumber, clampPageSize } from "@/config/pagination"
import { FRONTEND_ROUTES } from "@/config/frontend-routes"
import Link from "next/link"

import { fetchBackendPosCompareHistory } from "./_lib/pos-compare-history-server-api"

type PageProps = {
  searchParams: Promise<{
    page?: string
    page_size?: string
    upload_id?: string
    pos_id?: string
    status?: string
  }>
}

function StatusBadge({ status }: { status: string }) {
  const normalized = status.toLowerCase()
  const className =
    normalized === "new"
      ? "bg-emerald-100 text-emerald-800"
      : normalized === "removed"
        ? "bg-red-100 text-red-800"
        : normalized === "changed"
          ? "bg-amber-100 text-amber-800"
          : "bg-slate-100 text-slate-700"

  return (
    <span className={`inline-flex rounded-full px-2 py-0.5 text-[11px] font-semibold ${className}`}>
      {status || "—"}
    </span>
  )
}

export default async function PosCompareHistoryPage({ searchParams }: PageProps) {
  const params = await searchParams
  const page = clampPageNumber(params.page)
  const pageSize = clampPageSize(params.page_size, 50)
  const uploadId = params.upload_id?.trim() ?? ""
  const posId = params.pos_id?.trim() ?? ""
  const status = params.status?.trim() ?? ""

  const result = await fetchBackendPosCompareHistory({
    page,
    pageSize,
    uploadId,
    posId,
    status,
  })

  return (
    <div className="space-y-4 p-4 lg:p-6">
      <div className="flex flex-wrap items-end justify-between gap-3">
        <div>
          <h1 className="text-xl font-semibold tracking-tight">
            POS Compare History (New / Removed / Changed)
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Saved New, Removed and Changed rows from Compare POS
            {uploadId ? ` for upload #${uploadId}` : ""}.
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          {uploadId ? (
            <Link
              href={FRONTEND_ROUTES.xmlApis.uploadXml.importCompareHistoryView(
                uploadId,
                {
                  status: "all",
                  posId: posId || undefined,
                }
              )}
              className="inline-flex h-8 items-center rounded-md border border-emerald-600 bg-emerald-600 px-3 text-xs font-medium text-white hover:bg-emerald-700"
              title="Open the same POS XML import view with New and Removed history rows together"
              target="_blank"
            >
              Import XML View
            </Link>
          ) : null}
          {uploadId ? (
            <Link
              href={FRONTEND_ROUTES.xmlApis.uploadXml.importCompareHistoryView(
                uploadId,
                {
                  status: "all",
                  posId: posId || undefined,
                  commonRules: true,
                }
              )}
              className="inline-flex h-8 items-center rounded-md border border-sky-600 px-3 text-xs font-medium text-sky-800 hover:bg-sky-50 hover:text-sky-900 dark:text-sky-300 dark:hover:bg-sky-950"
              title="Open the same New and Removed history rows with the common detection rules (bonds, structures, funds, cash, equity) applied"
              target="_blank"
            >
              Common Rules
            </Link>
          ) : null}
          <Link
            href={FRONTEND_ROUTES.xmlApis.posCompareHistory.page}
            className="inline-flex h-8 items-center rounded-md border px-3 text-xs font-medium hover:bg-muted"
          >
            Clear filters
          </Link>
        </div>
      </div>

      {result.errorMessage ? (
        <div className="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-3 text-sm text-destructive">
          {result.errorMessage}
        </div>
      ) : null}

      <div className="overflow-auto rounded-md border">
        <table className="w-full border-collapse text-xs">
          <thead className="bg-muted">
            <tr>
              <th className="border px-2 py-1.5 text-left font-semibold">POS ID</th>
              <th className="border px-2 py-1.5 text-left font-semibold">Status</th>
              <th className="border px-2 py-1.5 text-left font-semibold">Source</th>
              <th className="border px-2 py-1.5 text-left font-semibold">Bank</th>
              <th className="border px-2 py-1.5 text-left font-semibold">Upload</th>
              <th className="border px-2 py-1.5 text-left font-semibold">Today</th>
              <th className="border px-2 py-1.5 text-left font-semibold">Yesterday</th>
              <th className="border px-2 py-1.5 text-left font-semibold">Match Key</th>
              <th className="border px-2 py-1.5 text-left font-semibold">Value</th>
              <th className="border px-2 py-1.5 text-left font-semibold">Row</th>
              <th className="border px-2 py-1.5 text-left font-semibold">Saved At</th>
            </tr>
          </thead>
          <tbody>
            {result.items.length === 0 ? (
              <tr>
                <td colSpan={11} className="border px-2 py-8 text-center text-muted-foreground">
                  No saved New/Removed/Changed history yet.
                </td>
              </tr>
            ) : (
              result.items.map((row) => (
                <tr key={row.id} className="align-top">
                  <td className="border px-2 py-1.5 font-semibold">
                    {row.posId ? (
                      <Link
                        href={`${FRONTEND_ROUTES.xmlApis.posCompareHistory.page}?pos_id=${encodeURIComponent(row.posId)}`}
                        className="text-violet-700 underline-offset-2 hover:underline"
                      >
                        {row.posId}
                      </Link>
                    ) : (
                      "—"
                    )}
                  </td>
                  <td className="border px-2 py-1.5">
                    <StatusBadge status={row.status} />
                  </td>
                  <td className="border px-2 py-1.5">{row.source || "—"}</td>
                  <td className="border px-2 py-1.5">{row.bankName || row.bankApiId || "—"}</td>
                  <td className="border px-2 py-1.5">
                    {row.uploadId ? (
                      <Link
                        href={FRONTEND_ROUTES.xmlApis.uploadXml.importView(row.uploadId)}
                        className="underline-offset-2 hover:underline"
                        target="_blank"
                      >
                        {row.uploadTitle || row.uploadId}
                      </Link>
                    ) : (
                      "—"
                    )}
                  </td>
                  <td className="border px-2 py-1.5">{row.todayDate || "—"}</td>
                  <td className="border px-2 py-1.5">{row.yesterdayDate || "—"}</td>
                  <td className="max-w-[280px] break-words border px-2 py-1.5">
                    {row.matchKey || "—"}
                  </td>
                  <td className="border px-2 py-1.5">
                    {row.valueField ? `${row.valueField}: ${row.value}` : row.value || "—"}
                  </td>
                  <td className="border px-2 py-1.5">{row.rowLabel || "—"}</td>
                  <td className="border px-2 py-1.5">{row.dateAdded || "—"}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      <div className="text-xs text-muted-foreground">
        Showing {result.items.length} of {result.totalCount} · page {result.page}/
        {Math.max(result.pageCount, 1)}
      </div>
    </div>
  )
}
