import type { QueryResult } from '@/app/lib/types';
import { formatDisplayNumber, isNumericLike } from '@/app/lib/format';
import { useT } from './ContentProvider';
import { ErrorNotice } from './ErrorNotice';
import { TableIcon } from './icons';
import { FrameHeader, cx } from './ui';

export function QueryResultTable({ result }: { result: QueryResult }) {
  const t = useT();
  if (result.error) {
    return <ErrorNotice monospace>{result.error}</ErrorNotice>;
  }
  if (result.rows.length === 0) {
    return (
      <div className="mt-3 rounded-[10px] border border-edge bg-notice px-4 py-2.5 text-center text-[14px] text-muted">
        {t('table.empty')}
      </div>
    );
  }
  return (
    <div className="mt-3 overflow-hidden rounded-xl border border-edge">
      {/* Results header */}
      <FrameHeader compact>
        <div className="flex items-center gap-2">
          <TableIcon color="var(--color-success)" />
          <span className="text-[12px] font-bold uppercase tracking-[0.12em] text-success">{t('table.results')}</span>
        </div>
        <span className="font-code text-[12px] text-muted">
          {t('table.summary', {
            rows: t(result.rows.length === 1 ? 'table.row' : 'table.rows', { count: result.rows.length, plus: result.truncated ? '+' : '' }),
            cols: t(result.columns.length === 1 ? 'table.col' : 'table.cols', { count: result.columns.length }),
          })}
        </span>
      </FrameHeader>
      {result.truncated && (
        <div className="border-b border-warning/25 bg-warning/10 px-3.5 py-1.5 text-[13px] text-warning-ink">
          {t('table.truncated', { count: result.rows.length.toLocaleString() })}
        </div>
      )}
      <div className="max-h-[380px] overflow-x-auto overflow-y-auto">
        <table className="w-full border-collapse text-[14px]">
          <thead className="sticky top-0 z-10">
            <tr>
              {result.columns.map(col => (
                <th key={col} className="whitespace-nowrap border-b border-line bg-panel-code px-3.5 py-2 text-left text-[13px] font-semibold text-ink-3">
                  {col}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {result.rows.map((row, i) => (
              <tr key={i} className={i % 2 === 0 ? 'bg-surface' : 'bg-stripe'}>
                {result.columns.map(col => {
                  const val = row[col];
                  const isNum = isNumericLike(val);
                  const isNull = val === null || val === undefined;
                  return (
                    <td key={col} className={cx('whitespace-nowrap border-b border-line-faint px-3.5 py-[7px] font-code', isNull ? 'italic text-subtle' : isNum ? 'text-number' : 'text-body', isNum ? 'text-right' : 'text-left')}>
                      {isNull ? 'null' : isNum && val !== null ? formatDisplayNumber(Number(val), { maximumFractionDigits: 6 }) : String(val)}
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
