import { useState } from 'react';
import { Input } from '@rutatiina/ui/components/ui/input';
import { Label } from '@rutatiina/ui/components/ui/label';
import { formatDate } from '@rutatiina/ui/lib/helpers';
import { useTrans } from '@rutatiina/ui/lib/translations';
import type { Account, Props } from '@nugsoft/savings/lib/types';
import {
  AccountActions,
  Approvals,
  History,
} from '@nugsoft/savings/components/account-actions';
import { Batches } from '@nugsoft/savings/components/batches';
import { Operation, Panel } from '@nugsoft/savings/lib/ui';
import { money } from '@nugsoft/accounting/components/openings/labels';

function status(a: Account, __: (k: string) => string): string {
  if (a.status.closed) return __('Closed');
  if (a.status.dormant) return __('Dormant');
  if (a.status.maturity)
    return a.status.matured
      ? __('Matured')
      : `${__('Matures')} ${formatDate(a.status.maturity)}`;
  return __('Active');
}

/** The latest month-end on or before a date: the date itself on the last day of a month. */
function monthEnd(date: string): string {
  const [year, month, day] = date.split('-').map(Number);
  if (new Date(Date.UTC(year, month, 0)).getUTCDate() === day) return date;
  return new Date(Date.UTC(year, month - 1, 0)).toISOString().slice(0, 10);
}

export function Accounts({ props }: { props: Props }) {
  const __ = useTrans();
  const can = props.permissions;
  const name = (id: number) =>
    props.members.find((m) => m.id === id)?.display_name ??
    `${__('Member')} ${id}`;
  const [query, setQuery] = useState('');
  const needle = query.trim().toLowerCase();
  const shown = props.accounts.filter((a) => {
    if (!needle) return true;
    const member = props.members.find((m) => m.id === a.member_id);
    return [a.account_number, member?.display_name, member?.number]
      .filter(Boolean)
      .some((text) => String(text).toLowerCase().includes(needle));
  });
  const offered = props.products.filter(
    (p) => p.current_version_id !== null && p.rules?.active,
  );
  const kind = (id: string) =>
    offered.find((p) => String(p.id) === id)?.rules?.kind;
  return (
    <div className="space-y-4">
      <Approvals props={props} />
      {props.accounts.length === 0 ? (
        <p>{__('No savings accounts yet.')}</p>
      ) : (
        <div className="space-y-2">
          <Label htmlFor="savings-search">{__('Find an account')}</Label>
          <Input
            id="savings-search"
            type="search"
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            placeholder={__('Member name, member number or account number')}
          />
          {needle && shown.length === 0 && (
            <p className="text-muted-foreground text-sm">
              {__('No account matches. Check the spelling or the number.')}
            </p>
          )}
        </div>
      )}
      {shown.map((a) => (
        <article className="space-y-2 rounded-lg border p-4" key={a.id}>
          <h2 className="font-semibold">
            {a.account_number} · {name(a.member_id)} · {a.product}
          </h2>
          <p>
            {__('Balance')}: <strong>{money('UGX', a.balance)}</strong> ·{' '}
            {__('Available')}: {money('UGX', a.available)}
            {a.held !== '0.00' &&
              ` · ${__('Held')}: ${money('UGX', a.held)}`} ·{' '}
            {status(a, __)} · {__('Opened')} {formatDate(a.opened_on)}
          </p>
          {a.contributions && (
            <p className="text-sm">
              {__('Contributions')}: {money('UGX', a.contributions.amount)}{' '}
              {__(a.contributions.frequency)} · {__('expected')}
              {money('UGX', a.contributions.expected)} · {__('paid')}
              {money('UGX', a.contributions.paid)}
              {a.contributions.arrears !== '0.00' &&
                ` · ${__('arrears')} ${money('UGX', a.contributions.arrears)}`}
              {a.contributions.missed.length > 0 &&
                ` · ${a.contributions.missed.length} ${__('missed')}`}
              {a.contributions.fines_outstanding !== '0.00' &&
                ` · ${__('fines due')} ${money('UGX', a.contributions.fines_outstanding)}`}
              {a.contributions.next_due &&
                ` · ${__('next due')} ${formatDate(a.contributions.next_due)}`}
            </p>
          )}
          <a className="underline" href={`/savings/${a.id}/statement`}>
            {__('Statement')}
          </a>
          <AccountActions props={props} account={a} />
          <History props={props} account={a} />
        </article>
      ))}
      {can.open && props.started && (
        <Panel
          title="Open a savings account"
          description="Choose the member and the product; the first deposit is recorded separately."
          open={props.member !== null && props.accounts.length === 0}
        >
          <Operation
            heading={false}
            title="Open savings account"
            operation="open"
            fields={[
              {
                name: 'member',
                label: 'Account holder',
                value: props.member ? String(props.member) : '',
                options: props.members.map((m) => [
                  String(m.id),
                  `${m.number} — ${m.display_name}`,
                ]),
              },
              {
                name: 'product',
                label: 'Savings product',
                value: offered.length === 1 ? String(offered[0].id) : '',
                options: offered.map((p) => [
                  String(p.id),
                  `${p.code} — ${p.name}`,
                ]),
              },
              { name: 'date', label: 'Opening date', value: props.date },
              {
                name: 'number',
                label: 'Account number',
                optional: true,
                hint: 'Leave blank and Mfuko numbers the account.',
              },
              {
                name: 'term_months',
                label: 'Term in months',
                optional: true,
                hint: "Leave blank to use the product's term.",
                show: (v) => kind(v.product) === 'fixed',
              },
            ]}
            build={(v) => ({
              member_id: parseInt(v.member, 10),
              product_id: parseInt(v.product, 10),
              date: v.date,
              ...(v.number ? { number: v.number } : {}),
              ...(v.term_months
                ? { term_months: parseInt(v.term_months, 10) }
                : {}),
            })}
          />
        </Panel>
      )}
      {can.deposit && props.started && (
        <Panel
          title="Many deposits at once, from a file"
          description="Check the file first; then every row is posted together, or none is."
        >
          <Batches props={props} />
        </Panel>
      )}
      {can.process && props.started && (
        <Panel
          title="Month-end: contributions and interest"
          description="Run these at the end of each month. Running one again for the same date changes nothing."
        >
          <div className="grid gap-8 md:grid-cols-2 md:gap-0 md:divide-x md:[&>*:first-child]:pe-6 md:[&>*:last-child]:ps-6">
            <Operation
              title="Process missed contributions"
              description="Charges the product's fine for each contribution missed up to this date, and takes unpaid fines from the account balance."
              operation="process"
              fields={[{ name: 'date', label: 'As of', value: props.date }]}
            />
            <Operation
              title="Credit month-end interest"
              description="Adds the month's interest to every interest-earning account, and maturity interest to fixed deposits that have matured."
              operation="interest"
              fields={[
                {
                  name: 'date',
                  label: 'Last day of the month',
                  value: monthEnd(props.date),
                },
              ]}
            />
          </div>
        </Panel>
      )}
    </div>
  );
}
