import { useState } from 'react';
import { Button } from '@rutatiina/ui/components/ui/button';
import { formatDate, formatDateTime } from '@rutatiina/ui/lib/helpers';
import { useTrans } from '@rutatiina/ui/lib/translations';
import type { Account, Props } from '@nugsoft/savings/lib/types';
import {
  evidence,
  Operation,
  type Field,
  type Payload,
} from '@nugsoft/savings/lib/ui';
import { money } from '@nugsoft/accounting/components/openings/labels';

/** Cash custody or confirmed bank / mobile-money payment, as entered on a form. */
export function useSettlement(props: Props, account: Account) {
  const custodies = props.custodies.filter(
    (c) => c.branch_id === account.branch_id,
  );
  const fields: Field[] = [
    {
      name: 'channel',
      label: 'Paid by',
      value: 'cash',
      options: [
        ['cash', 'Cash'],
        ['bank', 'Bank or mobile money'],
      ],
    },
    {
      name: 'custody',
      label: 'Cash drawer',
      show: (v) => v.channel === 'cash',
      value:
        custodies.find((c) => c.holder_id === props.actorId)?.id.toString() ??
        '',
      options: custodies.map((c) => [String(c.id), c.label]),
    },
    {
      name: 'reference',
      label: 'Bank or mobile-money reference',
      show: (v) => v.channel === 'bank',
    },
  ];
  const build = (v: Record<string, string>): Payload =>
    v.channel === 'cash'
      ? { channel: 'cash', custody_id: parseInt(v.custody, 10) }
      : { channel: 'bank', reference: v.reference };
  return { fields, build };
}

