'use client'

import { useState, useMemo } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useParams, useRouter } from 'next/navigation'
import axios from 'axios'
import { toast } from 'sonner'
import { formatCurrency, fmtDate, fmtDateTime, cn } from '@/lib/utils'
import {
  ChevronLeft, CreditCard, CheckCircle2, XCircle, RotateCcw,
  DollarSign, Plus, Printer, FileText, TrendingUp, Shield, ClipboardList,
} from 'lucide-react'
import {
  Badge, StatusBadge, Card, CardHeader, CardTitle, CardContent,
  Button, Tabs, InfoRow, InfoGrid, Amount, LoadingSpinner, Alert, Modal,
  Input, Select, Textarea, FormGrid,
} from '@/components/ui/components'

const METHOD_GL: Record<string, string> = {
  BANK_TRANSFER: '1102', CHEQUE: '1102', EFT: '1102', RTGS: '1102',
  MPESA: '1103', CASH: '1101',
}
const METHOD_GL_LABEL: Record<string, string> = {
  '1101': 'Cash in Hand', '1102': 'Bank - Equity', '1103': 'M-Pesa Float',
}

export default function LoanDetailPage() {
  const { id } = useParams<{ id: string }>()
  const router  = useRouter()
  const qc      = useQueryClient()

  const [tab, setTab] = useState('summary')

  // ── Modal state ───────────────────────────────────────────────────────────
  const [repayModal,      setRepayModal]      = useState(false)
  const [approveModal,    setApproveModal]    = useState(false)
  const [disburseModal,   setDisburseModal]   = useState(false)
  const [guarantorModal,  setGuarantorModal]  = useState(false)
  const [collateralModal, setCollateralModal] = useState(false)
  const [activityModal,   setActivityModal]   = useState(false)
  const [appraisalModal,  setAppraisalModal]  = useState(false)
  const [topupModal,      setTopupModal]      = useState(false)
  const [crbModal,        setCrbModal]        = useState(false)
  const [feeModal,        setFeeModal]        = useState(false)
  const [backdateModal,   setBackdateModal]   = useState(false)

  // ── Form state ────────────────────────────────────────────────────────────
  const [repayForm, setRepayForm] = useState({
    amount: '', method: 'CASH', reference: '',
    paymentDate: new Date().toISOString().slice(0, 10),
    useInterestOverride: false, interestOverride: '',
    excessSavingsAccountId: '',
  })
  const [earlyRepayInfo, setEarlyRepayInfo] = useState<{ amount: number; oneMonthInterest: number } | null>(null)
  const [approveForm,    setApproveForm]    = useState({ action: 'APPROVE', comments: '', level: 1 })
  const [disburseForm,   setDisburseForm]   = useState({ disbursementMethod: 'BANK_TRANSFER', disbursementReference: '' })
  const [guarantorForm,  setGuarantorForm]  = useState({
    memberId: '', isMember: true, guaranteeAmount: '', nonMemberName: '', nonMemberPhone: '',
  })
  const [collateralForm, setCollateralForm] = useState({
    collateralType: '', description: '', estimatedValue: '',
    make: '', model: '', serialNumber: '', location: '',
  })
  const [activityForm,   setActivityForm]   = useState({
    actionType: 'CALL_ATTEMPT', contactMade: false, notes: '', outcome: '',
  })
  const [appraisalForm,  setAppraisalForm]  = useState({
    totalScore: '', maxScore: '100', recommendation: 'APPROVE', notes: '',
    approvedAmount: '', incomeVerified: false, businessVisited: false,
    visitDate: '', visitNotes: '',
  })
  const [topupForm,    setTopupForm]    = useState({ topUpType: 'ADD_ON', requestedAmount: '', reason: '', newTenor: '' })
  const [crbForm,      setCrbForm]      = useState({ result: 'CLEAR', details: '', score: '' })
  const [feeForm,      setFeeForm]      = useState({ feeReference: '', feeMethod: 'CASH' })
  const [backdateForm, setBackdateForm] = useState({ targetDate: '' })

  // ── Data ──────────────────────────────────────────────────────────────────
  const { data, isLoading } = useQuery({
    queryKey: ['loan', id],
    queryFn:  () => axios.get(`/api/loans/${id}`).then(r => r.data.data),
  })

  // Fetch appraiser names for appraisals
  const appraisalUserIds = useMemo(() => {
    if (!data?.appraisals?.length) return []
    return [...new Set(data.appraisals.map((a: any) => a.appraisedById).filter(Boolean))] as string[]
  }, [data])

  const { data: appraisalUsers } = useQuery({
    queryKey: ['users-mini', appraisalUserIds],
    queryFn:  () => axios.get(`/api/admin/users?ids=${appraisalUserIds.join(',')}`).then(r => r.data.data),
    enabled:  appraisalUserIds.length > 0,
    // Fallback: if endpoint doesn't exist yet, we just won't show the name
    retry: false,
  })

  const appraisalUserMap = useMemo(() => {
    const map = new Map<string, string>()
    if (Array.isArray(appraisalUsers)) {
      appraisalUsers.forEach((u: any) => map.set(u.id, u.fullName))
    }
    return map
  }, [appraisalUsers])

  // ── Mutations ─────────────────────────────────────────────────────────────
  const actionMutation = useMutation({
    mutationFn: (p: any) => axios.patch(`/api/loans/${id}`, p),
    onSuccess: (res, vars) => {
      const msgs: Record<string, string> = {
        REPAY:                `Repayment recorded — ${res.data?.data?.breakdown ?? ''}`,
        APPROVE:              'Loan approved',
        DECLINE:              'Loan declined',
        RETURN:               'Loan returned for correction',
        DISBURSE:             'Loan disbursed successfully',
        APPRAISE:             'Appraisal saved',
        REQUEST_TOPUP:        'Top-up request submitted',
        CRB_CHECK:            'CRB check recorded',
        MARK_FEE_PAID:        'Processing fee recorded',
        BACKDATE:             'Loan backdated successfully',
      }
      toast.success(msgs[vars.action] ?? 'Done')
      qc.invalidateQueries({ queryKey: ['loan', id] })
      setRepayModal(false);    setApproveModal(false);  setDisburseModal(false)
      setAppraisalModal(false);setTopupModal(false);    setCrbModal(false)
      setFeeModal(false);      setBackdateModal(false)
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Action failed'),
  })

  const addGuarantorMutation = useMutation({
    mutationFn: (p: any) => axios.patch(`/api/loans/${id}`, { action: 'ADD_GUARANTOR', ...p }),
    onSuccess: () => {
      toast.success('Guarantor added')
      qc.invalidateQueries({ queryKey: ['loan', id] })
      setGuarantorModal(false)
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to add guarantor'),
  })

  const addCollateralMutation = useMutation({
    mutationFn: (p: any) => axios.patch(`/api/loans/${id}`, { action: 'ADD_COLLATERAL', ...p }),
    onSuccess: () => {
      toast.success('Collateral added')
      qc.invalidateQueries({ queryKey: ['loan', id] })
      setCollateralModal(false)
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to add collateral'),
  })

  const logActivityMutation = useMutation({
    mutationFn: (p: any) => axios.patch(`/api/loans/${id}`, { action: 'LOG_ACTIVITY', ...p }),
    onSuccess: () => {
      toast.success('Activity logged')
      qc.invalidateQueries({ queryKey: ['loan', id] })
      setActivityModal(false)
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to log activity'),
  })

  const submitMutation = useMutation({
    mutationFn: () => axios.patch(`/api/loans/${id}`, { action: 'SUBMIT' }),
    onSuccess: () => {
      toast.success('Loan submitted for approval')
      qc.invalidateQueries({ queryKey: ['loan', id] })
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Cannot submit'),
  })

  // ── Statement entries ─────────────────────────────────────────────────────
  const statementEntries = useMemo(() => {
    if (!data) return []
    const entries: any[] = []
    let balance = 0
    if (data.disbursedAt) {
      balance = parseFloat(data.principalAmount ?? 0)
      entries.push({
        date: data.disbursedAt, description: 'Loan Disbursement',
        reference: data.loanRef, debit: balance, credit: 0, balance, type: 'DISBURSEMENT',
      })
    }
    const sorted = [...(data.repayments ?? [])]
      .filter((r: any) => !r.isReversed)
      .sort((a: any, b: any) => new Date(a.paymentDate).getTime() - new Date(b.paymentDate).getTime())

    for (const r of sorted) {
      const principal = parseFloat(r.principalPaid ?? 0)
      const interest  = parseFloat(r.interestPaid  ?? 0)
      const penalties = parseFloat(r.penaltiesPaid ?? 0)
      const total     = parseFloat(r.amount        ?? 0)
      balance = Math.max(0, balance - principal)
      entries.push({
        date: r.paymentDate, description: 'Repayment',
        reference: r.receiptNo, method: r.method,
        debit: 0, credit: total,
        principalPaid: principal, interestPaid: interest, penaltiesPaid: penalties,
        balance, type: 'REPAYMENT',
      })
    }
    return entries
  }, [data])

  const printWindow = (contentId: string, title: string) => {
    const content = document.getElementById(contentId)?.innerHTML
    if (!content) return
    const w = window.open('', '_blank')
    if (!w) return
    w.document.write(`<html><head><title>${title}</title>
    <style>
      body{font-family:Arial,sans-serif;font-size:12px;padding:20px;color:#111}
      table{width:100%;border-collapse:collapse}
      th,td{padding:5px 8px;border-bottom:1px solid #ddd}
      th{background:#f5f5f5;font-weight:600}
      .text-right{text-align:right}
      @media print{body{padding:0}}
    </style></head><body>${content}</body></html>`)
    w.document.close(); w.print()
  }

  // ── Guards ────────────────────────────────────────────────────────────────
  if (isLoading) return <LoadingSpinner message="Loading loan…" />
  if (!data)     return <div className="p-8 text-center text-muted-foreground">Loan not found or access denied.</div>

  const l = data

  // FIX: include APPRAISED so officer can submit after appraising
  const canAppraise    = ['DRAFT', 'PENDING_APPRAISAL', 'APPRAISED'].includes(l.status)
  const canDisburse    = l.status === 'APPROVED'
  const canRepay       = l.status === 'ACTIVE'
  const pendingApproval= l.approvals?.find((a: any) => a.status === 'PENDING')
  const totalPrincipal = parseFloat(l.principalAmount ?? 0)
  const totalPaid      = parseFloat(l.totalPaid ?? 0)
  const totalInterestPaid = parseFloat(l.totalInterestPaid ?? 0)
  const completionRate = l.status === 'CLOSED'
    ? 100
    : totalPrincipal > 0
      ? Math.min(100, (totalPaid / (totalPrincipal + totalInterestPaid)) * 100)
      : 0

  const accruedInterest  = parseFloat(l.accruedInterest  ?? 0)
  const accruedPenalties = parseFloat(l.accruedPenalties ?? 0)
  const trueOutstanding  = parseFloat(l.outstandingPrincipal ?? 0) + accruedInterest + accruedPenalties

  // Latest appraisal (for summary display)
  const latestAppraisal = l.appraisals?.[0] ?? null

  const tabs = [
    { id: 'summary',     label: 'Summary'                                          },
    { id: 'statement',   label: 'Statement',   count: statementEntries.length      },
    { id: 'schedule',    label: 'Schedule',    count: l.schedule?.length            },
    { id: 'repayments',  label: 'Repayments',  count: l._count?.repayments         },
    { id: 'appraisal',   label: 'Appraisal',   count: l.appraisals?.length         },
    { id: 'topups',      label: 'Top-Ups',     count: l.topUps?.length              },
    { id: 'collateral',  label: 'Collateral',  count: l.collaterals?.length        },
    { id: 'guarantors',  label: 'Guarantors',  count: l.guarantors?.length         },
    { id: 'approvals',   label: 'Approvals',   count: l.approvals?.length          },
    { id: 'collections', label: 'Collections', count: l._count?.collectionActivities },
    { id: 'history',     label: 'History'                                           },
  ]

  return (
    <div className="p-6 space-y-5 max-w-screen-xl mx-auto">

      {/* ── Page header ── */}
      <div className="flex items-center justify-between flex-wrap gap-2">
        <div className="flex items-center gap-2">
          <Button variant="ghost" size="sm" icon={<ChevronLeft className="w-4 h-4" />}
            onClick={() => router.back()}>
            Loans
          </Button>
          <span className="text-muted-foreground">/</span>
          <span className="font-mono text-sm font-semibold">{l.loanRef}</span>
          {l.creatorName && (
            <span className="text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded">
              Created by: {l.creatorName}
            </span>
          )}
        </div>

        <div className="flex items-center gap-2 flex-wrap">
          {/* Statement print */}
          <Button variant="outline" size="sm" icon={<FileText className="w-4 h-4" />}
            onClick={() => { setTab('statement'); setTimeout(() => printWindow('loan-statement-print', `Statement — ${l.loanRef}`), 300) }}>
            Statement
          </Button>

          {/* Backdate — active loans only */}
          {l.status === 'ACTIVE' && (
            <Button variant="ghost" size="sm" icon={<ClipboardList className="w-4 h-4" />}
              onClick={() => setBackdateModal(true)}>
              Backdate
            </Button>
          )}

          {/* CRB Check — always available */}
          <Button variant="ghost" size="sm" icon={<Shield className="w-4 h-4" />}
            onClick={() => setCrbModal(true)}>
            CRB Check
          </Button>

          {/* Top-Up — active loans only */}
          {l.status === 'ACTIVE' && (
            <Button variant="outline" size="sm" icon={<TrendingUp className="w-4 h-4" />}
              onClick={() => { setTopupModal(true); setTab('topups') }}>
              Top Up
            </Button>
          )}

          {/* FIX: Appraise button also shows for APPRAISED so officer can update */}
          {canAppraise && (
            <Button variant="outline" size="sm" icon={<ClipboardList className="w-4 h-4" />}
              onClick={() => { setTab('appraisal'); setAppraisalModal(true) }}>
              {l.appraisals?.length > 0 ? 'Update Appraisal' : 'Appraise'}
            </Button>
          )}

          {/* Processing fee upfront — show if product requires upfront fee not yet paid */}
          {l.status === 'DRAFT' && !l.product?.processingFeeDeducted
            && !l.processingFeePaid && parseFloat(l.processingFee ?? 0) > 0 && (
            <Button size="sm" variant="outline" onClick={() => setFeeModal(true)}>
              Record Processing Fee
            </Button>
          )}

          {/* Submit — DRAFT */}
          {l.status === 'DRAFT' && (
            <Button size="sm" loading={submitMutation.isPending}
              onClick={() => submitMutation.mutate()}>
              Submit for Approval
            </Button>
          )}

          {/* Resubmit — returned for correction */}
          {l.status === 'PENDING_APPRAISAL' && (
            <Button size="sm" loading={submitMutation.isPending}
              onClick={() => submitMutation.mutate()}>
              Resubmit for Approval
            </Button>
          )}

          {/* FIX: Submit — APPRAISED (after officer completes appraisal) */}
          {l.status === 'APPRAISED' && (
            <Button size="sm" loading={submitMutation.isPending}
              onClick={() => submitMutation.mutate()}>
              Submit for Approval
            </Button>
          )}

          {/* Action Approval — when a level is pending */}
          {pendingApproval && (
            <Button size="sm" icon={<CheckCircle2 className="w-4 h-4" />}
              onClick={() => {
                setApproveForm(f => ({ ...f, level: pendingApproval.level }))
                setApproveModal(true)
              }}>
              Action Approval
            </Button>
          )}

          {/* Disburse */}
          {canDisburse && (
            <Button size="sm" variant="success" icon={<DollarSign className="w-4 h-4" />}
              onClick={() => setDisburseModal(true)}>
              Disburse
            </Button>
          )}

          {/* Repayment */}
          {canRepay && (
            <Button size="sm" icon={<Plus className="w-4 h-4" />}
              onClick={() => setRepayModal(true)}>
              Repayment
            </Button>
          )}
        </div>
      </div>

      {/* ── Status banners ── */}
      {l.status === 'PENDING_APPRAISAL' && (
        <Alert variant="warning">
          <strong>Loan returned for correction.</strong> Review the approval comments in the Approvals tab,
          make the required corrections, then resubmit.
        </Alert>
      )}

      {/* FIX: APPRAISED banner guides officer to submit */}
      {l.status === 'APPRAISED' && (
        <Alert variant="success">
          <div className="flex items-center justify-between flex-wrap gap-2">
            <span>
              <strong>Appraisal complete</strong>
              {latestAppraisal && (
                <>
                  {' '}— Recommendation:{' '}
                  <strong className={latestAppraisal.recommendation === 'APPROVE' ? 'text-green-700' : 'text-red-700'}>
                    {latestAppraisal.recommendation}
                  </strong>
                  {latestAppraisal.totalScore != null && (
                    <span className="text-muted-foreground">
                      {' '}(Score: {latestAppraisal.totalScore}/{latestAppraisal.maxScore ?? 100})
                    </span>
                  )}
                </>
              )}
              . Click <strong>Submit for Approval</strong> when ready.
            </span>
          </div>
        </Alert>
      )}

      {/* ── Loan summary card ── */}
      <Card>
        <CardContent className="p-6">
          <div className="flex items-start gap-5">
            <div className="w-14 h-14 rounded-xl bg-primary/10 text-primary flex items-center justify-center shrink-0">
              <CreditCard className="w-7 h-7" />
            </div>
            <div className="flex-1">
              <div className="flex items-center gap-3 flex-wrap">
                <h2 className="text-xl font-semibold font-mono">{l.loanRef}</h2>
                <StatusBadge status={l.status}     type="loan"  />
                <StatusBadge status={l.sasraClass} type="sasra" />
                <StatusBadge status={l.ifrsStage}  type="ifrs"  />
                {l.status === 'CLOSED' && parseFloat(l.outstandingBalance ?? 0) <= 0.01 && (
                  <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-green-100 text-green-800 border border-green-300">
                    <CheckCircle2 className="w-3.5 h-3.5" /> FULLY PAID
                  </span>
                )}
              </div>
              <p className="text-sm text-muted-foreground mt-1">
                {l.member?.fullName} · {l.member?.memberNo} · {l.product?.name}
              </p>

              {/* CRB status */}
              {l.member?.crbStatus && l.member.crbStatus !== 'NOT_CHECKED' && (
                <p className="text-xs mt-1">
                  CRB:{' '}
                  <span className={cn('font-semibold',
                    l.member.crbStatus === 'CLEAR' ? 'text-green-600' : 'text-red-600'
                  )}>
                    {l.member.crbStatus}
                  </span>
                  {l.member.crbCheckedAt && (
                    <span className="text-muted-foreground ml-1">
                      · checked {fmtDate(l.member.crbCheckedAt)}
                    </span>
                  )}
                </p>
              )}

              {l.daysOverdue > 0 && (
                <Alert variant="error" className="mt-2">
                  <strong>{l.daysOverdue} days overdue.</strong>{' '}
                  Accrued penalties: {formatCurrency(l.accruedPenalties)}
                </Alert>
              )}
            </div>
          </div>

          {/* Repayment progress bar */}
          <div className="mt-4">
            <div className="flex justify-between text-xs text-muted-foreground mb-1">
              <span>Repayment progress</span>
              <span>
                {completionRate.toFixed(1)}% ({formatCurrency(l.totalPaid)} of {formatCurrency(l.totalRepayable)})
              </span>
            </div>
            <div className="h-2 bg-muted rounded-full overflow-hidden">
              <div className="h-full bg-primary rounded-full transition-all" style={{ width: `${completionRate}%` }} />
            </div>
          </div>

          {/* Key metrics */}
          <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-6 gap-4 mt-5 pt-5 border-t">
            {[
              { label: 'Principal',             value: formatCurrency(l.principalAmount) },
              { label: 'Outstanding Principal', value: formatCurrency(l.outstandingPrincipal), color: 'text-amber-600' },
              { label: 'Accrued Interest',      value: formatCurrency(l.accruedInterest),  color: accruedInterest  > 0 ? 'text-orange-600' : '' },
              { label: 'Accrued Penalties',     value: formatCurrency(l.accruedPenalties), color: accruedPenalties > 0 ? 'text-red-600'    : '' },
              { label: 'Total Outstanding',     value: formatCurrency(trueOutstanding),    color: 'text-red-700 font-bold' },
              { label: 'Interest Rate',         value: `${l.interestRate}% / ${l.interestRatePeriod ?? 'mo'}` },
            ].map(m => (
              <div key={m.label}>
                <p className="text-xs text-muted-foreground">{m.label}</p>
                <p className={cn('text-sm font-semibold mt-0.5', m.color)}>{m.value}</p>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <Tabs tabs={tabs} active={tab} onChange={setTab} />

      {/* ══════════════════════════════════════════════════════════════════════
          TAB: SUMMARY
      ══════════════════════════════════════════════════════════════════════ */}
      {tab === 'summary' && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
          <Card>
            <CardHeader><CardTitle>Loan Terms</CardTitle></CardHeader>
            <CardContent>
              <InfoGrid cols={1}>
                <InfoRow label="Loan Product"        value={l.product?.name} />
                <InfoRow label="Interest Model"      value={l.interestModel?.replace(/_/g, ' ')} />
                <InfoRow label="Interest Rate"       value={`${l.interestRate}% per ${l.interestRatePeriod ?? 'month'}`} />
                <InfoRow label="Tenor"               value={`${l.tenor} ${l.tenorUnit ?? 'months'}`} />
                <InfoRow label="Repayment Frequency" value={l.repaymentFrequency} />
                <InfoRow label="Processing Fee"      value={`${formatCurrency(l.processingFee)} — ${l.processingFeePaid ? '✓ Paid' : l.product?.processingFeeDeducted ? 'Deducted at disbursement' : '⚠ Upfront — not yet paid'}`} />
                <InfoRow label="Total Repayable"     value={formatCurrency(l.totalRepayable)} />
                <InfoRow label="Payment Order"       value={l.paymentAllocationOrder} />
                <InfoRow label="Purpose"             value={l.purpose} />
                <InfoRow label="Applied On"          value={fmtDate(l.createdAt)} />
                <InfoRow label="Submitted On"        value={fmtDate(l.submittedAt)} />
              </InfoGrid>
            </CardContent>
          </Card>
          <Card>
            <CardHeader><CardTitle>Disbursement & Dates</CardTitle></CardHeader>
            <CardContent>
              <InfoGrid cols={1}>
                <InfoRow label="Disbursement Method" value={l.disbursementMethod} />
                <InfoRow label="Disbursed Amount"    value={formatCurrency(l.disbursedAmount)} />
                <InfoRow label="Net Disbursed"       value={formatCurrency(l.netDisbursedAmount)} />
                <InfoRow label="Disbursed On"        value={fmtDate(l.disbursedAt)} />
                <InfoRow label="First Due Date"      value={fmtDate(l.firstDueDate)} />
                <InfoRow label="Next Due Date"       value={fmtDate(l.nextDueDate)} />
                <InfoRow label="Maturity Date"       value={fmtDate(l.maturityDate)} />
                <InfoRow label="Approved On"         value={fmtDate(l.approvedAt)} />
              </InfoGrid>
            </CardContent>
          </Card>
        </div>
      )}

      {/* ══════════════════════════════════════════════════════════════════════
          TAB: STATEMENT
      ══════════════════════════════════════════════════════════════════════ */}
      {tab === 'statement' && (
        <Card>
          <CardHeader>
            <CardTitle>Loan Account Statement</CardTitle>
            <Button size="sm" variant="outline" icon={<Printer className="w-4 h-4" />}
              onClick={() => printWindow('loan-statement-print', `Statement — ${l.loanRef}`)}>
              Print
            </Button>
          </CardHeader>
          <div id="loan-statement-print">
            {/* Print header */}
            <div className="px-6 py-3 bg-muted/20 border-b text-sm grid grid-cols-2 gap-2">
              <div className="space-y-0.5">
                <p><span className="text-muted-foreground">Member:</span> <strong>{l.member?.fullName}</strong></p>
                <p><span className="text-muted-foreground">Loan Ref:</span> <strong className="font-mono">{l.loanRef}</strong></p>
              </div>
              <div className="space-y-0.5">
                <p><span className="text-muted-foreground">Outstanding:</span> <strong className="text-amber-600">{formatCurrency(trueOutstanding)}</strong></p>
                <p><span className="text-muted-foreground">Status:</span> {l.status.replace(/_/g, ' ')}</p>
              </div>
            </div>

            <div className="overflow-x-auto">
              <table className="table-lms w-full text-sm">
                <thead>
                  <tr>
                    <th>Date</th><th>Description</th><th>Reference</th>
                    <th className="text-right">Debit</th>
                    <th className="text-right">Credit</th>
                    <th className="text-right">Balance</th>
                  </tr>
                </thead>
                <tbody>
                  {statementEntries.length === 0 ? (
                    <tr><td colSpan={6} className="text-center py-8 text-muted-foreground">No transactions yet</td></tr>
                  ) : (
                    statementEntries.map((e, i) => (
                      <tr key={i} className={e.type === 'DISBURSEMENT' ? 'bg-blue-50/50 font-medium' : ''}>
                        <td className="font-mono text-xs">{fmtDate(e.date)}</td>
                        <td>
                          <p>{e.description}</p>
                          {e.type === 'REPAYMENT' && (
                            <p className="text-xs text-muted-foreground">
                              P:{formatCurrency(e.principalPaid)} I:{formatCurrency(e.interestPaid)}
                              {e.penaltiesPaid > 0 && ` Pen:${formatCurrency(e.penaltiesPaid)}`}
                            </p>
                          )}
                        </td>
                        <td className="font-mono text-xs text-muted-foreground">{e.reference}</td>
                        <td className="text-right font-mono">{e.debit  > 0 ? formatCurrency(e.debit)  : '—'}</td>
                        <td className="text-right font-mono text-green-600">{e.credit > 0 ? formatCurrency(e.credit) : '—'}</td>
                        <td className="text-right font-mono font-semibold">{formatCurrency(e.balance)}</td>
                      </tr>
                    ))
                  )}
                </tbody>
                {statementEntries.length > 0 && (
                  <tfoot>
                    <tr className="border-t-2 font-semibold bg-muted/30">
                      <td colSpan={3} className="py-2 px-4 text-right">TOTALS</td>
                      <td className="text-right font-mono py-2 px-4">
                        {formatCurrency(statementEntries.reduce((s, e) => s + e.debit,  0))}
                      </td>
                      <td className="text-right font-mono py-2 px-4 text-green-600">
                        {formatCurrency(statementEntries.reduce((s, e) => s + e.credit, 0))}
                      </td>
                      <td className="text-right font-mono py-2 px-4 text-amber-600">
                        {formatCurrency(l.outstandingPrincipal)}
                      </td>
                    </tr>
                  </tfoot>
                )}
              </table>
            </div>
          </div>
        </Card>
      )}

      {/* ══════════════════════════════════════════════════════════════════════
          TAB: SCHEDULE
      ══════════════════════════════════════════════════════════════════════ */}
      {tab === 'schedule' && (
        <Card>
          <CardHeader>
            <CardTitle>Amortisation Schedule</CardTitle>
            <Button size="sm" variant="outline" icon={<Printer className="w-4 h-4" />}
              onClick={() => printWindow('loan-schedule-print', `Schedule — ${l.loanRef}`)}>
              Print
            </Button>
          </CardHeader>
          <div id="loan-schedule-print">
            <div className="overflow-x-auto">
              <table className="table-lms w-full">
                <thead>
                  <tr>
                    <th>#</th><th>Due Date</th><th>Opening</th><th>Principal</th>
                    <th>Interest</th><th>Total Due</th><th>Paid</th><th>Closing</th><th>Status</th>
                  </tr>
                </thead>
                <tbody>
                  {!l.schedule?.length ? (
                    <tr><td colSpan={9} className="text-center py-8 text-muted-foreground">No schedule generated</td></tr>
                  ) : (
                    l.schedule.map((s: any) => (
                      <tr key={s.id} className={s.isOverdue ? 'bg-red-50/50' : s.isPaid ? 'opacity-60' : ''}>
                        <td className="text-center text-xs text-muted-foreground">{s.instalmentNo}</td>
                        <td className="font-mono text-xs">{fmtDate(s.dueDate)}</td>
                        <td><Amount value={s.openingBalance} size="sm" /></td>
                        <td><Amount value={s.principalDue}   size="sm" /></td>
                        <td><Amount value={s.interestDue}    size="sm" /></td>
                        <td className="font-semibold"><Amount value={s.totalDue} size="sm" /></td>
                        <td>
                          <Amount value={s.totalPaid} size="sm"
                            className={parseFloat(s.totalPaid) >= parseFloat(s.totalDue) ? 'text-green-600' : ''} />
                        </td>
                        <td><Amount value={s.closingBalance} size="sm" /></td>
                        <td>
                          {s.isPaid
                            ? <Badge variant="success">PAID</Badge>
                            : s.isOverdue
                              ? <Badge variant="danger">OVERDUE {s.daysOverdue}d</Badge>
                              : <Badge variant="default">PENDING</Badge>}
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
                {l.schedule?.length > 0 && (
                  <tfoot>
                    <tr className="border-t-2 font-semibold bg-muted/30">
                      <td colSpan={3} className="py-2 px-4 text-right text-xs">TOTALS</td>
                      <td className="px-4 font-mono text-sm">
                        {formatCurrency(l.schedule.reduce((s: number, r: any) => s + parseFloat(r.principalDue ?? 0), 0))}
                      </td>
                      <td className="px-4 font-mono text-sm">
                        {formatCurrency(l.schedule.reduce((s: number, r: any) => s + parseFloat(r.interestDue  ?? 0), 0))}
                      </td>
                      <td className="px-4 font-mono text-sm">
                        {formatCurrency(l.schedule.reduce((s: number, r: any) => s + parseFloat(r.totalDue     ?? 0), 0))}
                      </td>
                      <td colSpan={3} />
                    </tr>
                  </tfoot>
                )}
              </table>
            </div>
          </div>
        </Card>
      )}

      {/* ══════════════════════════════════════════════════════════════════════
          TAB: REPAYMENTS
      ══════════════════════════════════════════════════════════════════════ */}
      {tab === 'repayments' && (
        <Card>
          <CardHeader>
            <CardTitle>Repayment History</CardTitle>
            {canRepay && (
              <Button size="sm" icon={<Plus className="w-4 h-4" />} onClick={() => setRepayModal(true)}>
                Record Payment
              </Button>
            )}
          </CardHeader>
          <div className="overflow-x-auto">
            <table className="table-lms w-full">
              <thead>
                <tr>
                  <th>Receipt</th><th>Amount</th><th>Principal</th><th>Interest</th>
                  <th>Penalties</th><th>Excess</th><th>Method</th><th>Date</th>
                </tr>
              </thead>
              <tbody>
                {!l.repayments?.length ? (
                  <tr><td colSpan={8} className="text-center py-8 text-muted-foreground">No repayments recorded</td></tr>
                ) : (
                  l.repayments.map((r: any) => (
                    <tr key={r.id} className={r.isReversed ? 'opacity-50 line-through' : ''}>
                      <td className="font-mono text-xs">{r.receiptNo}</td>
                      <td><Amount value={r.amount}        size="sm" className="text-green-600" /></td>
                      <td><Amount value={r.principalPaid} size="sm" /></td>
                      <td><Amount value={r.interestPaid}  size="sm" /></td>
                      <td><Amount value={r.penaltiesPaid} size="sm" /></td>
                      <td>
                        <Amount value={r.excessAmount} size="sm"
                          className={parseFloat(r.excessAmount ?? 0) > 0 ? 'text-blue-600' : ''} />
                      </td>
                      <td><Badge variant="default">{r.method}</Badge></td>
                      <td className="text-xs text-muted-foreground">{fmtDate(r.paymentDate)}</td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </Card>
      )}

      {/* ══════════════════════════════════════════════════════════════════════
          TAB: APPRAISAL — includes "Appraised By" for each record
      ══════════════════════════════════════════════════════════════════════ */}
      {tab === 'appraisal' && (
        <Card>
          <CardHeader>
            <CardTitle>Loan Appraisal</CardTitle>
            {canAppraise && (
              <Button size="sm" icon={<Plus className="w-4 h-4" />} onClick={() => setAppraisalModal(true)}>
                {l.appraisals?.length > 0 ? 'Update Appraisal' : 'Add Appraisal'}
              </Button>
            )}
          </CardHeader>
          <CardContent>
            {!l.appraisals?.length ? (
              <div className="py-8 text-center text-muted-foreground">
                <ClipboardList className="w-8 h-8 mx-auto mb-2 opacity-40" />
                <p>No appraisal recorded yet.</p>
                {canAppraise && (
                  <Button size="sm" className="mt-3" onClick={() => setAppraisalModal(true)}>
                    Start Appraisal
                  </Button>
                )}
              </div>
            ) : (
              <div className="space-y-4">
                {l.appraisals.map((a: any, idx: number) => {
                  // Resolve appraiser name — from API enrichment or local map
                  const appraiserName = a.appraiserName
                    ?? appraisalUserMap.get(a.appraisedById)
                    ?? null

                  return (
                    <div key={a.id} className="border rounded-lg p-4">
                      {/* Header row: recommendation badge + score + appraiser */}
                      <div className="flex items-start justify-between mb-3 flex-wrap gap-2">
                        <div>
                          <div className="flex items-center gap-2 flex-wrap">
                            <Badge variant={
                              a.recommendation === 'APPROVE' ? 'success'
                              : a.recommendation === 'DECLINE' ? 'danger' : 'warning'
                            }>
                              {a.recommendation ?? 'PENDING'}
                            </Badge>
                            {idx === 0 && (
                              <Badge variant="info" className="text-xs">Latest</Badge>
                            )}
                          </div>
                          {/* ── Appraised By ── */}
                          <p className="text-xs text-muted-foreground mt-1">
                            Appraised by:{' '}
                            <span className="font-medium text-foreground">
                              {appraiserName ?? a.appraisedById?.slice(0, 8) ?? '—'}
                            </span>
                            {' · '}{fmtDateTime(a.appraisedAt)}
                          </p>
                        </div>

                        {a.totalScore != null && (
                          <div className="text-right">
                            <p className="text-2xl font-bold leading-none">
                              {a.totalScore}
                              <span className="text-sm text-muted-foreground font-normal">
                                /{a.maxScore ?? 100}
                              </span>
                            </p>
                            {a.scorePercentage != null && (
                              <p className="text-xs text-muted-foreground">
                                {parseFloat(a.scorePercentage).toFixed(1)}%
                              </p>
                            )}
                          </div>
                        )}
                      </div>

                      {/* Detail rows */}
                      <InfoGrid cols={2}>
                        {a.approvedAmount && (
                          <InfoRow label="Recommended Amount" value={formatCurrency(a.approvedAmount)} />
                        )}
                        {a.approvedTenor && (
                          <InfoRow label="Recommended Tenor"  value={`${a.approvedTenor} months`} />
                        )}
                        <InfoRow label="Income Verified"  value={a.incomeVerified  ? '✓ Yes' : '✗ No'} />
                        <InfoRow label="Business Visited" value={a.businessVisited ? '✓ Yes' : '✗ No'} />
                        {a.visitDate && <InfoRow label="Visit Date"  value={fmtDate(a.visitDate)} />}
                        {a.visitNotes && <InfoRow label="Visit Notes" value={a.visitNotes} />}
                      </InfoGrid>

                      {a.notes && (
                        <p className="text-sm mt-3 text-muted-foreground border-t pt-2">{a.notes}</p>
                      )}
                    </div>
                  )
                })}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* ══════════════════════════════════════════════════════════════════════
          TAB: TOP-UPS
      ══════════════════════════════════════════════════════════════════════ */}
      {tab === 'topups' && (
        <Card>
          <CardHeader>
            <CardTitle>Loan Top-Ups</CardTitle>
            {l.status === 'ACTIVE' && (
              <Button size="sm" icon={<TrendingUp className="w-4 h-4" />} onClick={() => setTopupModal(true)}>
                Request Top-Up
              </Button>
            )}
          </CardHeader>
          <CardContent>
            {!l.topUps?.length ? (
              <div className="py-8 text-center text-muted-foreground">
                <TrendingUp className="w-8 h-8 mx-auto mb-2 opacity-40" />
                <p>No top-ups requested.</p>
              </div>
            ) : (
              <div className="space-y-3">
                {l.topUps.map((t: any) => (
                  <div key={t.id} className="border rounded-lg p-4 flex justify-between items-start">
                    <div>
                      <p className="font-medium">{t.topUpType?.replace(/_/g, ' ')}</p>
                      <p className="text-sm text-muted-foreground">{t.reason}</p>
                      {t.requestedAmount && (
                        <p className="text-sm mt-1">
                          Requested: <Amount value={t.requestedAmount} size="sm" />
                        </p>
                      )}
                      {t.outstandingAtTopUp && (
                        <p className="text-xs text-muted-foreground mt-0.5">
                          Outstanding at request: {formatCurrency(t.outstandingAtTopUp)}
                        </p>
                      )}
                    </div>
                    <div className="text-right">
                      <Badge variant={
                        t.approvalStatus === 'APPROVED' ? 'success'
                        : t.approvalStatus === 'DECLINED' ? 'danger' : 'warning'
                      }>
                        {t.approvalStatus}
                      </Badge>
                      <p className="text-xs text-muted-foreground mt-1">{fmtDate(t.createdAt)}</p>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* ══════════════════════════════════════════════════════════════════════
          TAB: COLLATERAL
      ══════════════════════════════════════════════════════════════════════ */}
      {tab === 'collateral' && (
        <Card>
          <CardHeader>
            <CardTitle>Collateral Register</CardTitle>
            {l.status !== 'CLOSED' && (
              <Button variant="outline" size="sm" icon={<Plus className="w-4 h-4" />}
                onClick={() => setCollateralModal(true)}>
                Add Collateral
              </Button>
            )}
          </CardHeader>
          <CardContent>
            {!l.collaterals?.length ? (
              <p className="text-sm text-center py-8 text-muted-foreground">No collateral recorded.</p>
            ) : (
              <div className="space-y-3">
                {l.collaterals.map((c: any) => (
                  <div key={c.id} className="border rounded-lg p-4">
                    <div className="flex items-start justify-between">
                      <div>
                        <p className="font-medium">{c.collateralType?.replace(/_/g, ' ')}</p>
                        <p className="text-sm text-muted-foreground">{c.description}</p>
                        {c.registrationNo && (
                          <p className="text-xs text-muted-foreground">Reg: {c.registrationNo}</p>
                        )}
                      </div>
                      <Badge variant={c.status === 'ACTIVE' ? 'success' : 'default'}>{c.status}</Badge>
                    </div>
                    <div className="grid grid-cols-3 gap-4 mt-3 pt-3 border-t text-sm">
                      <div><p className="text-xs text-muted-foreground">Est. Value</p><Amount value={c.estimatedValue} /></div>
                      <div><p className="text-xs text-muted-foreground">FSV</p><Amount value={c.forcedSaleValue} /></div>
                      <div><p className="text-xs text-muted-foreground">Location</p><p className="font-medium text-xs">{c.location ?? '—'}</p></div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* ══════════════════════════════════════════════════════════════════════
          TAB: GUARANTORS
      ══════════════════════════════════════════════════════════════════════ */}
      {tab === 'guarantors' && (
        <Card>
          <CardHeader>
            <CardTitle>Guarantors</CardTitle>
            {l.status !== 'CLOSED' && (
              <Button variant="outline" size="sm" icon={<Plus className="w-4 h-4" />}
                onClick={() => setGuarantorModal(true)}>
                Add Guarantor
              </Button>
            )}
          </CardHeader>
          <CardContent>
            {!l.guarantors?.length ? (
              <p className="text-sm text-center py-8 text-muted-foreground">No guarantors added.</p>
            ) : (
              <div className="space-y-3">
                {l.guarantors.map((g: any) => (
                  <div key={g.id} className="border rounded-lg p-4 flex items-start justify-between">
                    <div>
                      <p className="font-medium">{g.member?.fullName ?? g.nonMemberName}</p>
                      <p className="text-sm text-muted-foreground">
                        {g.member?.memberNo ?? 'Non-member'} · {g.member?.phone ?? g.nonMemberPhone}
                      </p>
                      <p className="text-xs mt-1">
                        Guarantee: <Amount value={g.guaranteeAmount} size="sm" />
                      </p>
                    </div>
                    <Badge variant={
                      g.status === 'CONSENTED' ? 'success'
                      : g.status === 'DECLINED' ? 'danger' : 'warning'
                    }>
                      {g.status}
                    </Badge>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* ══════════════════════════════════════════════════════════════════════
          TAB: APPROVALS
      ══════════════════════════════════════════════════════════════════════ */}
      {tab === 'approvals' && (
        <Card>
          <CardHeader><CardTitle>Approval Workflow</CardTitle></CardHeader>
          <CardContent>
            <div className="space-y-3">
              {l.approvals?.map((a: any) => (
                <div key={a.id} className={cn('border rounded-lg p-4',
                  a.status === 'APPROVED' ? 'border-green-200 bg-green-50/50 dark:bg-green-900/10'
                  : a.status === 'DECLINED' ? 'border-red-200 bg-red-50/50 dark:bg-red-900/10'
                  : a.status === 'RETURNED' ? 'border-amber-200 bg-amber-50/50 dark:bg-amber-900/10'
                  : 'border-blue-200 bg-blue-50/50 dark:bg-blue-900/10'
                )}>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <div className={cn(
                        'w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold text-white',
                        a.status === 'APPROVED' ? 'bg-green-500'
                        : a.status === 'DECLINED' ? 'bg-red-500'
                        : a.status === 'RETURNED' ? 'bg-amber-500' : 'bg-blue-500'
                      )}>
                        L{a.level}
                      </div>
                      <div>
                        <p className="font-medium text-sm">Level {a.level} Approval</p>
                        {a.comments && (
                          <p className="text-xs text-muted-foreground mt-0.5">{a.comments}</p>
                        )}
                      </div>
                    </div>
                    <div className="text-right">
                      <Badge variant={
                        a.status === 'APPROVED' ? 'success'
                        : a.status === 'DECLINED' ? 'danger'
                        : a.status === 'RETURNED' ? 'warning' : 'default'
                      }>
                        {a.status}
                      </Badge>
                      {a.decidedAt && (
                        <p className="text-xs text-muted-foreground mt-1">{fmtDateTime(a.decidedAt)}</p>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>

            {pendingApproval && (
              <div className="mt-4 pt-4 border-t flex gap-2 flex-wrap">
                <Button icon={<CheckCircle2 className="w-4 h-4" />}
                  onClick={() => {
                    setApproveForm(f => ({ ...f, action: 'APPROVE', level: pendingApproval.level }))
                    setApproveModal(true)
                  }}>
                  Approve
                </Button>
                <Button variant="outline" icon={<RotateCcw className="w-4 h-4" />}
                  onClick={() => {
                    setApproveForm(f => ({ ...f, action: 'RETURN', level: pendingApproval.level }))
                    setApproveModal(true)
                  }}>
                  Return for Correction
                </Button>
                <Button variant="destructive" icon={<XCircle className="w-4 h-4" />}
                  onClick={() => {
                    setApproveForm(f => ({ ...f, action: 'DECLINE', level: pendingApproval.level }))
                    setApproveModal(true)
                  }}>
                  Decline
                </Button>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* ══════════════════════════════════════════════════════════════════════
          TAB: COLLECTIONS
      ══════════════════════════════════════════════════════════════════════ */}
      {tab === 'collections' && (
        <Card>
          <CardHeader>
            <CardTitle>Collection Activities</CardTitle>
            <Button variant="outline" size="sm" icon={<Plus className="w-4 h-4" />}
              onClick={() => setActivityModal(true)}>
              Log Activity
            </Button>
          </CardHeader>
          <CardContent>
            {!l.collectionActivities?.length ? (
              <p className="text-sm text-center py-8 text-muted-foreground">No collection activities recorded.</p>
            ) : (
              <div className="space-y-3">
                {l.collectionActivities.map((a: any) => (
                  <div key={a.id} className="border-l-2 border-primary/40 pl-4 py-1">
                    <div className="flex items-center justify-between">
                      <Badge variant="info">{a.actionType?.replace(/_/g, ' ')}</Badge>
                      <p className="text-xs text-muted-foreground">{fmtDateTime(a.createdAt)}</p>
                    </div>
                    <p className="text-sm mt-1">{a.notes}</p>
                    {a.outcome && (
                      <p className="text-xs text-green-600 mt-0.5">Outcome: {a.outcome}</p>
                    )}
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* ══════════════════════════════════════════════════════════════════════
          TAB: HISTORY
      ══════════════════════════════════════════════════════════════════════ */}
      {tab === 'history' && (
        <Card>
          <CardHeader><CardTitle>Status History</CardTitle></CardHeader>
          <CardContent>
            <div className="relative pl-4">
              <div className="absolute left-0 top-2 bottom-2 w-0.5 bg-border" />
              <div className="space-y-4">
                {l.statusHistory?.map((h: any) => (
                  <div key={h.id} className="relative">
                    <div className="absolute -left-5 top-1 w-2.5 h-2.5 rounded-full bg-primary border-2 border-background" />
                    <div className="flex items-start justify-between">
                      <div>
                        <div className="flex items-center gap-2">
                          {h.previousStatus && (
                            <span className="text-xs text-muted-foreground">
                              {h.previousStatus.replace(/_/g, ' ')} →
                            </span>
                          )}
                          <StatusBadge status={h.newStatus} type="loan" />
                        </div>
                        {h.reason && (
                          <p className="text-sm text-muted-foreground mt-0.5">{h.reason}</p>
                        )}
                      </div>
                      <p className="text-xs text-muted-foreground shrink-0">{fmtDate(h.changedAt)}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* ══════════════════════════════════════════════════════════════════════
          MODALS
      ══════════════════════════════════════════════════════════════════════ */}

      {/* ── Repayment Modal ── */}
      <Modal open={repayModal} onClose={() => setRepayModal(false)} title="Record Repayment"
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setRepayModal(false)}>Cancel</Button>
            <Button size="sm" loading={actionMutation.isPending}
              onClick={() => {
                const payAmount = parseFloat(repayForm.amount) || 0
                const outstanding = parseFloat(l.outstandingPrincipal ?? 0)
                const firstUnpaid = (l.schedule ?? []).find((s: any) => !s.isPaid)
                const payDate = new Date(repayForm.paymentDate)
                const isEarlyFullRepay = firstUnpaid && payAmount >= outstanding && payDate < new Date(firstUnpaid.dueDate)
                if (isEarlyFullRepay && !repayForm.useInterestOverride) {
                  const oneMonthInterest = outstanding * (parseFloat(l.interestRate ?? 0) / 100)
                  setRepayModal(false)
                  setEarlyRepayInfo({ amount: payAmount, oneMonthInterest })
                  return
                }
                const payload: any = {
                  action: 'REPAY',
                  amount: payAmount,
                  method: repayForm.method,
                  reference: repayForm.reference,
                  paymentDate: repayForm.paymentDate,
                  bankAccountCode: METHOD_GL[repayForm.method] ?? '1102',
                }
                if (repayForm.excessSavingsAccountId) payload.excessSavingsAccountId = repayForm.excessSavingsAccountId
                if (repayForm.useInterestOverride && repayForm.interestOverride !== '') {
                  payload.interestOverride = parseFloat(repayForm.interestOverride)
                }
                actionMutation.mutate(payload)
              }}>
              Record Payment
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Alert variant="info">
            <div className="grid grid-cols-2 gap-x-4 text-sm">
              <span className="text-muted-foreground">Outstanding Principal</span>
              <span className="font-semibold">{formatCurrency(l.outstandingPrincipal)}</span>
              <span className="text-muted-foreground">Accrued Interest</span>
              <span className="font-semibold">{formatCurrency(l.accruedInterest)}</span>
              {accruedPenalties > 0 && (
                <>
                  <span className="text-muted-foreground">Penalties</span>
                  <span className="font-semibold text-red-600">{formatCurrency(l.accruedPenalties)}</span>
                </>
              )}
              <span className="text-muted-foreground font-medium border-t pt-1">Total Outstanding</span>
              <span className="font-bold border-t pt-1">{formatCurrency(trueOutstanding)}</span>
            </div>
          </Alert>
          <Input label="Payment Amount (KES)" required type="number" min={1}
            value={repayForm.amount}
            onChange={e => setRepayForm(f => ({ ...f, amount: e.target.value }))} />
          <Select label="Payment Method" required value={repayForm.method}
            onChange={e => setRepayForm(f => ({ ...f, method: e.target.value }))}
            options={[
              { value: 'CASH',          label: 'Cash'          },
              { value: 'MPESA',         label: 'M-Pesa'        },
              { value: 'BANK_TRANSFER', label: 'Bank Transfer'  },
              { value: 'CHEQUE',        label: 'Cheque'         },
              { value: 'EFT',           label: 'EFT / RTGS'    },
            ]} />
          <p className="text-xs text-muted-foreground">
            GL: <span className="font-mono">{METHOD_GL[repayForm.method] ?? '1102'}</span>{' '}
            ({METHOD_GL_LABEL[METHOD_GL[repayForm.method]] ?? 'Bank - Equity'})
          </p>
          {(() => {
            const payAmount = parseFloat(repayForm.amount) || 0
            const potentialExcess = Math.max(0, payAmount - trueOutstanding)
            return potentialExcess > 0 && (
              <div>
                <Select label="Deposit Excess To" required value={repayForm.excessSavingsAccountId}
                  onChange={e => setRepayForm(f => ({ ...f, excessSavingsAccountId: e.target.value }))}
                  options={(l.member?.savingsAccounts ?? []).filter((a: any) => ['FOSA_CURRENT','FOSA_SAVINGS','BOSA_SAVINGS','BOSA_SPECIAL'].includes(a.accountType) && a.isActive)
                    .map((a: any) => ({ value: a.id, label: `${a.accountNo} (${a.accountType?.replace(/_/g,' ')} — ${formatCurrency(a.balance)})` }))}
                />
                <p className="text-xs text-amber-600 font-medium mt-1">
                  Payment exceeds outstanding by {formatCurrency(potentialExcess)}. Select a savings account to receive the excess.
                </p>
              </div>
            )
          })()}
          <Input label="Payment Reference" value={repayForm.reference}
            onChange={e => setRepayForm(f => ({ ...f, reference: e.target.value }))}
            placeholder="M-Pesa ref, bank ref…" />
          <Input label="Payment Date" type="date" required value={repayForm.paymentDate}
            onChange={e => setRepayForm(f => ({ ...f, paymentDate: e.target.value }))} />
          <div className="border rounded-lg p-3 bg-muted/20 space-y-2">
            <label className="flex items-center gap-2 cursor-pointer">
              <input type="checkbox" className="rounded"
                checked={repayForm.useInterestOverride}
                onChange={e => setRepayForm(f => ({
                  ...f,
                  useInterestOverride: e.target.checked,
                  interestOverride:    e.target.checked ? String(accruedInterest > 0 ? accruedInterest : '') : '',
                }))} />
              <span className="text-sm font-medium">Override interest amount (waiver / early settlement)</span>
            </label>
            {repayForm.useInterestOverride && (
              <>
                <Input label="Interest to Recover (KES)" type="number" min={0} step="0.01"
                  value={repayForm.interestOverride}
                  onChange={e => setRepayForm(f => ({ ...f, interestOverride: e.target.value }))}
                  placeholder={String(accruedInterest)} />
                {repayForm.interestOverride !== '' && parseFloat(repayForm.interestOverride) < accruedInterest && (
                  <Alert variant="warning">
                    Waiving {formatCurrency(accruedInterest - parseFloat(repayForm.interestOverride))} of interest.
                    Ensure this is authorised per your waiver policy.
                  </Alert>
                )}
              </>
            )}
          </div>
          <p className="text-xs text-muted-foreground">
            Any excess payment after all allocations will be credited to the member's FOSA account.
          </p>
        </div>
      </Modal>

      {/* ── Early Repayment Confirmation ── */}
      <Modal open={!!earlyRepayInfo} onClose={() => setEarlyRepayInfo(null)} title="Early Repayment" size="md">
        <div className="space-y-4">
          <Alert variant="warning" title="⚠️ Early loan repayment">
            <p className="text-sm">This loan is being repaid before the first installment due date.</p>
          </Alert>
          {earlyRepayInfo && (
            <div className="border rounded-lg p-4 space-y-2 bg-muted/20">
              <div className="flex justify-between text-sm">
                <span className="text-muted-foreground">Payment Amount</span>
                <span className="font-semibold">{formatCurrency(earlyRepayInfo.amount)}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-muted-foreground">Outstanding Principal</span>
                <span className="font-semibold">{formatCurrency(l.outstandingPrincipal)}</span>
              </div>
              <div className="flex justify-between text-sm border-t pt-2">
                <span className="font-medium">Suggested 1 Month Interest</span>
                <span className="font-semibold text-amber-600">{formatCurrency(earlyRepayInfo.oneMonthInterest)}</span>
              </div>
            </div>
          )}
          <p className="text-sm text-muted-foreground">
            Would you like to charge one month&apos;s interest of <strong>{formatCurrency(earlyRepayInfo?.oneMonthInterest ?? 0)}</strong> for this early settlement?
          </p>
          <div className="flex justify-end gap-3 pt-2">
            <Button variant="outline" onClick={() => {
              setEarlyRepayInfo(null)
              const payAmount = parseFloat(repayForm.amount) || 0
              actionMutation.mutate({
                action: 'REPAY', amount: payAmount,
                method: repayForm.method, reference: repayForm.reference,
                paymentDate: repayForm.paymentDate,
                bankAccountCode: METHOD_GL[repayForm.method] ?? '1102',
                ...(repayForm.excessSavingsAccountId ? { excessSavingsAccountId: repayForm.excessSavingsAccountId } : {}),
              })
            }}>
              No, proceed without
            </Button>
            <Button onClick={() => {
              setEarlyRepayInfo(null)
              const autoExcess = repayForm.excessSavingsAccountId ||
                (l.member?.savingsAccounts ?? []).find((a: any) =>
                  ['FOSA_CURRENT','FOSA_SAVINGS','BOSA_SAVINGS'].includes(a.accountType) && a.isActive
                )?.id
              actionMutation.mutate({
                action: 'REPAY', amount: parseFloat(repayForm.amount) || 0,
                method: repayForm.method, reference: repayForm.reference,
                paymentDate: repayForm.paymentDate,
                bankAccountCode: METHOD_GL[repayForm.method] ?? '1102',
                chargeEarlyInterest: true,
                excessSavingsAccountId: autoExcess,
              })
            }}>
              Yes, charge {formatCurrency(earlyRepayInfo?.oneMonthInterest ?? 0)}
            </Button>
          </div>
        </div>
      </Modal>

      {/* ── Approve / Decline / Return Modal ── */}
      <Modal open={approveModal} onClose={() => setApproveModal(false)}
        title={`${approveForm.action === 'APPROVE' ? 'Approve' : approveForm.action === 'DECLINE' ? 'Decline' : 'Return'} Loan — Level ${approveForm.level}`}
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setApproveModal(false)}>Cancel</Button>
            <Button
              variant={approveForm.action === 'APPROVE' ? 'success' : approveForm.action === 'DECLINE' ? 'destructive' : 'outline'}
              size="sm"
              loading={actionMutation.isPending}
              onClick={() => actionMutation.mutate({
                action:   approveForm.action,
                level:    approveForm.level,
                comments: approveForm.comments,
              })}>
              {approveForm.action === 'APPROVE' ? 'Approve Loan'
               : approveForm.action === 'DECLINE' ? 'Decline Loan'
               : 'Return for Correction'}
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Alert variant={approveForm.action === 'APPROVE' ? 'success' : approveForm.action === 'DECLINE' ? 'error' : 'warning'}>
            {approveForm.action === 'RETURN'
              ? 'Loan will be returned to the officer for correction. The officer must edit and resubmit.'
              : <><strong>{approveForm.action}</strong> — {l.loanRef} for <strong>{l.member?.fullName}</strong> — <strong>{formatCurrency(l.principalAmount)}</strong></>
            }
          </Alert>
          <Textarea label="Comments / Reason" required
            value={approveForm.comments}
            onChange={e => setApproveForm(f => ({ ...f, comments: e.target.value }))}
            placeholder={
              approveForm.action === 'RETURN' ? 'State what needs to be corrected…'
              : approveForm.action === 'DECLINE' ? 'State the reason for declining…'
              : 'Add any conditions or notes…'
            } />
        </div>
      </Modal>

      {/* ── Disburse Modal ── */}
      <Modal open={disburseModal} onClose={() => setDisburseModal(false)}
        title={`Disburse — ${l.loanRef}`}
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setDisburseModal(false)}>Cancel</Button>
            <Button variant="success" size="sm" loading={actionMutation.isPending}
              onClick={() => actionMutation.mutate({
                action:                'DISBURSE',
                disbursementMethod:    disburseForm.disbursementMethod,
                disbursementReference: disburseForm.disbursementReference,
                bankAccountCode:       METHOD_GL[disburseForm.disbursementMethod] ?? '1102',
              })}>
              Confirm Disbursement
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Alert variant="warning">
            Disburse <strong>{formatCurrency(l.principalAmount)}</strong> to{' '}
            <strong>{l.member?.fullName}</strong>. This action cannot be undone.
          </Alert>
          <Select label="Disbursement Method" required
            value={disburseForm.disbursementMethod}
            onChange={e => setDisburseForm(f => ({ ...f, disbursementMethod: e.target.value }))}
            options={[
              { value: 'BANK_TRANSFER', label: 'Bank Transfer' },
              { value: 'MPESA',         label: 'M-Pesa'        },
              { value: 'CASH',          label: 'Cash'          },
              { value: 'CHEQUE',        label: 'Cheque'        },
              { value: 'EFT',           label: 'EFT / RTGS'   },
            ]} />
          <p className="text-xs text-muted-foreground">
            GL: <span className="font-mono">{METHOD_GL[disburseForm.disbursementMethod] ?? '1102'}</span>{' '}
            ({METHOD_GL_LABEL[METHOD_GL[disburseForm.disbursementMethod]] ?? 'Bank - Equity'})
          </p>
          <Input label="Reference / Transaction ID"
            value={disburseForm.disbursementReference}
            onChange={e => setDisburseForm(f => ({ ...f, disbursementReference: e.target.value }))}
            placeholder="Bank ref, M-Pesa confirmation, cheque no…" />
        </div>
      </Modal>

      {/* ── Appraisal Modal ── */}
      <Modal open={appraisalModal} onClose={() => setAppraisalModal(false)} title="Loan Appraisal"
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setAppraisalModal(false)}>Cancel</Button>
            <Button size="sm" loading={actionMutation.isPending}
              onClick={() => actionMutation.mutate({
                action:          'APPRAISE',
                totalScore:      appraisalForm.totalScore ? parseInt(appraisalForm.totalScore) : undefined,
                maxScore:        parseInt(appraisalForm.maxScore || '100'),
                recommendation:  appraisalForm.recommendation,
                notes:           appraisalForm.notes,
                approvedAmount:  appraisalForm.approvedAmount ? parseFloat(appraisalForm.approvedAmount) : undefined,
                incomeVerified:  appraisalForm.incomeVerified,
                businessVisited: appraisalForm.businessVisited,
                visitDate:       appraisalForm.visitDate  || undefined,
                visitNotes:      appraisalForm.visitNotes || undefined,
              })}>
              Save Appraisal
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <FormGrid cols={2}>
            <Input label="Score" type="number" min={0}
              value={appraisalForm.totalScore}
              onChange={e => setAppraisalForm(f => ({ ...f, totalScore: e.target.value }))}
              placeholder="e.g. 75" />
            <Input label="Max Score" type="number" min={0}
              value={appraisalForm.maxScore}
              onChange={e => setAppraisalForm(f => ({ ...f, maxScore: e.target.value }))} />
            <Select label="Recommendation"
              value={appraisalForm.recommendation}
              onChange={e => setAppraisalForm(f => ({ ...f, recommendation: e.target.value }))}
              options={[
                { value: 'APPROVE', label: 'Recommend Approval' },
                { value: 'DECLINE', label: 'Recommend Decline'  },
                { value: 'REVIEW',  label: 'Needs Further Review'},
              ]} />
            <Input label="Recommended Amount (KES)" type="number"
              value={appraisalForm.approvedAmount}
              onChange={e => setAppraisalForm(f => ({ ...f, approvedAmount: e.target.value }))}
              placeholder="Leave blank = requested amount" />
          </FormGrid>
          <div className="grid grid-cols-2 gap-3">
            <label className="flex items-center gap-2 cursor-pointer">
              <input type="checkbox" className="rounded"
                checked={appraisalForm.incomeVerified}
                onChange={e => setAppraisalForm(f => ({ ...f, incomeVerified: e.target.checked }))} />
              <span className="text-sm">Income Verified</span>
            </label>
            <label className="flex items-center gap-2 cursor-pointer">
              <input type="checkbox" className="rounded"
                checked={appraisalForm.businessVisited}
                onChange={e => setAppraisalForm(f => ({ ...f, businessVisited: e.target.checked }))} />
              <span className="text-sm">Business Visited</span>
            </label>
          </div>
          {appraisalForm.businessVisited && (
            <FormGrid cols={2}>
              <Input label="Visit Date" type="date"
                value={appraisalForm.visitDate}
                onChange={e => setAppraisalForm(f => ({ ...f, visitDate: e.target.value }))} />
              <Input label="Visit Notes"
                value={appraisalForm.visitNotes}
                onChange={e => setAppraisalForm(f => ({ ...f, visitNotes: e.target.value }))} />
            </FormGrid>
          )}
          <div>
            <label className="text-sm font-medium">Appraisal Notes</label>
            <textarea rows={3}
              className="mt-1 w-full border rounded-md px-3 py-2 text-sm resize-none focus:outline-none focus:ring-1 focus:ring-primary"
              value={appraisalForm.notes}
              onChange={e => setAppraisalForm(f => ({ ...f, notes: e.target.value }))}
              placeholder="Detailed appraisal findings, risks, conditions…" />
          </div>
        </div>
      </Modal>

      {/* ── Top-Up Modal ── */}
      <Modal open={topupModal} onClose={() => setTopupModal(false)} title="Request Loan Top-Up"
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setTopupModal(false)}>Cancel</Button>
            <Button size="sm" loading={actionMutation.isPending}
              onClick={() => actionMutation.mutate({
                action:          'REQUEST_TOPUP',
                topUpType:       topupForm.topUpType,
                requestedAmount: topupForm.requestedAmount ? parseFloat(topupForm.requestedAmount) : undefined,
                reason:          topupForm.reason,
                newTenor:        topupForm.newTenor ? parseInt(topupForm.newTenor) : undefined,
              })}>
              Submit Request
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Alert variant="info">
            Current outstanding principal: <strong>{formatCurrency(l.outstandingPrincipal)}</strong>
          </Alert>
          <Select label="Top-Up Type" value={topupForm.topUpType}
            onChange={e => setTopupForm(f => ({ ...f, topUpType: e.target.value }))}
            options={[
              { value: 'ADD_ON',      label: 'Add-On (additional amount)'   },
              { value: 'RESTRUCTURE', label: 'Restructure'                  },
              { value: 'REFINANCE',   label: 'Refinance'                    },
              { value: 'MORATORIUM',  label: 'Moratorium (payment holiday)' },
            ]} />
          <FormGrid cols={2}>
            <Input label="Requested Amount (KES)" type="number"
              value={topupForm.requestedAmount}
              onChange={e => setTopupForm(f => ({ ...f, requestedAmount: e.target.value }))} />
            <Input label="New Tenor (months)" type="number"
              value={topupForm.newTenor}
              onChange={e => setTopupForm(f => ({ ...f, newTenor: e.target.value }))}
              placeholder="Leave blank to keep current" />
          </FormGrid>
          <div>
            <label className="text-sm font-medium">Reason</label>
            <textarea rows={2}
              className="mt-1 w-full border rounded-md px-3 py-2 text-sm resize-none"
              value={topupForm.reason}
              onChange={e => setTopupForm(f => ({ ...f, reason: e.target.value }))} />
          </div>
        </div>
      </Modal>

      {/* ── CRB Check Modal ── */}
      <Modal open={crbModal} onClose={() => setCrbModal(false)} title="Record CRB Check"
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setCrbModal(false)}>Cancel</Button>
            <Button size="sm" loading={actionMutation.isPending}
              onClick={() => actionMutation.mutate({
                action:  'CRB_CHECK',
                result:  crbForm.result,
                details: crbForm.details,
                score:   crbForm.score ? parseInt(crbForm.score) : undefined,
              })}>
              Save CRB Result
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Select label="CRB Status" value={crbForm.result}
            onChange={e => setCrbForm(f => ({ ...f, result: e.target.value }))}
            options={[
              { value: 'CLEAR',       label: 'Clear — no adverse listing'    },
              { value: 'LISTED',      label: 'Listed — adverse record found' },
              { value: 'BLACKLISTED', label: 'Blacklisted'                   },
              { value: 'DISPUTED',    label: 'Disputed'                      },
            ]} />
          <Input label="CRB Score" type="number"
            value={crbForm.score}
            onChange={e => setCrbForm(f => ({ ...f, score: e.target.value }))}
            placeholder="e.g. 720" />
          <div>
            <label className="text-sm font-medium">Details / Report Summary</label>
            <textarea rows={3}
              className="mt-1 w-full border rounded-md px-3 py-2 text-sm resize-none"
              value={crbForm.details}
              onChange={e => setCrbForm(f => ({ ...f, details: e.target.value }))}
              placeholder="Summary of CRB report findings…" />
          </div>
        </div>
      </Modal>

      {/* ── Processing Fee Upfront Modal ── */}
      <Modal open={feeModal} onClose={() => setFeeModal(false)} title="Record Processing Fee Payment"
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setFeeModal(false)}>Cancel</Button>
            <Button size="sm" loading={actionMutation.isPending}
              onClick={() => actionMutation.mutate({
                action:       'MARK_FEE_PAID',
                feeReference: feeForm.feeReference,
                feeMethod:    feeForm.feeMethod,
              })}>
              Mark Fee as Paid
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Alert variant="info">
            Processing fee of <strong>{formatCurrency(l.processingFee)}</strong> is payable
            upfront for this loan product. Record the payment receipt before submitting.
          </Alert>
          <Select label="Payment Method" value={feeForm.feeMethod}
            onChange={e => setFeeForm(f => ({ ...f, feeMethod: e.target.value }))}
            options={[
              { value: 'CASH',          label: 'Cash'          },
              { value: 'MPESA',         label: 'M-Pesa'        },
              { value: 'BANK_TRANSFER', label: 'Bank Transfer'  },
              { value: 'CHEQUE',        label: 'Cheque'         },
            ]} />
          <Input label="Receipt / Reference Number"
            value={feeForm.feeReference}
            onChange={e => setFeeForm(f => ({ ...f, feeReference: e.target.value }))}
            placeholder="M-Pesa ref, bank ref, receipt no…" />
        </div>
      </Modal>

      {/* ── Backdate Modal ── */}
      <Modal open={backdateModal} onClose={() => setBackdateModal(false)} title={`Backdate Loan — ${l.loanRef}`}
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setBackdateModal(false)}>Cancel</Button>
            <Button size="sm" loading={actionMutation.isPending}
              disabled={(() => {
                if (!backdateForm.targetDate) return true
                const target = new Date(backdateForm.targetDate)
                const created = new Date(l.createdAt)
                const diffMs = created.getTime() - target.getTime()
                const days = Math.floor(diffMs / 86400000)
                return days < 1 || days > 365
              })()}
              onClick={() => actionMutation.mutate({
                action:     'BACKDATE',
                targetDate: backdateForm.targetDate,
              })}>
              Apply Backdate
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          {(() => {
            if (!backdateForm.targetDate) {
              return (
                <Alert variant="warning">
                  Select a date before the current loan dates. All loan dates will be shifted
                  backward and interest will be accrued for the backdated period.
                </Alert>
              )
            }
            const target = new Date(backdateForm.targetDate)
            const created = new Date(l.createdAt)
            const diffMs = created.getTime() - target.getTime()
            const days = Math.floor(diffMs / 86400000)
            const dailyRate = parseFloat(l.interestRate) / 100 / 30
            const estimatedInterest = Math.round(parseFloat(l.outstandingPrincipal) * dailyRate * days * 100) / 100
            const dateFields = [
              { label: 'Created', date: l.createdAt },
              { label: 'Disbursed', date: l.disbursedAt },
              { label: 'First Due', date: l.firstDueDate },
              { label: 'Next Due', date: l.nextDueDate },
              { label: 'Maturity', date: l.maturityDate },
            ]

            if (days < 1 || days > 365) {
              return (
                <Alert variant="error">
                  {days < 1 ? 'Target date must be before the loan start date.' : `Difference is ${days} days — maximum is 365 days.`}
                </Alert>
              )
            }

            return (
              <>
                <Alert variant="warning">
                  <div className="space-y-1">
                    <p><strong>Shift dates back by {days} day(s)</strong></p>
                    <p className="text-xs">All loan dates will be shifted backward.
                    Interest of approx. <strong>{formatCurrency(estimatedInterest)}</strong> will be accrued.</p>
                  </div>
                </Alert>

                <div className="border rounded-lg divide-y text-sm">
                  <div className="px-3 py-2 bg-muted/30 font-medium flex justify-between">
                    <span>Date</span>
                    <span>Current → New</span>
                  </div>
                  {dateFields.filter(f => f.date).map(f => {
                    const newDate = new Date(new Date(f.date).getTime() - days * 86400000)
                    return (
                      <div key={f.label} className="px-3 py-1.5 flex justify-between">
                        <span className="text-muted-foreground">{f.label}</span>
                        <span className="font-mono text-xs">{fmtDate(f.date)} → <strong>{fmtDate(newDate)}</strong></span>
                      </div>
                    )
                  })}
                </div>

                <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 text-sm space-y-1">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Backdate period</span>
                    <span className="font-semibold">{days} days</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Daily rate</span>
                    <span className="font-mono">{(dailyRate * 100).toFixed(4)}%</span>
                  </div>
                  <div className="flex justify-between border-t border-amber-300 pt-1 font-medium">
                    <span>Estimated interest accrued</span>
                    <span className="font-bold text-red-700">{formatCurrency(estimatedInterest)}</span>
                  </div>
                </div>
              </>
            )
          })()}

          <Input label="Backdate to Date" type="date" required
            max={(() => {
              const d = new Date(l.createdAt)
              d.setDate(d.getDate() - 1)
              return d.toISOString().slice(0, 10)
            })()}
            value={backdateForm.targetDate}
            onChange={e => setBackdateForm({ targetDate: e.target.value })} />
        </div>
      </Modal>

      {/* ── Add Guarantor Modal ── */}
      <Modal open={guarantorModal} onClose={() => setGuarantorModal(false)} title="Add Guarantor"
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setGuarantorModal(false)}>Cancel</Button>
            <Button size="sm" loading={addGuarantorMutation.isPending}
              onClick={() => addGuarantorMutation.mutate({
                ...guarantorForm,
                guaranteeAmount: parseFloat(guarantorForm.guaranteeAmount),
                memberId: guarantorForm.isMember ? guarantorForm.memberId : undefined,
              })}>
              Add Guarantor
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Select label="Guarantor Type"
            value={guarantorForm.isMember ? 'member' : 'non-member'}
            onChange={e => setGuarantorForm(f => ({ ...f, isMember: e.target.value === 'member' }))}
            options={[{ value: 'member', label: 'Member' }, { value: 'non-member', label: 'Non-Member' }]} />
          {guarantorForm.isMember ? (
            <Input label="Member ID (UUID)" required
              value={guarantorForm.memberId}
              onChange={e => setGuarantorForm(f => ({ ...f, memberId: e.target.value }))} />
          ) : (
            <>
              <Input label="Full Name"
                value={guarantorForm.nonMemberName}
                onChange={e => setGuarantorForm(f => ({ ...f, nonMemberName: e.target.value }))} />
              <Input label="Phone"
                value={guarantorForm.nonMemberPhone}
                onChange={e => setGuarantorForm(f => ({ ...f, nonMemberPhone: e.target.value }))} />
            </>
          )}
          <Input label="Guarantee Amount (KES)" type="number" required
            value={guarantorForm.guaranteeAmount}
            onChange={e => setGuarantorForm(f => ({ ...f, guaranteeAmount: e.target.value }))} />
        </div>
      </Modal>

      {/* ── Add Collateral Modal ── */}
      <Modal open={collateralModal} onClose={() => setCollateralModal(false)} title="Add Collateral"
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setCollateralModal(false)}>Cancel</Button>
            <Button size="sm" loading={addCollateralMutation.isPending}
              onClick={() => addCollateralMutation.mutate({
                ...collateralForm,
                estimatedValue: parseFloat(collateralForm.estimatedValue),
              })}>
              Add Collateral
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <FormGrid cols={2}>
            <Input label="Collateral Type" required
              value={collateralForm.collateralType}
              onChange={e => setCollateralForm(f => ({ ...f, collateralType: e.target.value }))}
              placeholder="Motor Vehicle, Land, Equipment…" />
            <Input label="Estimated Value (KES)" type="number" required
              value={collateralForm.estimatedValue}
              onChange={e => setCollateralForm(f => ({ ...f, estimatedValue: e.target.value }))} />
          </FormGrid>
          <Input label="Description" required
            value={collateralForm.description}
            onChange={e => setCollateralForm(f => ({ ...f, description: e.target.value }))} />
          <FormGrid cols={3}>
            <Input label="Make"
              value={collateralForm.make}
              onChange={e => setCollateralForm(f => ({ ...f, make: e.target.value }))} />
            <Input label="Model"
              value={collateralForm.model}
              onChange={e => setCollateralForm(f => ({ ...f, model: e.target.value }))} />
            <Input label="Serial / Reg No."
              value={collateralForm.serialNumber}
              onChange={e => setCollateralForm(f => ({ ...f, serialNumber: e.target.value }))} />
          </FormGrid>
          <Input label="Location"
            value={collateralForm.location}
            onChange={e => setCollateralForm(f => ({ ...f, location: e.target.value }))} />
        </div>
      </Modal>

      {/* ── Log Activity Modal ── */}
      <Modal open={activityModal} onClose={() => setActivityModal(false)} title="Log Collection Activity"
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setActivityModal(false)}>Cancel</Button>
            <Button size="sm" loading={logActivityMutation.isPending}
              onClick={() => logActivityMutation.mutate(activityForm)}>
              Log Activity
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Select label="Action Type" value={activityForm.actionType}
            onChange={e => setActivityForm(f => ({ ...f, actionType: e.target.value }))}
            options={[
              { value: 'CALL_ATTEMPT',   label: 'Call Attempt'   },
              { value: 'CALL_CONNECTED', label: 'Call Connected'  },
              { value: 'SMS_SENT',       label: 'SMS Sent'        },
              { value: 'FIELD_VISIT',    label: 'Field Visit'     },
              { value: 'DEMAND_LETTER',  label: 'Demand Letter'   },
              { value: 'NOTE',           label: 'Note'            },
              { value: 'ESCALATION',     label: 'Escalation'      },
            ]} />
          <Input label="Notes"
            value={activityForm.notes}
            onChange={e => setActivityForm(f => ({ ...f, notes: e.target.value }))} />
          <Input label="Outcome"
            value={activityForm.outcome}
            onChange={e => setActivityForm(f => ({ ...f, outcome: e.target.value }))}
            placeholder="Result of this action…" />
        </div>
      </Modal>

    </div>
  )
}
