"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { Loader2 } from "lucide-react"
import { toast } from "sonner"

import { createUploadXmlCompareTransactionFile } from "@/components/xml-apis/upload-xml/api/upload-xml.api"
import {
  openCompareTransactionFile,
  type CompareTransactionFileMode,
} from "@/components/xml-apis/upload-xml/_lib/compare-transaction-file"

const MODES: Record<CompareTransactionFileMode, { label: string; title: string; className: string }> = {
  import: {
    label: "Import XML View",
    title: "Make the bank's own transaction file from these saved rows, add it to Upload XML (Compare transactions tab) and open it",
    className: "border border-emerald-600 bg-emerald-600 text-white hover:bg-emerald-700",
  },
  commonRules: {
    label: "Common Rules",
    title: "Make the same transaction file (kept in Upload XML, Compare transactions tab) and open it with the common detection rules (bonds, structures, funds, cash, equity) applied",
    className: "border border-sky-600 text-sky-800 hover:bg-sky-50 hover:text-sky-900 dark:text-sky-300 dark:hover:bg-sky-950",
  },
}

/**
 * "Import XML View" and "Common Rules" on the Compare POS history page: both make the bank's own transaction file
 * from the saved Buy / Sell / Partial rows (one file per POS upload, so the second click reuses the first), keep it in
 * Upload XML (the "Compare transactions" tab) and open it: plain, or with the common detection rules applied.
 */
export function CreateTransactionFileButton({ uploadId, mode = "import" }: { uploadId: string; mode?: CompareTransactionFileMode }) {
  const router = useRouter()
  const [busy, setBusy] = React.useState(false)
  const [error, setError] = React.useState<string | null>(null)
  const { label, title, className } = MODES[mode]

  const handleClick = async () => {
    if (busy) return
    setBusy(true)
    setError(null)
    const outcome = await openCompareTransactionFile(uploadId, mode, {
      create: createUploadXmlCompareTransactionFile,
      notify: (message) => toast.success(message),
      navigate: (href) => router.push(href),
    })
    if (!outcome.ok) setError(outcome.message)
    setBusy(false)
  }

  return (
    <div className="flex flex-col items-end gap-1">
      <button
        type="button"
        onClick={() => void handleClick()}
        disabled={busy}
        className={`inline-flex h-8 items-center gap-1.5 rounded-md px-3 text-xs font-medium disabled:opacity-70 ${className}`}
        title={title}
      >
        {busy ? <Loader2 className="size-3.5 animate-spin" /> : null}
        {label}
      </button>
      {error ? (
        <span role="alert" className="max-w-xs text-right text-[11px] text-destructive">
          {error}
        </span>
      ) : null}
    </div>
  )
}
