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

const label = (s: string) => s.replace(/_/g, ' ');

/** Required and pledged guarantor/collateral cover for an application. */
export function CoverSummary({ cover }: { cover: Cover }) {
  const __ = useTrans();
  return (
    <div className="text-sm">
      <p>
        {__('Guarantors')}: {cover.pledged.guarantors} /{' '}
        {cover.required.guarantors} · {__('Guaranteed (UGX)')}:{' '}
        {cover.pledged.guaranteed} / {cover.required.guaranteed} ·{' '}
        {__('Collateral, forced-sale (UGX)')}: {cover.pledged.collateral} /{' '}
        {cover.required.collateral}
      </p>
      {cover.short.length > 0 && (
        <p className="text-destructive">
          {__('Security short')}: {cover.short.join('; ')}
        </p>
      )}
    </div>
  );
}

function status(s: Security, __: (k: string) => string): string {
  if (!s.closed) return __('Pledged');
  return `${__(s.closed.kind)} ${formatDate(s.closed.date)}`;
}

/** Pledged securities with withdraw/release actions; add forms while the loan is not disbursed. */
export function Securities({
  props,
  securities,
  applicationKey,
  borrowerId,
  editable,
  releasable,
}: {
  props: Props;
  securities: Security[];
  applicationKey: string;
  borrowerId: number;
  editable: boolean;
  releasable: boolean;
}) {
  const __ = useTrans();
  const can = props.permissions;
  const name = (id: number | null) =>
    props.members.find((m) => m.id === id)?.display_name ??
    `${__('Member')} ${id}`;
  return (
    <details className="space-y-2">
      <summary className="cursor-pointer">
        {__('Guarantors and collateral')} (
        {securities.filter((s) => !s.closed).length})
      </summary>
      <ul className="space-y-2 text-sm">
        {securities.map((s) => (
          <li className="rounded border p-2" key={s.id}>
            <p>
              {s.kind === 'guarantor'
                ? `${__('Guarantor')}: ${name(s.member_id)} · ${money('UGX', s.amount)} · ${__('consent')} ${formatDate(s.valued_on)}`
                : `${__(label(s.type))}: ${s.description} · ${__('market')} ${money('UGX', s.amount)} · ${__('forced-sale')} ${money('UGX', s.forced_value)} · ${__('valued')} ${formatDate(s.valued_on)}`}
              {s.owner ? ` · ${__('owner')} ${s.owner}` : ''}
              {s.reference ? ` · ${s.reference}` : ''} · {status(s, __)}
            </p>
            {s.holds.length > 0 && (
              <p className="text-sm">
                {__('Savings locked')}:{' '}
                {s.holds
                  .map(
                    (h) =>
                      `${h.account} ${money('UGX', h.amount)}${h.released ? ` (${__('released')})` : ''}`,
                  )
                  .join(', ')}
              </p>
            )}
            <p className="text-muted-foreground">{s.evidence}</p>
            {can.create && !s.closed && (editable || releasable) && (
              <Operation
                title={editable ? 'Withdraw pledge' : 'Release security'}
                operation="close-security"
                fields={[
                  { name: 'date', label: 'Date', value: props.date },
                  evidence,
                ]}
                build={(v) => ({
                  id: s.id,
                  date: v.date,
                  evidence: v.evidence,
                })}
              />
            )}
          </li>
        ))}
      </ul>
      {can.create && editable && (
        <div className="grid gap-3 lg:grid-cols-2">
          <Operation
            title="Add guarantor"
            operation="guarantor"
            fields={[
              {
                name: 'member',
                label: 'Guarantor (member)',
                options: props.members
                  .filter((m) => m.id !== borrowerId)
                  .map((m) => [
                    String(m.id),
                    `${m.number} — ${m.display_name}`,
                  ]),
              },
              { name: 'amount', label: 'Amount guaranteed (UGX)' },
              { name: 'date', label: 'Consent date', value: props.date },
              { ...evidence, label: 'Signed guarantee form reference' },
            ]}
            build={(v) => ({
              key: applicationKey,
              member_id: parseInt(v.member, 10),
              amount: v.amount,
              date: v.date,
              evidence: v.evidence,
            })}
          />
          <Operation
            title="Add collateral"
            operation="collateral"
            fields={[
              {
                name: 'type',
                label: 'Collateral type',
                options: props.collateralTypes.map((t) => [t, label(t)]),
              },
              { name: 'description', label: 'Description' },
              ...(props.savingsEnabled
                ? [
                    {
                      name: 'savings_account',
                      label: 'Savings account (for savings collateral)',
                      optional: true,
                      options: props.savingsAccounts.map(
                        (a) =>
                          [
                            String(a.id),
                            `${a.number} · ${money('UGX', a.free)}`,
                          ] as [string, string],
                      ),
                    },
                  ]
                : []),
              { name: 'owner', label: 'Owner', optional: true },
              {
                name: 'reference',
                label: 'Title, logbook or serial number',
                optional: true,
              },
              { name: 'market_value', label: 'Market value (UGX)' },
              { name: 'forced_value', label: 'Forced-sale value (UGX)' },
              { name: 'date', label: 'Valuation date', value: props.date },
              { ...evidence, label: 'Valuation report reference' },
            ]}
            build={(v) => ({
              key: applicationKey,
              type: v.type,
              description: v.description,
              owner: v.owner,
              reference: v.reference,
              market_value: v.market_value,
              forced_value: v.forced_value,
              ...(v.savings_account
                ? { savings_account: parseInt(v.savings_account, 10) }
                : {}),
              date: v.date,
              evidence: v.evidence,
            })}
          />
        </div>
      )}
    </details>
  );
}

/** Loans a member has guaranteed, for the member-filtered view. */
export function Guarantees({ props }: { props: Props }) {
  const __ = useTrans();
  if (props.guarantees.length === 0) return null;
  return (
    <section className="space-y-2 rounded border p-4">
      <h2 className="font-semibold">{__('Guarantees given by this member')}</h2>
      <ul className="text-sm">
        {props.guarantees.map((g) => (
          <li key={g.security_id}>
            {g.application_key} · {money('UGX', g.amount)}{' '}
            {g.disbursed
              ? `· ${__('outstanding principal')} ${money('UGX', g.outstanding_principal)}`
              : `· ${__('not yet disbursed')}`}
          </li>
        ))}
      </ul>
    </section>
  );
}
