"use client"

import { AlertTriangle, CheckCircle2 } from "lucide-react"

import type { RowValidation } from "@/components/deepdex/deepdex-upload-queue-review-types"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { reviewRowLabel, summarizeValidation } from "@/components/deepdex/utils/review-validation"

/**
 * Why the structures below were not published automatically. Shows the validation rules re-run on the rows as they
 * stand, and is refreshed after each edit or underlying mapping.
 */
export function DeepdexUploadQueueReviewValidation({
  queueRows,
  validation,
}: {
  queueRows: Array<Record<string, unknown>>
  validation: RowValidation[] | undefined
}) {
  const summary = summarizeValidation(validation)
  if (!summary) return null
  const { flagged, failing, total } = summary

  if (flagged.length === 0) {
    return (
      <Alert>
        <CheckCircle2 />
        <AlertTitle>All automatic checks pass</AlertTitle>
        <AlertDescription>
          ISIN, final valuation date, strike, spot prices and the observation / coupon schedule are consistent.
        </AlertDescription>
      </Alert>
    )
  }

  return (
    <Alert variant={failing > 0 ? "destructive" : "default"}>
      <AlertTriangle />
      <AlertTitle>
        {failing > 0
          ? `${failing} of ${total} row${total === 1 ? "" : "s"} need${failing === 1 ? "s" : ""} a manual check`
          : "Automatic checks passed with notes"}
      </AlertTitle>
      <AlertDescription>
        <ul className="mt-1 space-y-2">
          {flagged.map(({ result, index }) => (
            <li key={index}>
              <p className="font-medium">{reviewRowLabel(queueRows[index], index)}</p>
              <ul className="list-disc space-y-0.5 pl-5">
                {result.errors.map((issue, i) => (
                  <li key={`e-${issue.code}-${i}`}>{issue.message}</li>
                ))}
                {result.warnings.map((issue, i) => (
                  <li key={`w-${issue.code}-${i}`} className="text-muted-foreground">
                    {issue.message}
                  </li>
                ))}
              </ul>
            </li>
          ))}
        </ul>
      </AlertDescription>
    </Alert>
  )
}