export function AccountActions({
  props,
  account,
}: {
  props: Props;
  account: Account;
}) {
  const __ = useTrans();
  const can = props.permissions;
  const settlement = useSettlement(props, account);
  const date: Field = { name: 'date', label: 'Date', value: props.date };
  const others = props.accounts.filter(
    (a) => a.id !== account.id && !a.status.closed,
  );
  const limit = account.rules.approval_above;
  const approved = props.requests.filter(
    (r) => r.account_id === account.id && r.decision === 'approved' && !r.paid,
  );
  // One form at a time, so a withdrawal is never typed into the deposit form.
  const [open, setOpen] = useState<string | null>(null);
  if (account.status.closed) return null;
  const choices = [
    can.deposit && ['deposit', __('Deposit')],
    can.withdraw && ['withdraw', __('Withdraw')],
    can.transfer && others.length > 0 && ['transfer', __('Transfer')],
    (can.withdraw || can.transfer) &&
      limit !== '0.00' && ['request', __('Ask approval for a large amount')],
    can.open &&
      (account.status.dormant || account.balance === '0.00') && [
        'more',
        account.status.dormant ? __('Reactivate') : __('Close account'),
      ],
  ].filter((c): c is [string, string] => Array.isArray(c));
  return (
    <div className="space-y-3">
      <div className="flex flex-wrap gap-2">
        {choices.map(([key, label]) => (
          <Button
            key={key}
            size="sm"
            variant={open === key ? 'primary' : 'outline'}
            aria-expanded={open === key}
            onClick={() => setOpen(open === key ? null : key)}
          >
            {label}
          </Button>
        ))}
      </div>
      <div className="max-w-2xl">
        {can.deposit && open === 'deposit' && (
          <Operation
            title="Record deposit"
            operation="deposit"
            fields={[
              {
                name: 'key',
                label: 'Receipt number',
                optional: true,
                auto: true,
                hint: 'Leave blank and Mfuko numbers the receipt.',
              },
              { name: 'amount', label: 'Amount (UGX)' },
              date,
              ...settlement.fields,
              {
                ...evidence,
                label: 'Deposited by or note',
                optional: true,
                fallback: 'Deposit at the counter',
              },
            ]}
            build={(v) => ({
              id: account.id,
              key: v.key,
              amount: v.amount,
              date: v.date,
              evidence: v.evidence,
              settlement: settlement.build(v),
            })}
          />
        )}
        {can.withdraw && open === 'withdraw' && (
          <Operation
            title="Pay withdrawal"
            operation="withdraw"
            fields={[
              {
                name: 'key',
                label: 'Voucher number',
                optional: true,
                auto: true,
                hint: 'Leave blank and Mfuko numbers the voucher.',
              },
              { name: 'amount', label: 'Amount (UGX)' },
              date,
              ...settlement.fields,
              ...(approved.length > 0
                ? [
                    {
                      name: 'request',
                      label: 'Approved request',
                      optional: true,
                      options: approved.map(
                        (r) =>
                          [
                            r.request_key,
                            `${r.request_key} · ${money('UGX', r.amount)}`,
                          ] as [string, string],
                      ),
                    },
                  ]
                : []),
              {
                ...evidence,
                label: 'Paid to or note',
                optional: true,
                fallback: 'Withdrawal paid at the counter',
              },
            ]}
            build={(v) => ({
              id: account.id,
              key: v.key,
              amount: v.amount,
              date: v.date,
              evidence: v.evidence,
              settlement: settlement.build(v),
              ...(v.request ? { request: v.request } : {}),
            })}
          />
        )}
        {(can.withdraw || can.transfer) &&
          limit !== '0.00' &&
          open === 'request' && (
            <Operation
              title="Request approval for a large withdrawal or transfer"
              operation="request"
              fields={[
                {
                  name: 'key',
                  label: 'Request reference',
                  optional: true,
                  auto: true,
                  hint: 'Leave blank and Mfuko numbers the request.',
                },
                {
                  name: 'amount',
                  label: 'Amount (UGX)',
                  hint: `${__('Above')} ${money('UGX', limit)}`,
                },
                {
                  name: 'to',
                  label: 'Transfer to',
                  optional: true,
                  hint: 'Leave blank for a cash or bank withdrawal.',
                  options: others.map((a) => [
                    String(a.id),
                    `${a.account_number} · ${a.product}`,
                  ]),
                },
                date,
                { ...evidence, label: 'Reason' },
              ]}
              build={(v) => ({
                id: account.id,
                key: v.key,
                amount: v.amount,
                date: v.date,
                evidence: v.evidence,
                ...(v.to ? { to: parseInt(v.to, 10) } : {}),
              })}
            />
          )}
        {can.transfer && others.length > 0 && open === 'transfer' && (
          <Operation
            title="Transfer to another account"
            operation="transfer"
            fields={[
              {
                name: 'to',
                label: 'Receiving account',
                options: others.map((a) => [
                  String(a.id),
                  `${a.account_number} · ${a.product}`,
                ]),
              },
              {
                name: 'key',
                label: 'Transfer reference',
                optional: true,
                auto: true,
                hint: 'Leave blank and Mfuko numbers the transfer.',
              },
              { name: 'amount', label: 'Amount (UGX)' },
              date,
              ...(approved.length > 0
                ? [
                    {
                      name: 'request',
                      label: 'Approved request',
                      optional: true,
                      options: approved.map(
                        (r) =>
                          [
                            r.request_key,
                            `${r.request_key} · ${money('UGX', r.amount)}`,
                          ] as [string, string],
                      ),
                    },
                  ]
                : []),
              {
                ...evidence,
                label: 'Member instruction',
                optional: true,
                fallback: 'Transfer requested by the member',
              },
            ]}
            build={(v) => ({
              id: account.id,
              to: parseInt(v.to, 10),
              key: v.key,
              amount: v.amount,
              date: v.date,
              evidence: v.evidence,
              ...(v.request ? { request: v.request } : {}),
            })}
          />
        )}
        {can.open && account.status.dormant && open === 'more' && (
          <Operation
            title="Reactivate dormant account"
            operation="reactivate"
            fields={[
              date,
              { ...evidence, label: 'How the member was confirmed' },
            ]}
            build={(v) => ({ id: account.id, ...v })}
          />
        )}
        {can.open &&
          account.balance === '0.00' &&
          !account.status.dormant &&
          open === 'more' && (
            <Operation
              title="Close account"
              operation="close"
              fields={[date, { ...evidence, label: 'Reason' }]}
              build={(v) => ({ id: account.id, ...v })}
            />
          )}
      </div>
    </div>
  );
}

