"use client"

import * as React from "react"

import {
  rowHasUnmapped,
  UNDERLYING_SLOTS,
  type StructureQueueRow,
} from "@/components/deepdex/utils/structure-underlying-alias"
import { ACCUMULATOR_TABLE_COLUMNS } from "@/components/deepdex/utils/accumulator-queue-fields"
import { accumulatorRowHasUnmapped, type AccumulatorQueueRow } from "@/components/deepdex/utils/accumulator-underlying-alias"
import {
  XmlApiPaginatedRange,
  XmlApiServerPagination,
} from "@/components/xml-apis/shared/xml-api-server-pagination"
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"

import {
  renderAccumulatorUnderlyingCell,
  renderStatusCell,
  renderUnderlyingCell,
} from "./deepdex-upload-queue-review-cells"
import type { ReviewData } from "./deepdex-upload-queue-review-types"

const PAGE_SIZE_OPTIONS = [10, 20, 50, 100]

export function DeepdexUploadQueueReviewTable({
  module,
  queueRows,
  reviewData,
  onEdit,
  onView,
  onRemove,
  onMapStructure,
  onMapAccumulator,
}: {
  module: string
  queueRows: Array<Record<string, unknown>>
  reviewData: ReviewData | null
  onEdit: (row: Record<string, unknown>, index: number) => void
  onView: (index: number) => void
  onRemove: (index: number) => void
  onMapStructure: (queueIndex: number, slot: number, row: StructureQueueRow) => void
  onMapAccumulator: (queueIndex: number, row: AccumulatorQueueRow) => void
}) {
  const [page, setPage] = React.useState(1)
  const [pageSize, setPageSize] = React.useState(PAGE_SIZE_OPTIONS[0]!)

  const totalCount = queueRows.length
  const pageCount = Math.max(1, Math.ceil(totalCount / pageSize))
  // Removing rows can leave the current page past the end; clamp instead of showing an empty page.
  const currentPage = Math.min(page, pageCount)
  const start = (currentPage - 1) * pageSize
  // Rows keep their absolute queue index so selection, edit, view and remove work across pages.
  const pageRows = React.useMemo(
    () => queueRows.slice(start, start + pageSize).map((row, offset) => ({ row, index: start + offset })),
    [queueRows, start, pageSize],
  )

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base">Review records</CardTitle>
      </CardHeader>
      <CardContent className="overflow-x-auto p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-10">#</TableHead>
              <TableHead className="min-w-[12rem]">Status</TableHead>
              {module === "accumulator"
                ? ACCUMULATOR_TABLE_COLUMNS.map((column) => (
                    <TableHead key={column.key}>{column.label}</TableHead>
                  ))
                : (
                  <>
                    <TableHead>ISIN</TableHead>
                    <TableHead>Name</TableHead>
                    <TableHead>Coupon</TableHead>
                    <TableHead>Expiry</TableHead>
                    <TableHead>Observation</TableHead>
                    <TableHead>KO Barrier</TableHead>
                    <TableHead>KI Barrier</TableHead>
                    <TableHead>Product</TableHead>
                    <TableHead>Non-call</TableHead>
                    <TableHead>Strike</TableHead>
                    <TableHead>Issuer</TableHead>
                    <TableHead>Settlement</TableHead>
                    <TableHead>Trade</TableHead>
                    <TableHead>Final Valuation</TableHead>
                    {UNDERLYING_SLOTS.map((slot) => (
                      <TableHead key={`u-head-${slot}`}>Underlying {slot}</TableHead>
                    ))}
                  </>
                )}
            </TableRow>
          </TableHeader>
          <TableBody>
            {pageRows.map(({ row, index }) => (
              <TableRow
                key={`review-row-${index}`}
                className={
                  (module === "structure" && rowHasUnmapped(row)) ||
                  (module === "accumulator" && accumulatorRowHasUnmapped(row))
                    ? "bg-amber-50/40 dark:bg-amber-950/30"
                    : undefined
                }
              >
                <TableCell>{index + 1}</TableCell>
                <TableCell>
                  {renderStatusCell(
                    module,
                    row as StructureQueueRow,
                    index,
                    reviewData,
                    onEdit,
                    onView,
                    onRemove,
                  )}
                </TableCell>
                {module === "accumulator"
                  ? ACCUMULATOR_TABLE_COLUMNS.map((column) => (
                      <TableCell
                        key={`${column.key}-${index}`}
                        className={column.key === "Name" ? "max-w-[22rem] truncate" : undefined}
                        title={column.key === "Name" ? String(row[column.key] ?? "") : undefined}
                      >
                        {column.key === "UnderlyingISIN"
                          ? renderAccumulatorUnderlyingCell(row as AccumulatorQueueRow, index, onMapAccumulator)
                          : String(row[column.key] ?? "—")}
                      </TableCell>
                    ))
                  : (
                    <>
                      <TableCell>{String(row.ISIN ?? "—")}</TableCell>
                      <TableCell className="max-w-[22rem] truncate" title={String(row.Name ?? "")}>
                        {String(row.Name ?? "—")}
                      </TableCell>
                      <TableCell>{String(row.Coupon ?? "—")}</TableCell>
                      <TableCell>{String(row.Expiry ?? "—")}</TableCell>
                      <TableCell>{String(row.Observations ?? "—")}</TableCell>
                      <TableCell>{String(row.KO_Barrier ?? "—")}</TableCell>
                      <TableCell>{String(row.KI_Barrier ?? "—")}</TableCell>
                      <TableCell>{String(row.Product_Type ?? "—")}</TableCell>
                      <TableCell>{String(row.Non_Call_Period ?? "—")}</TableCell>
                      <TableCell>{String(row.Strike ?? "—")}</TableCell>
                      <TableCell>{String(row.Issuer ?? "—")}</TableCell>
                      <TableCell>{String(row.settlement_date ?? "—")}</TableCell>
                      <TableCell>{String(row.trade_date ?? "—")}</TableCell>
                      <TableCell>{String(row.final_valuation_date ?? "—")}</TableCell>
                      {UNDERLYING_SLOTS.map((slot) => (
                        <TableCell key={`u-cell-${index}-${slot}`}>
                          {renderUnderlyingCell(
                            module,
                            row as StructureQueueRow,
                            index,
                            slot,
                            onMapStructure,
                          )}
                        </TableCell>
                      ))}
                    </>
                  )}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </CardContent>
      <CardFooter className="flex flex-col gap-3 border-t pt-4 sm:flex-row sm:items-center sm:justify-between">
        <XmlApiPaginatedRange page={currentPage} pageSize={pageSize} totalCount={totalCount} />
        <XmlApiServerPagination
          page={currentPage}
          pageSize={pageSize}
          pageCount={pageCount}
          totalCount={totalCount}
          pageSizeOptions={PAGE_SIZE_OPTIONS}
          onPageChange={(next) => setPage(Math.min(Math.max(1, next), pageCount))}
          onPageSizeChange={(size) => {
            setPageSize(size)
            setPage(1)
          }}
        />
      </CardFooter>
    </Card>
  )
}
