import { formatDate } from '@rutatiina/ui/lib/helpers';
import { useTrans } from '@rutatiina/ui/lib/translations';
import type { Loan, Props, WriteOffPreview } from '@nugsoft/loans/lib/types';
import {
  choices,
  Components,
  evidence,
  Operation,
} from '@nugsoft/loans/lib/ui';
import { money } from '@nugsoft/accounting/components/openings/labels';

const BUCKET_LABELS: Record<string, string> = {
  current: 'Current',
  '1-30': '1–30 days',
  '31-60': '31–60 days',
  '61-90': '61–90 days',
  '91-180': '91–180 days',
  'over-180': 'Over 180 days',
};

/** What a write-off would do: dues, recoveries from liens, and how the allowance covers the rest. */
export function WriteOffSummary({ preview }: { preview: WriteOffPreview }) {
  const __ = useTrans();
  return (
    <div className="space-y-2 text-sm">
      <p>
        {__('As of')} {formatDate(preview.date)} · {preview.days}{' '}
        {__('days past due')} · {__('Owed')}:{' '}
        <strong>{money('UGX', preview.owed_total)}</strong>
      </p>
      {preview.claims.length > 0 && (
        <div>
          <p className="font-medium">
            {__('Recovered first from liened savings')}:{' '}
            {money('UGX', preview.claimed)}
          </p>
          <ul className="list-disc ps-5">
            {preview.claims.map((c) => (
              <li key={c.hold}>
                {c.kind === 'guarantor'
                  ? __('Guarantor')
                  : __('Cash collateral')}{' '}
                · {__('Member')} {c.member} · {__('Savings account')}{' '}
                {c.account} · {money('UGX', c.amount)}
              </li>
            ))}
          </ul>
        </div>
      )}
      <p className="font-medium">
        {__('Written off')}: {money('UGX', preview.write_off_total)}
      </p>
      <Components values={preview.write_off} />
      <p>
        {__('On the books')}: {money('UGX', preview.on_books)} ·{' '}
        {__('Allowance used')}:{money('UGX', preview.allowance)} ·{' '}
        {__('Further impairment expense')}: UGX {preview.expense}
        {preview.release !== '0.00' &&
          ` · ${__('Allowance released')}: ${money('UGX', preview.release)}`}
      </p>
      {preview.recognition !== 'due' && (
        <p className="text-muted-foreground">
          {__(
            'Interest, fees and penalties recognized when paid are not on the books; they are written off from the loan record only.',
          )}
        </p>
      )}
      <p className="text-muted-foreground">
        {__(
          'The member still owes the written-off amount. Later payments are recorded as recoveries.',
        )}
      </p>
    </div>
  );
}