export function History({
  props,
  account,
}: {
  props: Props;
  account: Account;
}) {
  const __ = useTrans();
  const can = props.permissions;
  if (account.history.length === 0) return null;
  return (
    <details>
      <summary className="cursor-pointer">{__('Entries')}</summary>
      <ul className="divide-y text-sm [&>li]:py-2">
        {account.history.map((e) => (
          <li className="space-y-1" key={e.id}>
            <p>
              {formatDate(e.date)} · {__(e.kind)} ·{' '}
              {e.movements
                .map((m) => `${__(m.kind)} ${money('UGX', m.amount)}`)
                .join(' · ')}
              {e.reversed && ` · ${__('corrected')}`} · {__('recorded')}{' '}
              {formatDateTime(e.created_at)}
            </p>
            <p className="text-muted-foreground">{e.evidence}</p>
            <a className="underline" href={`/savings/receipts/${e.id}`}>
              {__('Receipt')}
            </a>
            {!e.reversed &&
              !['correction', 'payment', 'credit'].includes(e.kind) &&
              can['correct.approve'] &&
              e.actor_id !== props.actorId &&
              !e.correction_review && (
                <Operation
                  title="Review correction"
                  operation="review-correction"
                  fields={[
                    { name: 'date', label: 'Original date', value: e.date },
                    { ...evidence, label: 'Reason and money returned' },
                  ]}
                  build={(v) => ({ id: e.id, ...v })}
                />
              )}
            {!e.reversed &&
              !['correction', 'payment', 'credit'].includes(e.kind) &&
              can.correct &&
              e.correction_review && (
                <Operation
                  title="Correct entry"
                  operation="correct"
                  fields={[
                    { name: 'date', label: 'Original date', value: e.date },
                    { ...evidence, label: 'Same reason as the review' },
                  ]}
                  build={(v) => ({ id: e.id, ...v })}
                />
              )}
          </li>
        ))}
      </ul>
    </details>
  );
}

/** Withdrawal and transfer requests waiting for a second person. */
export function Approvals({ props }: { props: Props }) {
  const __ = useTrans();
  const waiting = props.requests.filter((r) => r.decision === null);
  if (waiting.length === 0 || !props.permissions.approve) return null;
  const number = (id: number | null) =>
    props.accounts.find((a) => a.id === id)?.account_number ?? id;
  return (
    <section className="space-y-2 rounded-lg border p-4">
      <h2 className="font-semibold">{__('Withdrawals awaiting approval')}</h2>
      {waiting.map((r) => (
        <div className="space-y-2 border-t pt-3" key={r.id}>
          <p>
            {r.request_key} · {number(r.account_id)} · {money('UGX', r.amount)}
            {r.to_account_id && ` → ${number(r.to_account_id)}`} ·{' '}
            {formatDate(r.requested_on)} · {__(r.channel)} · {r.evidence}
          </p>
          {r.requester_id !== props.actorId && (
            <Operation
              title="Decide request"
              operation="decide"
              fields={[
                {
                  name: 'decision',
                  label: 'Decision',
                  options: [
                    ['approved', 'Approve'],
                    ['rejected', 'Reject'],
                  ],
                },
                { ...evidence, label: 'Checks done (signature, identity)' },
              ]}
              build={(v) => ({ id: r.id, ...v })}
            />
          )}
        </div>
      ))}
    </section>
  );
}
