"use client"

import { useEffect, useState } from "react"

import { bankAccountsApi } from "@/lib/api/general-ledger"
import { salesApi } from "@/lib/api/sales"
import { errorMessage } from "@/lib/error-map"
import { formatAmount } from "@/lib/format"
import { CashAndBankAccountDto } from "@/types/general-ledger"
import { SalesInvoice, SalesInvoicePayment } from "@/types/sales"

import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { toast } from "@/components/ui/toast"

interface SalesInvoicePaymentDialogProps {
  invoice: SalesInvoice | null
  open: boolean
  onOpenChange: (open: boolean) => void
  onPaid: (invoice: SalesInvoice, payment: SalesInvoicePayment) => void
}

/** Record a customer payment against a posted invoice's balance — full or partial, into an
 * existing GL cash/bank account. Modeled on GrnPaymentDialog's "pick an account, submit" shape. */
export function SalesInvoicePaymentDialog({ invoice, open, onOpenChange, onPaid }: SalesInvoicePaymentDialogProps) {
  const [accounts, setAccounts] = useState<CashAndBankAccountDto[] | null>(null)
  const [glBankAccountId, setGlBankAccountId] = useState("")
  const [amount, setAmount] = useState("")
  const [reference, setReference] = useState("")
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

  // Reset the form fields for a fresh open (or a different invoice) during render — same
  // "adjust state while rendering" pattern as GrnPaymentDialog, not inside an effect.
  const openKey = open && invoice ? `${invoice.salesInvoiceId}` : null
  const [resetFor, setResetFor] = useState<string | null>(null)
  if (openKey !== null && resetFor !== openKey) {
    setResetFor(openKey)
    setAmount(invoice!.totals.balanceAmount.toFixed(2))
    setGlBankAccountId("")
    setReference("")
    setErrors({})
  }

  useEffect(() => {
    if (!open || accounts !== null) return
    bankAccountsApi.list("Both").then(setAccounts).catch(() => setAccounts([]))
  }, [open, accounts])

  if (!invoice) return null

  async function submit() {
    if (!invoice) return
    const nextErrors: Record<string, string> = {}
    const amountNum = Number(amount)
    if (!glBankAccountId) nextErrors.glBankAccountId = "Select an account to pay into"
    if (!amount || Number.isNaN(amountNum) || amountNum <= 0) nextErrors.amount = "Enter a valid amount"
    else if (amountNum > invoice.totals.balanceAmount) nextErrors.amount = `Cannot exceed the balance (${formatAmount(invoice.totals.balanceAmount)})`
    setErrors(nextErrors)
    if (Object.keys(nextErrors).length > 0) return

    setSubmitting(true)
    try {
      const payment = await salesApi.payInvoice(invoice.salesInvoiceId, {
        amount: amountNum,
        glBankAccountId: Number(glBankAccountId),
        reference: reference || undefined,
      })
      toast.success("Payment recorded", `${formatAmount(amountNum)} posted to the ledger (${payment.glJournalNo ?? "—"}).`)
      onPaid(invoice, payment)
      onOpenChange(false)
    } catch (err) {
      toast.error("Could not record payment", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Pay invoice {invoice.invoiceNo}</DialogTitle>
        </DialogHeader>

        <p className="text-sm text-muted-foreground">
          Balance due: <span className="font-medium text-foreground tabular-nums">{formatAmount(invoice.totals.balanceAmount)}</span>
        </p>

        <FieldGroup>
          <Field data-invalid={!!errors.glBankAccountId}>
            <FieldLabel htmlFor="inv-pay-account">Pay into</FieldLabel>
            <Select<string> value={glBankAccountId} onValueChange={(v) => setGlBankAccountId(v ?? "")}>
              <SelectTrigger id="inv-pay-account" className="w-full text-base" aria-invalid={!!errors.glBankAccountId}>
                <SelectValue placeholder={accounts === null ? "Loading…" : "Select a cash/bank account"} />
              </SelectTrigger>
              <SelectContent>
                {(accounts ?? []).map((a) => (
                  <SelectItem key={a.accountId} value={String(a.accountId)} label={a.accountName} className="text-base">
                    {a.accountName} ({a.accountType})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <FieldError errors={[errors.glBankAccountId ? { message: errors.glBankAccountId } : undefined]} />
          </Field>

          <Field data-invalid={!!errors.amount}>
            <FieldLabel htmlFor="inv-pay-amount">Amount</FieldLabel>
            <Input
              id="inv-pay-amount"
              type="number"
              step="0.01"
              min="0.01"
              max={invoice.totals.balanceAmount}
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              aria-invalid={!!errors.amount}
            />
            <FieldError errors={[errors.amount ? { message: errors.amount } : undefined]} />
          </Field>

          <Field>
            <FieldLabel htmlFor="inv-pay-reference">Reference (optional)</FieldLabel>
            <Input id="inv-pay-reference" value={reference} onChange={(e) => setReference(e.target.value)} />
          </Field>
        </FieldGroup>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={submitting}>
            Cancel
          </Button>
          <Button onClick={submit} disabled={submitting}>
            {submitting ? "Recording…" : "Record payment"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
