import { Check, Circle, X } from 'lucide-react';
import { formatDateTime } from '@/lib/format';
import { cn } from '@/lib/utils';
import type { LoanDetails } from '@/types';

/**
 * The AMCSMS §12 stages in order, with the status a loan has once each is done.
 */
const stages = [
    { label: 'Application', doneAt: 'submitted' },
    { label: 'Loan officer review', doneAt: 'officer_reviewed' },
    { label: 'Guarantor verification', doneAt: 'guarantors_verified' },
    { label: 'Accountant / manager review', doneAt: 'manager_reviewed' },
    { label: 'Approval committee', doneAt: 'committee_approved' },
    { label: 'Final approval', doneAt: 'approved' },
    { label: 'Disbursement', doneAt: 'disbursed' },
] as const;

const order: string[] = stages.map((stage) => stage.doneAt);

/**
 * Where the loan is in the approval workflow, and the trail of decisions.
 */
export default function LoanTimeline({ loan }: { loan: LoanDetails }) {
    const isRejected = loan.status === 'rejected';
    const isCancelled = loan.status === 'cancelled';
    const rejectedAt = isRejected
        ? loan.reviews.find((review) => review.outcome === 'rejected')
        : undefined;
    const reached = isRejected
        ? order.indexOf(
              stages.find((stage) => stage.label === rejectedAt?.stage)
                  ?.doneAt ?? 'submitted',
          ) - 1
        : isCancelled
          ? 0
          : order.indexOf(
                loan.status === 'completed' ? 'disbursed' : loan.status,
            );

    return (
        <section className="rounded-landing-lg border border-surface-200 bg-white p-5 shadow-landing-sm">
            <h2 className="font-display text-base font-semibold text-ink">
                Approval progress
            </h2>
            <ol className="mt-4 grid gap-3 sm:grid-cols-7 sm:gap-2">
                {stages.map((stage, position) => {
                    const done = position <= reached;
                    const failed = isRejected && position === reached + 1;
                    const current =
                        !isRejected && !isCancelled && position === reached + 1;

                    return (
                        <li
                            key={stage.label}
                            className="flex items-center gap-2 sm:flex-col sm:items-start"
                        >
                            <span
                                className={cn(
                                    'flex size-6 shrink-0 items-center justify-center rounded-full border text-xs',
                                    done &&
                                        'border-highlight bg-highlight text-white',
                                    failed &&
                                        'border-red-500 bg-red-500 text-white',
                                    current && 'border-brand text-brand',
                                    !done &&
                                        !failed &&
                                        !current &&
                                        'border-surface-200 text-ink-300',
                                )}
                            >
                                {done ? (
                                    <Check className="size-3.5" />
                                ) : failed ? (
                                    <X className="size-3.5" />
                                ) : (
                                    <Circle className="size-2 fill-current" />
                                )}
                            </span>
                            <span
                                className={cn(
                                    'text-xs leading-tight',
                                    done || current || failed
                                        ? 'font-semibold text-ink'
                                        : 'text-ink-400',
                                )}
                            >
                                {stage.label}
                            </span>
                        </li>
                    );
                })}
            </ol>

            {loan.rejectionReason && (
                <p className="mt-4 rounded-landing border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800">
                    Not approved: {loan.rejectionReason}
                </p>
            )}

            {loan.reviews.length > 0 && (
                <ul className="mt-4 divide-y divide-surface-100 border-t border-surface-100">
                    {loan.reviews.map((review) => (
                        <li key={review.id} className="py-2.5 text-sm">
                            <p className="text-ink-700">
                                <span className="font-semibold text-ink">
                                    {review.stage}
                                </span>{' '}
                                → {review.outcomeLabel}
                                {review.by && (
                                    <span className="text-ink-500">
                                        {' '}
                                        by {review.by}
                                    </span>
                                )}
                            </p>
                            <p className="text-xs text-ink-400">
                                {formatDateTime(review.at)}
                                {review.note && ` · ${review.note}`}
                            </p>
                        </li>
                    ))}
                </ul>
            )}
        </section>
    );
}
