import { Check, Circle, X } from 'lucide-react';
import WithdrawalStatus from '@/components/member/withdrawal-status';
import type { WithdrawalItem } from '@/components/member/withdrawal-status';
import { formatDateTime, formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';

type Step = {
    label: string;
    at: string | null;
    state: 'done' | 'current' | 'todo' | 'stopped';
};

function steps(
    withdrawal: WithdrawalItem,
    reviewedBy?: string | null,
    paidBy?: string | null,
): Step[] {
    const stopped =
        withdrawal.status === 'rejected' || withdrawal.status === 'cancelled';
    const reviewed = ['approved', 'paid'].includes(withdrawal.status);

    return [
        {
            label: 'Requested — money held',
            at: withdrawal.requestedAt,
            state: 'done',
        },
        stopped
            ? {
                  label:
                      withdrawal.status === 'rejected'
                          ? `Not approved${reviewedBy ? ` by ${reviewedBy}` : ''} — money returned`
                          : 'Cancelled — money returned',
                  at: withdrawal.reviewedAt,
                  state: 'stopped',
              }
            : {
                  label: reviewed
                      ? `Approved${reviewedBy ? ` by ${reviewedBy}` : ''}`
                      : 'Waiting for approval',
                  at: withdrawal.reviewedAt,
                  state: reviewed ? 'done' : 'current',
              },
        ...(stopped
            ? []
            : [
                  {
                      label:
                          withdrawal.status === 'paid'
                              ? `Paid${paidBy ? ` by ${paidBy}` : ''}`
                              : 'Payment',
                      at: withdrawal.paidAt,
                      state:
                          withdrawal.status === 'paid'
                              ? ('done' as const)
                              : withdrawal.status === 'approved'
                                ? ('current' as const)
                                : ('todo' as const),
                  },
              ]),
    ];
}

/**
 * Amount, method, payee and progress of a withdrawal, shared by the member
 * page and the staff review page. Also prints as the receipt.
 */
export default function WithdrawalDetails({
    withdrawal,
    reviewedBy,
    paidBy,
    memberLine,
}: {
    withdrawal: WithdrawalItem;
    reviewedBy?: string | null;
    paidBy?: string | null;
    memberLine?: string;
}) {
    const rows: [string, string][] = [
        ['Reference', withdrawal.reference],
        ...(memberLine ? ([['Member', memberLine]] as [string, string][]) : []),
        ['Reason', withdrawal.reason],
        ['Paid as', withdrawal.paymentMethodLabel],
        ...(withdrawal.paymentMethod === 'bank_transfer'
            ? ([
                  ['Bank', withdrawal.bankName ?? '—'],
                  [
                      'Account',
                      `${withdrawal.accountNumber ?? '—'} · ${withdrawal.accountName ?? ''}`,
                  ],
              ] as [string, string][])
            : []),
        ...(withdrawal.paymentReference
            ? ([['Payment reference', withdrawal.paymentReference]] as [
                  string,
                  string,
              ][])
            : []),
        ...(withdrawal.reviewNote
            ? ([['Note from staff', withdrawal.reviewNote]] as [
                  string,
                  string,
              ][])
            : []),
    ];

    return (
        <section className="grid gap-5 rounded-landing-lg border border-surface-200 bg-white p-5 shadow-landing-sm sm:p-6">
            <div className="flex flex-wrap items-center justify-between gap-3">
                <div>
                    <p className="text-sm text-ink-400">Withdrawal</p>
                    <p className="font-display text-3xl font-semibold text-ink tabular-nums">
                        {formatNaira(withdrawal.amount)}
                    </p>
                </div>
                <WithdrawalStatus
                    status={withdrawal.status}
                    label={withdrawal.statusLabel}
                />
            </div>

            <ol className="grid gap-3">
                {steps(withdrawal, reviewedBy, paidBy).map((step) => (
                    <li key={step.label} className="flex items-start gap-3">
                        <span
                            className={cn(
                                'mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-full',
                                step.state === 'done' &&
                                    'bg-highlight text-white',
                                step.state === 'current' &&
                                    'border-2 border-brand text-brand',
                                step.state === 'todo' &&
                                    'border-2 border-surface-200 text-ink-300',
                                step.state === 'stopped' &&
                                    'bg-red-100 text-red-700',
                            )}
                        >
                            {step.state === 'done' ? (
                                <Check className="size-3.5" />
                            ) : step.state === 'stopped' ? (
                                <X className="size-3.5" />
                            ) : (
                                <Circle className="size-2 fill-current" />
                            )}
                        </span>
                        <span>
                            <span className="block text-sm font-semibold text-ink">
                                {step.label}
                            </span>
                            {step.at && (
                                <span className="block text-xs text-ink-400">
                                    {formatDateTime(step.at)}
                                </span>
                            )}
                        </span>
                    </li>
                ))}
            </ol>

            <dl className="grid gap-3 border-t border-surface-100 pt-4 text-sm sm:grid-cols-2">
                {rows.map(([term, detail]) => (
                    <div key={term} className="min-w-0">
                        <dt className="text-xs text-ink-400">{term}</dt>
                        <dd className="font-medium wrap-break-word text-ink">
                            {detail}
                        </dd>
                    </div>
                ))}
            </dl>
        </section>
    );
}
