'use client'

import { useEffect, useMemo, useState } from 'react'
import type { FormEvent } from 'react'
import { toast } from 'sonner'
import {
  AlertTriangle,
  Banknote,
  CheckCircle2,
  FileText,
  Link2,
  Loader2,
  Printer,
  Receipt,
  RefreshCcw,
  Scale,
  Send,
  ShieldCheck,
  Undo2,
} from 'lucide-react'
import { PageHeader } from '@/components/ui/page-header'
import { SectionCard } from '@/components/ui/section-card'
import { KpiCard } from '@/components/ui/kpi-card'
import { DataTable, type Column } from '@/components/ui/data-table'
import { StatusBadge, type StatusTone } from '@/components/ui/status-badge'
import { Button } from '@/components/ui/button'
import { Modal } from '@/components/ui/modal'
import { InputField, SelectField, TextAreaField } from '@/components/ui/FormFields'
import { formatDateTime, formatNumber } from '@/lib/format'
import { useAuth } from '@/contexts/auth-context'
import i18n from '@/lib/i18n'
import {
  PaymentCreatePayload,
  PaymentType,
  Reconciliation,
  Settlement,
  SprintPayment,
  useSprintPayments,
  useSprintReconciliations,
  useSprintSettlements,
  Voucher,
} from '@/hooks/useSprint9Finance'

const statusTone: Record<string, StatusTone> = {
  draft: 'neutral',
  pending: 'warning',
  approved: 'info',
  posted: 'success',
  cancelled: 'danger',
  refunded: 'danger',
  full: 'success',
  partial: 'warning',
  reversed: 'danger',
  in_progress: 'warning',
  reconciled: 'success',
  discrepancy: 'danger',
}

const t = (key: string, options?: Record<string, unknown>) => i18n.t(`components.finance.payment_operations.${key}`, options)

function money(amount: unknown, currencyId?: string | null) {
  return `${formatNumber(Number(amount || 0))} ${currencyId ? shortId(currencyId) : ''}`.trim()
}

function shortId(value?: string | null) {
  if (!value) return '-'
  return value.length > 12 ? `${value.slice(0, 8)}...` : value
}

function partyLabel(payment: SprintPayment) {
  const type = payment.payment_type === 'inbound' ? payment.payer_type : payment.payee_type
  const id = payment.payment_type === 'inbound' ? payment.payer_id : payment.payee_id
  return `${type || 'platform'}${id ? ` / ${shortId(id)}` : ''}`
}

function settlementLabel(payment: SprintPayment, settlements: Settlement[]) {
  const rows = settlements.filter((s) => s.payment_id === payment.id && s.status !== 'cancelled' && s.status !== 'reversed')
  const applied = rows.reduce((sum, row) => sum + Number(row.total_applied || 0), 0)
  if (applied <= 0) return t('settlement.unallocated')
  if (applied < Number(payment.amount || 0)) return t('settlement.partial')
  return t('settlement.settled')
}

function printVoucher(payment: SprintPayment, voucher: Voucher | null, title: string) {
  const win = window.open('', '_blank', 'width=900,height=1100')
  if (!win) {
    toast.error(t('toast.popup_blocked'))
    return
  }

  const html = `
    <html>
      <head>
        <title>${voucher?.voucher_no || payment.payment_no}</title>
        <style>
          body { font-family: Arial, sans-serif; margin: 40px; color: #111827; }
          .top { display: flex; justify-content: space-between; border-bottom: 2px solid #c9a227; padding-bottom: 18px; margin-bottom: 28px; }
          h1 { margin: 0; font-size: 26px; }
          .brand { font-size: 18px; font-weight: 700; color: #8a6d12; }
          table { width: 100%; border-collapse: collapse; margin-top: 16px; }
          td { border: 1px solid #d1d5db; padding: 10px; font-size: 14px; }
          td:first-child { background: #f9fafb; width: 32%; font-weight: 700; }
          .signatures { display: grid; grid-template-columns: repeat(3, 1fr); gap: 22px; margin-top: 70px; }
          .sig { border-top: 1px solid #111827; padding-top: 8px; text-align: center; font-size: 13px; }
          @media print { button { display: none; } body { margin: 20px; } }
        </style>
      </head>
      <body>
        <button onclick="window.print()">${t('action.print')}</button>
        <div class="top">
          <div>
            <div class="brand">Gold Wallet</div>
            <h1>${title}</h1>
          </div>
          <div>
            <div><strong>${t('field.voucher')}:</strong> ${voucher?.voucher_no || '-'}</div>
            <div><strong>${t('field.payment')}:</strong> ${payment.payment_no}</div>
          </div>
        </div>
        <table>
          <tr><td>${t('field.date')}</td><td>${voucher?.issued_at || payment.approved_at || payment.created_at || '-'}</td></tr>
          <tr><td>${t('field.party')}</td><td>${partyLabel(payment)}</td></tr>
          <tr><td>${t('field.amount')}</td><td>${money(payment.amount, payment.currency_id)}</td></tr>
          <tr><td>${t('field.payment_method')}</td><td>${payment.payment_method}</td></tr>
          <tr><td>${t('field.reference')}</td><td>${payment.reference || '-'}</td></tr>
          <tr><td>${t('field.status')}</td><td>${voucher?.status || payment.status}</td></tr>
          <tr><td>${t('field.created_by')}</td><td>${shortId(payment.created_by)}</td></tr>
          <tr><td>${t('field.approved_by')}</td><td>${shortId(payment.approved_by)}</td></tr>
          <tr><td>${t('field.notes')}</td><td>${payment.notes || payment.description || '-'}</td></tr>
        </table>
        <div class="signatures">
          <div class="sig">${t('signature.receiver')}</div>
          <div class="sig">${t('signature.accountant')}</div>
          <div class="sig">${t('signature.manager')}</div>
        </div>
      </body>
    </html>`

  win.document.open()
  win.document.write(html)
  win.document.close()
  win.focus()
  toast.success(t('toast.print_opened'))
}

