"use client"

import { Pencil } from "lucide-react"

import {
  getOcrCodeForSlot,
  needsMapping,
  type StructureQueueRow,
} from "@/components/deepdex/utils/structure-underlying-alias"
import {
  accumulatorNeedsMapping,
  getOcrCodeForAccumulator,
  type AccumulatorQueueRow,
} from "@/components/deepdex/utils/accumulator-underlying-alias"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"

import type { ReviewData } from "./deepdex-upload-queue-review-types"

export function renderChildRows(
  title: string,
  rows: Array<{ date?: string; nonCall?: string }> | Array<{ date?: string }>,
) {
  if (!Array.isArray(rows) || rows.length === 0) {
    return <p className="text-sm text-muted-foreground">No {title.toLowerCase()} rows.</p>
  }

  const hasNonCall = rows.some((row) => "nonCall" in row)
  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>Date</TableHead>
          {hasNonCall ? <TableHead>Non-call</TableHead> : null}
        </TableRow>
      </TableHeader>
      <TableBody>
        {rows.map((row, index) => (
          <TableRow key={`${title}-${index}`}>
            <TableCell>{row.date || "—"}</TableCell>
            {hasNonCall ? <TableCell>{"nonCall" in row ? row.nonCall || "—" : "—"}</TableCell> : null}
          </TableRow>
        ))}
      </TableBody>
    </Table>
  )
}

export function renderUnderlyingCell(
  module: string,
  row: StructureQueueRow,
  index: number,
  slot: number,
  onMap: (queueIndex: number, slot: number, row: StructureQueueRow) => void,
) {
  const ocr = getOcrCodeForSlot(row, slot)
  const isin = String(row[`underlying${slot}_isin`] ?? "").trim()
  const name = String(row[`underlying${slot}_name`] ?? "").trim()
  const ccy = String(row[`underlying${slot}_currency`] ?? "").trim()
  const spot = String(row[`underlying${slot}_spot`] ?? "").trim()
  if (!ocr && !isin && !name && !ccy && !spot) {
    return <span className="text-xs text-muted-foreground">—</span>
  }

  return (
    <div className="min-w-[140px] space-y-1 text-[11px] leading-snug">
      {ocr && ocr !== isin ? (
        <span className="inline-block rounded border border-amber-300 bg-amber-50 px-1.5 py-0.5 text-[10px] font-semibold text-amber-800">
          {ocr}
        </span>
      ) : null}
      {isin ? <p className="font-semibold text-slate-800 break-all">{isin}</p> : null}
      {(name || ccy || spot) ? (
        <p className="text-muted-foreground">
          {[name, ccy, spot].filter(Boolean).join(" · ")}
        </p>
      ) : null}
      {module === "structure" && needsMapping(row, slot) ? (
        <Button
          type="button"
          variant="outline"
          size="sm"
          className="h-7 border-amber-300 bg-amber-50 px-2 text-[10px] text-amber-900 hover:bg-amber-100"
          onClick={() => onMap(index, slot, row)}
        >
          Map ISIN
        </Button>
      ) : null}
    </div>
  )
}

export function renderAccumulatorUnderlyingCell(
  row: AccumulatorQueueRow,
  index: number,
  onMap: (queueIndex: number, row: AccumulatorQueueRow) => void,
) {
  const ocr = getOcrCodeForAccumulator(row)
  const isin = String(row.UnderlyingISIN ?? "").trim()
  const name = String(row.UnderlyingName ?? "").trim()
  if (!ocr && !isin && !name) {
    return <span className="text-xs text-muted-foreground">—</span>
  }

  return (
    <div className="min-w-[140px] space-y-1 text-[11px] leading-snug">
      {ocr && ocr !== isin ? (
        <span className="inline-block rounded border border-amber-300 bg-amber-50 px-1.5 py-0.5 text-[10px] font-semibold text-amber-800">
          {ocr}
        </span>
      ) : null}
      {isin ? <p className="font-semibold text-slate-800 break-all">{isin}</p> : null}
      {name ? <p className="text-muted-foreground">{name}</p> : null}
      {accumulatorNeedsMapping(row) ? (
        <Button
          type="button"
          variant="outline"
          size="sm"
          className="h-7 border-amber-300 bg-amber-50 px-2 text-[10px] text-amber-900 hover:bg-amber-100"
          onClick={() => onMap(index, row)}
        >
          Map ISIN
        </Button>
      ) : null}
    </div>
  )
}

export function renderStatusCell(
  module: string,
  row: StructureQueueRow,
  index: number,
  reviewData: ReviewData | null,
  onEdit: (row: Record<string, unknown>, index: number) => void,
  onView: (index: number) => void,
  onRemove: (index: number) => void,
  onAddUnderlying: (row: Record<string, unknown>, index: number) => void,
) {
  const existingInfo = Array.isArray(reviewData?.existingInfo) ? reviewData.existingInfo[index] : null
  const childData = row._child && typeof row._child === "object"
    ? (row._child as { observations?: unknown[]; coupons?: unknown[]; rows?: unknown[] })
    : null
  const obsCount = Array.isArray(childData?.observations) ? childData.observations.length : 0
  const coupCount = Array.isArray(childData?.coupons) ? childData.coupons.length : 0
  const accChildCount = Array.isArray(childData?.rows) ? childData.rows.length : 0
  const docType = String(row._docType ?? "").trim()
  const bankName = String(row._bankName ?? "").trim()

  return (
    <div className="min-w-[12rem] space-y-2">
      <div>
        {existingInfo?.exists ? (
          <Badge variant="secondary">Existing - will update</Badge>
        ) : (
          <Badge variant="outline">New - will create</Badge>
        )}
      </div>
      <div className="flex flex-wrap gap-1">
        {bankName ? <Badge variant="default">{bankName}</Badge> : null}
        {docType ? <Badge variant="secondary">{docType}</Badge> : null}
        <Badge variant="outline">
          {module === "accumulator"
            ? `${accChildCount} child`
            : obsCount > 0 || coupCount > 0
              ? `${obsCount} obs, ${coupCount} coup`
              : "0 child"}
        </Badge>
      </div>
      <div className="flex flex-wrap gap-1">
        <Button variant="outline" size="sm" onClick={() => onEdit(row, index)}>
          <Pencil className="size-3.5" />
          Edit
        </Button>
        <Button variant="outline" size="sm" onClick={() => onView(index)}>
          View all data
        </Button>
        <Button variant="outline" size="sm" onClick={() => onRemove(index)}>
          Remove
        </Button>
        {module === "structure" ? (
          <Button variant="outline" size="sm" onClick={() => onAddUnderlying(row, index)}>
            Add underlying
          </Button>
        ) : null}
      </div>
    </div>
  )
}

export function reviewPageTitle(module: string): string {
  if (module === "accumulator") return "Accumulator Review"
  if (module === "structure") return "Structure Review"
  return "Queue Review"
}