/** The organization's provisioning policy: a rate for each aging bucket, the base and the write-off threshold. */
export function ImpairmentPolicySection({ props }: { props: Props }) {
  const __ = useTrans();
  const can = props.permissions;
  const { current, pending, buckets } = props.impairment;
  return (
    <section className="space-y-3 rounded border p-4">
      <h2 className="font-semibold">{__('Loan impairment policy')}</h2>
      <p className="text-muted-foreground text-sm">
        {__(
          'Provisions set aside an allowance for each loan at the rate for its days past due. A loan is written off against its allowance once it is old enough and a second person approves.',
        )}
      </p>
      {current ? (
        <div className="space-y-1 text-sm">
          <p>
            {__('Version')} {current.version} · {__('Effective')}{' '}
            {formatDate(current.effective_date)} ·{' '}
            {current.base === 'principal'
              ? __('Provision on outstanding principal')
              : __('Provision on principal and receivables on the books')}{' '}
            · {__('Write-offs from')} {current.write_off_days}{' '}
            {__('days past due')}
          </p>
          <div className="flex flex-wrap gap-4">
            {buckets.map((b) => (
              <p key={b}>
                {__(BUCKET_LABELS[b] ?? b)}:{' '}
                <strong>{current.rates[b]}%</strong>
              </p>
            ))}
          </div>
          {props.impairment.last_run && (
            <p className="text-muted-foreground">
              {__('Last provisions')}:{' '}
              {formatDate(props.impairment.last_run.as_of)}
            </p>
          )}
        </div>
      ) : (
        <p className="text-sm">
          {__(
            'No impairment policy is set yet. Provisions and write-offs need one.',
          )}
        </p>
      )}
      {pending &&
        can['policy.approve'] &&
        pending.maker_id !== props.actorId && (
          <Operation
            title="Review the proposed impairment policy"
            operation="review-impairment"
            fields={[
              {
                name: 'decision',
                label: 'Decision',
                value: 'approved',
                options: choices(['approved', 'rejected']),
              },
              evidence,
            ]}
            build={(v) => ({
              id: pending.id,
              checksum: pending.checksum,
              decision: v.decision,
              evidence: v.evidence,
            })}
          />
        )}
      {can['policy.manage'] && (
        <details>
          <summary className="cursor-pointer">
            {current
              ? __('Change the impairment policy')
              : __('Set the impairment policy')}
          </summary>
          <Operation
            title="Save impairment policy"
            operation="impairment-policy"
            fields={[
              ...buckets.map((b) => ({
                name: `rate_${b}`,
                label: `${BUCKET_LABELS[b] ?? b} — provision rate (%)`,
                value: current?.rates[b] ?? '',
              })),
              {
                name: 'base',
                label: 'Provision base',
                value: current?.base ?? 'principal',
                options: [
                  ['principal', __('Outstanding principal')],
                  ['receivables', __('Principal and receivables on the books')],
                ] as [string, string][],
              },
              {
                name: 'write_off_days',
                label: 'Days past due before a write-off is allowed',
                value: String(current?.write_off_days ?? ''),
              },
              { name: 'date', label: 'Effective date', value: props.date },
              { ...evidence, label: 'Reason and approval reference' },
            ]}
            build={(v) => ({
              rates: Object.fromEntries(
                buckets.map((b) => [b, v[`rate_${b}`]]),
              ),
              base: v.base,
              write_off_days: parseInt(v.write_off_days, 10),
              date: v.date,
              evidence: v.evidence,
            })}
          />
        </details>
      )}
    </section>
  );
}

/** Write-off status, request and preview for one loan. */
export function LoanWriteOff({ props, loan }: { props: Props; loan: Loan }) {
  const __ = useTrans();
  const can = props.permissions;
  if (loan.written_off) {
    const owed = Object.values(loan.recoverable).some((v) => v !== '0.00');
    return (
      <div className="border-destructive/40 space-y-1 rounded border p-3 text-sm">
        <p className="font-medium">
          {loan.settled
            ? __('Written off and fully recovered')
            : __('Written off — still owed by the member')}
        </p>
        <Components values={loan.recoverable} />
        {!loan.settled && owed && (
          <p className="text-muted-foreground">
            {__('Record what the member pays with “Record recovery”.')}
          </p>
        )}
      </div>
    );
  }
  if (loan.settled || loan.void) return null;
  const pending = props.writeOffs.find(
    (w) => w.loan_id === loan.id && w.decision === null,
  );
  return (
    <div className="space-y-2">
      <p className="text-sm">
        {__('Days past due')}: {loan.days_past_due} ·{' '}
        {__('Impairment allowance')}: {money('UGX', loan.allowance)}
      </p>
      {pending && (
        <p className="text-sm">
          {__('Write-off requested')} ({pending.request_key}) ·{' '}
          {__('waiting for a second person')}
        </p>
      )}
      {can.write_off && !pending && props.impairment.current && (
        <details>
          <summary className="cursor-pointer">
            {__('Write off this loan')}
          </summary>
          <div className="grid gap-4 py-3 lg:grid-cols-2">
            <Operation
              title="Preview write-off"
              operation="write-off-preview"
              preview
              fields={[
                { name: 'date', label: 'Write-off date', value: props.date },
              ]}
              build={(v) => ({ id: loan.id, date: v.date })}
              render={(r) => <WriteOffSummary preview={r as WriteOffPreview} />}
            />
            <Operation
              title="Request write-off"
              operation="write-off"
              fields={[
                { name: 'key', label: 'Write-off reference' },
                { name: 'date', label: 'Write-off date', value: props.date },
                { ...evidence, label: 'Reason and collection efforts' },
              ]}
              build={(v) => ({
                id: loan.id,
                key: v.key,
                date: v.date,
                evidence: v.evidence,
              })}
            />
          </div>
        </details>
      )}
    </div>
  );
}

