import { useId } from 'react';
import type { TableSpec } from '@/lib/agent-stream';

function tableCurrency(
    table: TableSpec,
    fallback?: string,
): string | undefined {
    const metaCurrency = table.meta?.currency;

    return typeof metaCurrency === 'string' && metaCurrency !== ''
        ? metaCurrency
        : fallback;
}

function formatCell(
    value: string | number,
    columnIndex: number,
    columns: string[],
    currency?: string,
): string {
    if (typeof value !== 'number' || !Number.isFinite(value)) {
        return String(value);
    }

    const columnName = columns[columnIndex]?.toLowerCase() ?? '';

    if (
        currency &&
        (columnName.includes('amount') ||
            columnName.includes('balance') ||
            columnName.includes('period a') ||
            columnName.includes('period b') ||
            columnName.includes('delta'))
    ) {
        return new Intl.NumberFormat(undefined, {
            style: 'currency',
            currency,
            maximumFractionDigits: 2,
        }).format(value);
    }

    return new Intl.NumberFormat(undefined, {
        maximumFractionDigits: 2,
    }).format(value);
}

export function TableMessage({
    table,
    currency,
    artifactId,
}: {
    table: TableSpec;
    currency?: string;
    artifactId: string;
}) {
    const titleId = useId();
    const resolvedCurrency = tableCurrency(table, currency);

    return (
        <figure
            className="my-3 w-full max-w-2xl min-w-0 overflow-hidden rounded-xl border border-border bg-card p-4"
            aria-labelledby={titleId}
            data-artifact-id={artifactId}
        >
            <figcaption
                id={titleId}
                className="mb-3 text-sm font-medium text-foreground"
            >
                {table.title}
            </figcaption>
            <div className="overflow-x-auto rounded-lg border border-border">
                <table className="w-full min-w-[20rem] border-collapse text-sm">
                    <thead>
                        <tr className="border-b border-border bg-muted/50">
                            {table.columns.map((column) => (
                                <th
                                    key={column}
                                    scope="col"
                                    className="px-3 py-2 text-left font-medium text-foreground"
                                >
                                    {column}
                                </th>
                            ))}
                        </tr>
                    </thead>
                    <tbody>
                        {table.rows.map((row, rowIndex) => (
                            <tr
                                key={rowIndex}
                                className="border-b border-border/70 last:border-b-0"
                            >
                                {row.map((cell, cellIndex) => (
                                    <td
                                        key={cellIndex}
                                        className="px-3 py-2 text-muted-foreground"
                                    >
                                        {formatCell(
                                            cell,
                                            cellIndex,
                                            table.columns,
                                            resolvedCurrency,
                                        )}
                                    </td>
                                ))}
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </figure>
    );
}