function Status({ value }: { value: string }) {
  return <StatusBadge tone={statusTone[value] || 'neutral'}>{t(`status.${value}`)}</StatusBadge>
}

function useFinanceAccess() {
  const { user } = useAuth()
  const role = String(user?.role || '').toLowerCase()
  const roles = new Set([role, ...(user?.roles || []).map((r) => String(r.code || '').toLowerCase())])
  const permissions = new Set(user?.permissions || [])
  const manager = roles.has('super_admin') || roles.has('finance_admin') || roles.has('finance_manager')
  return {
    canCreate: manager || permissions.has('payment:create'),
    canUpdate: manager || permissions.has('payment:update'),
    canApprove: manager || permissions.has('payment:approve'),
    canPost: manager || permissions.has('payment:post'),
  }
}

type VoucherPageProps = {
  type: PaymentType
}

export function VoucherPage({ type }: VoucherPageProps) {
  const isReceipt = type === 'inbound'
  const access = useFinanceAccess()
  const payments = useSprintPayments()
  const settlements = useSprintSettlements()
  const [selected, setSelected] = useState<SprintPayment | null>(null)
  const [voucher, setVoucher] = useState<Voucher | null>(null)
  const [createOpen, setCreateOpen] = useState(false)
  const [note, setNote] = useState('')
  const [reason, setReason] = useState('')
  const [busy, setBusy] = useState(false)
  const [statusFilter, setStatusFilter] = useState('')
  const [methodFilter, setMethodFilter] = useState('')
  const [currencyFilter, setCurrencyFilter] = useState('')
  const [partyFilter, setPartyFilter] = useState('')
  const [fromDate, setFromDate] = useState('')
  const [toDate, setToDate] = useState('')
  const [form, setForm] = useState<PaymentCreatePayload>({
    payment_type: type,
    payment_method: 'cash',
    amount: 0,
    currency_id: '',
    exchange_rate: 1,
    reference: '',
    payer_type: isReceipt ? 'customer' : 'platform',
    payee_type: isReceipt ? 'platform' : 'supplier',
    payer_id: '',
    payee_id: '',
    description: '',
    notes: '',
  })

  const reload = async () => {
    await Promise.all([
      payments.fetchPayments({ payment_type: type }),
      settlements.fetchSettlements(),
    ])
  }

  useEffect(() => {
    reload()
  }, [type])

  const rows = payments.items.filter((payment) => {
    const created = String(payment.created_at || payment.approved_at || '')
    const party = partyLabel(payment).toLowerCase()
    if (statusFilter && payment.status !== statusFilter) return false
    if (methodFilter && payment.payment_method !== methodFilter) return false
    if (currencyFilter && payment.currency_id !== currencyFilter) return false
    if (partyFilter && !party.includes(partyFilter.toLowerCase())) return false
    if (fromDate && created.slice(0, 10) < fromDate) return false
    if (toDate && created.slice(0, 10) > toDate) return false
    return true
  })

  const totals = useMemo(() => ({
    draft: rows.filter((p) => p.status === 'draft').length,
    approved: rows.filter((p) => p.status === 'approved').length,
    posted: rows.filter((p) => p.status === 'posted').length,
    amount: rows.reduce((sum, p) => sum + Number(p.amount || 0), 0),
  }), [rows])

  const openVoucher = async (payment: SprintPayment) => {
    setSelected(payment)
    if (payment.status === 'posted') {
      try {
        setVoucher(await payments.fetchVoucher(payment))
      } catch {
        setVoucher(null)
      }
    } else {
      setVoucher(null)
    }
  }

  const run = async (fn: () => Promise<unknown>, message: string) => {
    setBusy(true)
    try {
      await fn()
      toast.success(message)
      setNote('')
      setReason('')
      await reload()
    } finally {
      setBusy(false)
    }
  }

  const createPayment = async (event: FormEvent) => {
    event.preventDefault()
    if (!form.currency_id || Number(form.amount) <= 0) {
      toast.error(t('validation.currency_amount_required'))
      return
    }
    setBusy(true)
    try {
      const payload = { ...form, payment_type: type }
      if (!payload.payer_id) payload.payer_id = null
      if (!payload.payee_id) payload.payee_id = null
      await payments.createPayment(payload)
      toast.success(isReceipt ? t('toast.receipt_created') : t('toast.payment_created'))
      setCreateOpen(false)
      await reload()
    } finally {
      setBusy(false)
    }
  }

  const columns: Column<SprintPayment>[] = [
    { key: 'no', header: t('table.voucher_payment'), cell: (p) => <button className="font-mono text-xs font-semibold hover:text-gold-700" onClick={() => openVoucher(p)}>{p.payment_no}</button> },
    { key: 'date', header: t('field.date'), cell: (p) => <span className="text-xs text-muted-foreground">{formatDateTime(p.approved_at || p.created_at || '')}</span> },
    { key: 'party', header: t('field.party'), cell: (p) => <span>{partyLabel(p)}</span> },
    { key: 'method', header: t('field.method'), cell: (p) => <span className="capitalize">{p.payment_method.replace('_', ' ')}</span> },
    { key: 'amount', header: t('field.amount'), cell: (p) => <span className="font-mono font-semibold">{money(p.amount, p.currency_id)}</span> },
    { key: 'status', header: t('field.status'), cell: (p) => <Status value={p.status} /> },
    { key: 'settlement', header: t('field.settlement'), cell: (p) => settlementLabel(p, settlements.items) },
    { key: 'recon', header: t('field.reconciliation'), cell: (p) => p.reconciliation_id ? <Status value="reconciled" /> : t('status.unmatched') },
    {
      key: 'actions',
      header: t('field.actions'),
      cell: (p) => (
        <div className="flex flex-wrap gap-1">
          {p.status === 'draft' && access.canUpdate && <Button size="sm" variant="outline" onClick={() => run(() => payments.submitPayment(p.id), t('toast.submitted'))}><Send className="h-3.5 w-3.5" />{t('action.submit')}</Button>}
          {p.status === 'pending' && access.canApprove && <Button size="sm" variant="outline" onClick={() => run(() => payments.approvePayment(p.id), t('toast.approved'))}><CheckCircle2 className="h-3.5 w-3.5" />{t('action.approve')}</Button>}
          {p.status === 'approved' && access.canPost && <Button size="sm" onClick={() => run(() => payments.postPayment(p.id), t('toast.posted'))}><ShieldCheck className="h-3.5 w-3.5" />{t('action.post')}</Button>}
          {p.status === 'posted' && <Button size="sm" variant="outline" onClick={async () => { const v = await payments.fetchVoucher(p); printVoucher(p, v, isReceipt ? t('title.receipt_voucher_single') : t('title.payment_voucher_single')) }}><Printer className="h-3.5 w-3.5" />{t('action.print')}</Button>}
          {p.posting_journal_id && <Button size="sm" variant="ghost" onClick={() => window.location.assign(`/ledger?journal=${p.posting_journal_id}`)}><FileText className="h-3.5 w-3.5" />{t('action.journal')}</Button>}
        </div>
      ),
    },
  ]

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <PageHeader
          title={isReceipt ? t('title.receipt_vouchers') : t('title.payment_vouchers')}
          description={isReceipt ? t('description.receipt_vouchers') : t('description.payment_vouchers')}
        />
        {access.canCreate && <Button onClick={() => setCreateOpen(true)}><Receipt className="h-4 w-4" />{isReceipt ? t('action.create_receipt') : t('action.create_payment')}</Button>}
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <KpiCard label={t('status.draft')} value={String(totals.draft)} icon={Receipt} />
        <KpiCard label={t('status.approved')} value={String(totals.approved)} icon={CheckCircle2} tone="info" />
        <KpiCard label={t('status.posted')} value={String(totals.posted)} icon={ShieldCheck} tone="success" />
        <KpiCard label={t('kpi.total')} value={formatNumber(totals.amount)} icon={Banknote} tone="gold" />
      </div>

      {!isReceipt && (
        <div className="rounded-md border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
          {t('warning.outbound')}
        </div>
      )}

      <SectionCard title={t('section.filters')}>
        <div className="grid gap-3 md:grid-cols-3 lg:grid-cols-6">
          <InputField label={t('field.from')} id="from_date" name="from_date" type="date" value={fromDate} onChange={(e) => setFromDate(e.target.value)} />
          <InputField label={t('field.to')} id="to_date" name="to_date" type="date" value={toDate} onChange={(e) => setToDate(e.target.value)} />
          <InputField label={t('field.party')} id="party_filter" name="party_filter" value={partyFilter} onChange={(e) => setPartyFilter(e.target.value)} />
          <InputField label={t('field.currency_id')} id="currency_filter" name="currency_filter" value={currencyFilter} onChange={(e) => setCurrencyFilter(e.target.value)} />
          <SelectField label={t('field.status')} id="status_filter" name="status_filter" value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)} options={[
            { value: 'draft', label: t('status.draft') },
            { value: 'pending', label: t('status.pending') },
            { value: 'approved', label: t('status.approved') },
            { value: 'posted', label: t('status.posted') },
            { value: 'cancelled', label: t('status.cancelled') },
            { value: 'refunded', label: t('status.refunded') },
          ]} />
          <SelectField label={t('field.method')} id="method_filter" name="method_filter" value={methodFilter} onChange={(e) => setMethodFilter(e.target.value)} options={[
            { value: 'cash', label: t('method.cash') },
            { value: 'bank_transfer', label: t('method.bank_transfer') },
            { value: 'wallet', label: t('method.wallet') },
          ]} />
        </div>
      </SectionCard>

      <SectionCard title={isReceipt ? t('section.receipt_register') : t('section.payment_register')} padded={false}>
        {payments.isLoading ? <div className="flex justify-center py-10"><Loader2 className="h-6 w-6 animate-spin" /></div> : <DataTable columns={columns} data={rows} rowKey={(p) => p.id} />}
      </SectionCard>

      {payments.error && <p className="text-sm text-destructive">{payments.error}</p>}

      <Modal open={createOpen} onClose={() => setCreateOpen(false)} title={isReceipt ? t('title.create_receipt') : t('title.create_payment')} size="lg">
        <form onSubmit={createPayment} className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2">
            <SelectField label={t('field.payment_method')} id="method" name="method" value={form.payment_method} onChange={(e) => setForm({ ...form, payment_method: e.target.value as any })} options={[
              { value: 'cash', label: t('method.cash') },
              { value: 'bank_transfer', label: t('method.bank_transfer') },
              { value: 'wallet', label: t('method.wallet') },
            ]} required />
            <InputField label={t('field.currency_id')} id="currency_id" name="currency_id" value={form.currency_id} onChange={(e) => setForm({ ...form, currency_id: e.target.value })} required />
            <InputField label={t('field.amount')} id="amount" name="amount" type="number" min="0.01" step="0.01" value={form.amount || ''} onChange={(e) => setForm({ ...form, amount: Number(e.target.value) })} required />
            <InputField label={t('field.exchange_rate')} id="exchange_rate" name="exchange_rate" type="number" min="0.000001" step="0.000001" value={form.exchange_rate || 1} onChange={(e) => setForm({ ...form, exchange_rate: Number(e.target.value) })} />
            <SelectField label={isReceipt ? t('field.payer_type') : t('field.payee_type')} id="party_type" name="party_type" value={(isReceipt ? form.payer_type : form.payee_type) || ''} onChange={(e) => isReceipt ? setForm({ ...form, payer_type: e.target.value as any }) : setForm({ ...form, payee_type: e.target.value as any })} options={[
              { value: 'customer', label: t('party.customer') },
              { value: 'supplier', label: t('party.supplier') },
              { value: 'platform', label: t('party.platform') },
            ]} />
            <InputField label={isReceipt ? t('field.payer_id') : t('field.payee_id')} id="party_id" name="party_id" value={(isReceipt ? form.payer_id : form.payee_id) || ''} onChange={(e) => isReceipt ? setForm({ ...form, payer_id: e.target.value }) : setForm({ ...form, payee_id: e.target.value })} />
            <InputField label={t('field.reference')} id="reference" name="reference" value={form.reference || ''} onChange={(e) => setForm({ ...form, reference: e.target.value })} />
          </div>
          <TextAreaField label={t('field.notes')} id="notes" name="notes" value={form.notes || ''} onChange={(e) => setForm({ ...form, notes: e.target.value })} />
          <div className="flex justify-end gap-2">
            <Button type="button" variant="outline" onClick={() => setCreateOpen(false)}>{t('action.cancel')}</Button>
            <Button type="submit" isLoading={busy}>{t('action.save_draft')}</Button>
          </div>
        </form>
      </Modal>

      <Modal open={Boolean(selected)} onClose={() => setSelected(null)} title={selected?.payment_no || t('field.voucher')} size="md">
        {selected && (
          <div className="space-y-4 text-sm">
            <div className="grid grid-cols-2 gap-3">
              <Info label={t('field.status')} value={t(`status.${selected.status}`)} />
              <Info label={t('field.amount')} value={money(selected.amount, selected.currency_id)} />
              <Info label={t('field.party')} value={partyLabel(selected)} />
              <Info label={t('action.journal')} value={shortId(selected.posting_journal_id)} />
              <Info label={t('field.voucher')} value={voucher?.voucher_no || '-'} />
              <Info label={t('field.reconciled')} value={selected.reconciliation_id ? t('common.yes') : t('common.no')} />
            </div>
            {selected.status === 'posted' && <Button variant="outline" onClick={() => printVoucher(selected, voucher, isReceipt ? t('title.receipt_voucher_single') : t('title.payment_voucher_single'))}><Printer className="h-4 w-4" />{t('action.print')}</Button>}
            {(selected.status === 'draft' || selected.status === 'pending' || selected.status === 'approved') && (
              <div className="space-y-2">
                <TextAreaField label={t('field.action_note')} id="note" name="note" value={note} onChange={(e) => setNote(e.target.value)} />
              </div>
            )}
            {selected.status === 'posted' && (
              <div className="space-y-2">
                <TextAreaField label={t('field.reverse_reason')} id="reason" name="reason" value={reason} onChange={(e) => setReason(e.target.value)} required />
                {access.canPost && <Button variant="danger" disabled={!reason} isLoading={busy} onClick={() => run(() => payments.reversePayment(selected.id, reason), t('toast.reversed'))}><Undo2 className="h-4 w-4" />{t('action.reverse')}</Button>}
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  )
}

function Info({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-md border border-border bg-muted/20 p-3">
      <div className="text-xs text-muted-foreground">{label}</div>
      <div className="mt-1 font-medium">{value}</div>
    </div>
  )
}

export function SettlementsPage() {
  const access = useFinanceAccess()
  const payments = useSprintPayments()
  const settlements = useSprintSettlements()
  const [selectedPaymentId, setSelectedPaymentId] = useState('')
  const [selectedSettlement, setSelectedSettlement] = useState<Settlement | null>(null)
  const [referenceType, setReferenceType] = useState('buy_order')
  const [referenceId, setReferenceId] = useState('')
  const [amount, setAmount] = useState(0)
  const [reason, setReason] = useState('')
  const [busy, setBusy] = useState(false)

  const reload = async () => {
    await Promise.all([
      payments.fetchPayments({ status: 'posted' }),
      settlements.fetchSettlements(),
    ])
  }

  useEffect(() => {
    reload()
  }, [])

  const selectedPayment = payments.items.find((p) => p.id === selectedPaymentId)
  const activeSettlements = settlements.items.filter((s) => s.status !== 'cancelled' && s.status !== 'reversed')
  const allocated = selectedPayment ? activeSettlements.filter((s) => s.payment_id === selectedPayment.id).reduce((sum, row) => sum + Number(row.total_applied || 0), 0) : 0
  const remaining = Math.max(Number(selectedPayment?.amount || 0) - allocated, 0)
  const availablePayments = payments.items.filter((p) => {
    const used = activeSettlements.filter((s) => s.payment_id === p.id).reduce((sum, row) => sum + Number(row.total_applied || 0), 0)
    return used < Number(p.amount || 0)
  })

  const createSettlement = async () => {
    if (!selectedPaymentId) return
    setBusy(true)
    try {
      const settlement = await settlements.createSettlement(selectedPaymentId)
      toast.success(t('toast.settlement_created'))
      setSelectedSettlement(settlement)
      await reload()
    } finally {
      setBusy(false)
    }
  }

  const addLine = async () => {
    if (!selectedSettlement || !referenceId || amount <= 0) return
    if (amount > Number(selectedSettlement.remaining_amount || remaining)) {
      toast.error(t('validation.allocation_exceeds_remaining'))
      return
    }
    setBusy(true)
    try {
      await settlements.addLine(selectedSettlement.id, referenceType, referenceId, amount)
      toast.success(t('toast.allocation_added'))
      setReferenceId('')
      setAmount(0)
      await reload()
    } finally {
      setBusy(false)
    }
  }

  const runSettlement = async (fn: () => Promise<unknown>, message: string) => {
    if (!selectedSettlement) return
    setBusy(true)
    try {
      await fn()
      toast.success(message)
      setReason('')
      await reload()
    } finally {
      setBusy(false)
    }
  }

  const columns: Column<Settlement>[] = [
    { key: 'no', header: t('field.settlement'), cell: (s) => <button className="font-mono text-xs font-semibold hover:text-gold-700" onClick={() => setSelectedSettlement(s)}>{s.settlement_no}</button> },
    { key: 'payment', header: t('field.payment'), cell: (s) => shortId(s.payment_id) },
    { key: 'applied', header: t('field.applied'), cell: (s) => <span className="font-mono">{money(s.total_applied)}</span> },
    { key: 'remaining', header: t('field.remaining'), cell: (s) => <span className="font-mono">{money(s.remaining_amount)}</span> },
    { key: 'status', header: t('field.status'), cell: (s) => <Status value={s.status} /> },
    { key: 'created', header: t('field.created'), cell: (s) => <span className="text-xs text-muted-foreground">{formatDateTime(s.created_at || '')}</span> },
  ]

  return (
    <div className="space-y-6">
      <PageHeader title={t('title.settlements')} description={t('description.settlements')} />

      <div className="grid gap-4 md:grid-cols-3">
        <KpiCard label={t('kpi.available_payments')} value={String(availablePayments.length)} icon={Banknote} tone="info" />
        <KpiCard label={t('title.settlements')} value={String(settlements.items.length)} icon={Link2} tone="gold" />
        <KpiCard label={t('status.posted')} value={String(settlements.items.filter((s) => s.status === 'posted').length)} icon={ShieldCheck} tone="success" />
      </div>

      <SectionCard title={t('section.create_allocation')}>
        <div className="grid gap-4 lg:grid-cols-[1fr_220px]">
          <SelectField label={t('field.posted_payment')} id="payment" name="payment" value={selectedPaymentId} onChange={(e) => setSelectedPaymentId(e.target.value)} options={availablePayments.map((p) => ({ value: p.id, label: `${p.payment_no} - ${money(p.amount, p.currency_id)} - ${t('field.remaining')} ${money(Number(p.amount || 0) - activeSettlements.filter((s) => s.payment_id === p.id).reduce((sum, row) => sum + Number(row.total_applied || 0), 0))}` }))} />
          {access.canCreate && <Button disabled={!selectedPaymentId || busy} isLoading={busy} onClick={createSettlement}><Link2 className="h-4 w-4" />{t('action.create_settlement')}</Button>}
        </div>
        {selectedPayment && (
          <div className="mt-4 grid gap-3 md:grid-cols-3">
            <Info label={t('field.payment_amount')} value={money(selectedPayment.amount, selectedPayment.currency_id)} />
            <Info label={t('field.allocated')} value={money(allocated, selectedPayment.currency_id)} />
            <Info label={t('field.remaining')} value={money(remaining, selectedPayment.currency_id)} />
          </div>
        )}
      </SectionCard>

      <SectionCard title={t('section.settlement_register')} padded={false}>
        {settlements.isLoading ? <div className="flex justify-center py-10"><Loader2 className="h-6 w-6 animate-spin" /></div> : <DataTable columns={columns} data={settlements.items} rowKey={(s) => s.id} />}
      </SectionCard>

      <Modal open={Boolean(selectedSettlement)} onClose={() => setSelectedSettlement(null)} title={selectedSettlement?.settlement_no || t('field.settlement')} size="lg">
        {selectedSettlement && (
          <div className="space-y-5">
            <div className="grid gap-3 md:grid-cols-3">
              <Info label={t('field.status')} value={t(`status.${selectedSettlement.status}`)} />
              <Info label={t('field.applied')} value={money(selectedSettlement.total_applied)} />
              <Info label={t('field.remaining')} value={money(selectedSettlement.remaining_amount)} />
            </div>

            {access.canUpdate && (selectedSettlement.status === 'draft' || selectedSettlement.status === 'partial') && (
              <div className="grid gap-3 md:grid-cols-[160px_1fr_160px_auto]">
                <SelectField label={t('field.reference_type')} id="ref_type" name="ref_type" value={referenceType} onChange={(e) => setReferenceType(e.target.value)} options={[{ value: 'buy_order', label: t('reference.buy_order') }, { value: 'sell_order', label: t('reference.sell_order') }]} />
                <InputField label={t('field.reference_id')} id="ref_id" name="ref_id" value={referenceId} onChange={(e) => setReferenceId(e.target.value)} />
                <InputField label={t('field.amount')} id="line_amount" name="line_amount" type="number" min="0.01" step="0.01" value={amount || ''} onChange={(e) => setAmount(Number(e.target.value))} />
                <div className="flex items-end"><Button disabled={!referenceId || amount <= 0 || busy} onClick={addLine}>{t('action.add')}</Button></div>
              </div>
            )}

            <div className="rounded-md border border-border">
              <div className="border-b border-border bg-muted/30 px-3 py-2 text-sm font-semibold">{t('section.lines')}</div>
              <div className="divide-y divide-border">
                {selectedSettlement.lines?.length ? selectedSettlement.lines.map((line) => (
                  <div key={line.id} className="grid grid-cols-4 gap-2 px-3 py-2 text-sm">
                    <span>{line.reference_type}</span>
                    <span className="font-mono">{shortId(line.reference_id)}</span>
                    <span className="font-mono">{money(line.amount)}</span>
                    <Status value={line.status} />
                  </div>
                )) : <div className="px-3 py-6 text-center text-sm text-muted-foreground">{t('empty.no_lines')}</div>}
              </div>
            </div>

            <div className="flex flex-wrap gap-2">
              {selectedSettlement.status === 'draft' && access.canUpdate && <Button variant="outline" onClick={() => runSettlement(() => settlements.submitSettlement(selectedSettlement.id), t('toast.submitted'))}>{t('action.submit')}</Button>}
              {selectedSettlement.status === 'pending' && access.canApprove && <Button variant="outline" onClick={() => runSettlement(() => settlements.approveSettlement(selectedSettlement.id), t('toast.approved'))}>{t('action.approve')}</Button>}
              {(selectedSettlement.status === 'full' || selectedSettlement.status === 'partial') && access.canPost && <Button onClick={() => runSettlement(() => settlements.postSettlement(selectedSettlement.id), t('toast.posted'))}>{t('action.post')}</Button>}
            </div>

            {selectedSettlement.status === 'posted' && (
              <div className="space-y-2">
                <TextAreaField label={t('field.reverse_reason')} id="settlement_reason" name="settlement_reason" value={reason} onChange={(e) => setReason(e.target.value)} />
                {access.canPost && <Button variant="danger" disabled={!reason || busy} onClick={() => runSettlement(() => settlements.reverseSettlement(selectedSettlement.id, reason), t('toast.settlement_reversed'))}><RefreshCcw className="h-4 w-4" />{t('action.reverse_settlement')}</Button>}
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  )
}

export function FinanceReconciliationPage() {
  const access = useFinanceAccess()
  const recs = useSprintReconciliations()
  const [createOpen, setCreateOpen] = useState(false)
  const [selected, setSelected] = useState<Reconciliation | null>(null)
  const [notes, setNotes] = useState('')
  const [busy, setBusy] = useState(false)
  const [form, setForm] = useState({ reconciliation_type: 'cash', period_start: '', period_end: '', actual_balance: 0, notes: '' })

  const reload = () => recs.fetchReconciliations()

  useEffect(() => {
    reload()
  }, [])

  const create = async (event: FormEvent) => {
    event.preventDefault()
    setBusy(true)
    try {
      await recs.createReconciliation(form as any)
      toast.success(t('toast.reconciliation_created'))
      setCreateOpen(false)
      await reload()
    } finally {
      setBusy(false)
    }
  }

  const run = async (fn: () => Promise<unknown>, message: string) => {
    setBusy(true)
    try {
      await fn()
      toast.success(message)
      setNotes('')
      await reload()
    } finally {
      setBusy(false)
    }
  }

  const columns: Column<Reconciliation>[] = [
    { key: 'no', header: t('field.number'), cell: (r) => <button className="font-mono text-xs font-semibold hover:text-gold-700" onClick={() => setSelected(r)}>{r.reconciliation_no}</button> },
    { key: 'type', header: t('field.type'), cell: (r) => <span className="capitalize">{t(`method.${r.reconciliation_type}`)}</span> },
    { key: 'period', header: t('field.period'), cell: (r) => <span className="text-xs">{r.period_start} - {r.period_end}</span> },
    { key: 'expected', header: t('field.expected'), cell: (r) => <span className="font-mono">{money(r.expected_balance)}</span> },
    { key: 'actual', header: t('field.actual'), cell: (r) => <span className="font-mono">{money(r.actual_balance)}</span> },
    { key: 'diff', header: t('field.difference'), cell: (r) => <span className={Number(r.difference) === 0 ? 'font-mono text-emerald-700' : 'font-mono text-red-700'}>{money(r.difference)}</span> },
    { key: 'status', header: t('field.status'), cell: (r) => <Status value={r.status} /> },
  ]

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <PageHeader title={t('title.reconciliation')} description={t('description.reconciliation')} />
        {access.canCreate && <Button onClick={() => setCreateOpen(true)}><Scale className="h-4 w-4" />{t('action.create_reconciliation')}</Button>}
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <KpiCard label={t('kpi.sessions')} value={String(recs.items.length)} icon={Scale} tone="gold" />
        <KpiCard label={t('status.in_progress')} value={String(recs.items.filter((r) => r.status === 'in_progress').length)} icon={Loader2} tone="warning" />
        <KpiCard label={t('status.reconciled')} value={String(recs.items.filter((r) => r.status === 'reconciled').length)} icon={CheckCircle2} tone="success" />
        <KpiCard label={t('status.discrepancy')} value={String(recs.items.filter((r) => r.status === 'discrepancy').length)} icon={AlertTriangle} tone="danger" />
      </div>

      <SectionCard title={t('section.reconciliation_sessions')} padded={false}>
        {recs.isLoading ? <div className="flex justify-center py-10"><Loader2 className="h-6 w-6 animate-spin" /></div> : <DataTable columns={columns} data={recs.items} rowKey={(r) => r.id} />}
      </SectionCard>

      <Modal open={createOpen} onClose={() => setCreateOpen(false)} title={t('action.create_reconciliation')} size="md">
        <form onSubmit={create} className="space-y-4">
          <SelectField label={t('field.type')} id="rec_type" name="rec_type" value={form.reconciliation_type} onChange={(e) => setForm({ ...form, reconciliation_type: e.target.value })} options={[{ value: 'cash', label: t('method.cash') }, { value: 'bank', label: t('method.bank') }, { value: 'wallet', label: t('method.wallet') }]} />
          <div className="grid gap-4 md:grid-cols-2">
            <InputField label={t('field.period_start')} id="period_start" name="period_start" type="date" value={form.period_start} onChange={(e) => setForm({ ...form, period_start: e.target.value })} required />
            <InputField label={t('field.period_end')} id="period_end" name="period_end" type="date" value={form.period_end} onChange={(e) => setForm({ ...form, period_end: e.target.value })} required />
          </div>
          <InputField label={t('field.actual_balance')} id="actual_balance" name="actual_balance" type="number" step="0.01" value={form.actual_balance || ''} onChange={(e) => setForm({ ...form, actual_balance: Number(e.target.value) })} />
          <TextAreaField label={t('field.notes')} id="rec_notes" name="rec_notes" value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} />
          <div className="flex justify-end gap-2">
            <Button type="button" variant="outline" onClick={() => setCreateOpen(false)}>{t('action.cancel')}</Button>
            <Button type="submit" isLoading={busy}>{t('action.create')}</Button>
          </div>
        </form>
      </Modal>

      <Modal open={Boolean(selected)} onClose={() => setSelected(null)} title={selected?.reconciliation_no || t('field.reconciliation')} size="md">
        {selected && (
          <div className="space-y-4">
            <div className="grid gap-3 md:grid-cols-2">
              <Info label={t('field.expected')} value={money(selected.expected_balance)} />
              <Info label={t('field.actual')} value={money(selected.actual_balance)} />
              <Info label={t('field.difference')} value={money(selected.difference)} />
              <Info label={t('field.reconciled_by')} value={shortId(selected.reconciled_by)} />
              <Info label={t('field.reconciled_at')} value={selected.reconciled_at ? formatDateTime(selected.reconciled_at) : '-'} />
              <Info label={t('field.status')} value={t(`status.${selected.status}`)} />
            </div>
            <div className="flex flex-wrap gap-2">
              {selected.status === 'draft' && access.canUpdate && <Button variant="outline" disabled={busy} onClick={() => run(() => recs.startReconciliation(selected.id), t('toast.reconciliation_started'))}>{t('action.start')}</Button>}
              {selected.status === 'in_progress' && access.canApprove && <Button disabled={busy} onClick={() => run(() => recs.markReconciled(selected.id), t('toast.marked_reconciled'))}>{t('action.mark_reconciled')}</Button>}
            </div>
            {selected.status === 'in_progress' && (
              <div className="space-y-2">
                <TextAreaField label={t('field.discrepancy_note')} id="disc_notes" name="disc_notes" value={notes} onChange={(e) => setNotes(e.target.value)} />
                {access.canApprove && <Button variant="danger" disabled={!notes || busy} onClick={() => run(() => recs.markDiscrepancy(selected.id, notes), t('toast.marked_discrepancy'))}>{t('action.mark_discrepancy')}</Button>}
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  )
}