/** Write-off requests waiting for a decision, and the decided ones. */
export function WriteOffRequests({ props }: { props: Props }) {
  const __ = useTrans();
  const can = props.permissions;
  if (props.writeOffs.length === 0) return null;
  return (
    <section className="space-y-3 rounded border p-4">
      <h2 className="font-semibold">{__('Write-off requests')}</h2>
      {props.writeOffs.map((w) => (
        <article className="space-y-2 rounded border p-3" key={w.id}>
          <p className="font-medium">
            {w.loan_key} · {w.request_key} · {formatDate(w.date)} ·{' '}
            {w.decision
              ? __(w.decision.decision)
              : __('waiting for a decision')}
          </p>
          <p className="text-sm break-words">{w.reason}</p>
          <WriteOffSummary preview={w.preview} />
          {!w.decision &&
            can['write_off.approve'] &&
            w.maker_id !== props.actorId && (
              <Operation
                title="Decide write-off"
                operation="review-write-off"
                fields={[
                  {
                    name: 'decision',
                    label: 'Decision',
                    value: 'approved',
                    options: choices(['approved', 'rejected']),
                  },
                  evidence,
                ]}
                build={(v) => ({
                  id: w.id,
                  checksum: w.checksum,
                  decision: v.decision,
                  evidence: v.evidence,
                })}
              />
            )}
          {w.decision && (
            <p className="text-muted-foreground text-sm break-words">
              {w.decision.evidence}
            </p>
          )}
        </article>
      ))}
    </section>
  );
}

type ProvisionPreview = {
  date: string;
  required: string;
  current: string;
  change: string;
  buckets: Record<string, { count: number; base: string; required: string }>;
  loans: {
    loan_id: number;
    loan_key: string;
    bucket: string;
    days: number;
    base: string;
    rate: string;
    required: string;
    current: string;
    change: string;
  }[];
  run: { id: number } | null;
};

/** Preview and post the provisions for a date (reports page). */
export function Provisions({ date }: { date: string }) {
  const __ = useTrans();
  return (
    <div className="grid gap-4 lg:grid-cols-2">
      <Operation
        title="Preview provisions"
        operation="provision-preview"
        preview
        fields={[{ name: 'date', label: 'Provisions as of', value: date }]}
        render={(r) => {
          const p = r as unknown as ProvisionPreview;
          return (
            <div className="space-y-2 text-sm">
              <p>
                {__('Required allowance')}:{' '}
                <strong>{money('UGX', p.required)}</strong> · {__('Held now')}:{' '}
                {money('UGX', p.current)} · {__('Change to post')}:
                {money('UGX', p.change)}
                {p.run && ` · ${__('Already run for this date')}`}
              </p>
              <ul className="list-disc ps-5">
                {Object.entries(p.buckets).map(([b, v]) => (
                  <li key={b}>
                    {__(BUCKET_LABELS[b] ?? b)}: {v.count} · {__('Base')}
                    {money('UGX', v.base)} · {__('Required')}{' '}
                    {money('UGX', v.required)}
                  </li>
                ))}
              </ul>
            </div>
          );
        }}
      />
      <Operation
        title="Post provisions"
        operation="provision"
        fields={[{ name: 'date', label: 'Provisions as of', value: date }]}
      />
    </div>
  );
}
