import React from 'react'
import { VARIANT_NAME_MAP } from './galleryUtils'
import MetricInfoIcon from './MetricInfoIcon'

interface ExampleVariantMetricsTablesProps {
  variantMetadatas: Record<string, Record<string, string | number | boolean>>
}

const ACCURACY_METRICS = ['bit_acc', 'word_acc', 'log10_p_value']

const ExampleVariantMetricsTables: React.FC<ExampleVariantMetricsTablesProps> = ({
  variantMetadatas,
}) => {
  const variantKeys = Object.keys(variantMetadatas)
  if (variantKeys.length === 0) return null

  // Collect all unique metadata keys across all variants
  let allKeys = Array.from(
    new Set(variantKeys.flatMap((variant) => Object.keys(variantMetadatas[variant] || {})))
  )

  // Split keys into accuracy and quality metrics
  const accuracyKeys = [...ACCURACY_METRICS.filter((k) => allKeys.includes(k))]
  if (allKeys.includes('detected')) {
    accuracyKeys.unshift('detected')
  }
  const qualityKeys = allKeys.filter((k) => !accuracyKeys.includes(k) && k !== 'detected')

  // Helper to render a table for a set of keys and a set of variants
  const renderTable = (keys: string[], title: string, rowVariants: string[]) =>
    keys.length === 0 ? null : (
      <div className="overflow-x-auto mb-4">
        <div className="mb-1 text-sm">{title}</div>
        <table className="table w-full min-w-max border-gray-700 border text-xs">
          <thead>
            <tr>
              <th className="bg-base-100 border-gray-700 border">Variant</th>
              {keys.map((k) => (
                <th key={k} className="bg-base-100 border-gray-700 border text-center">
                  <span className="inline-flex items-center gap-1">
                    {k}
                    {k !== 'detected' && <MetricInfoIcon metricName={k} />}
                  </span>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rowVariants.map((variant) =>
              variantKeys.includes(variant) ? (
                <tr key={variant} className="hover:bg-base-100">
                  <td className="font-mono border-gray-700 border">
                    {VARIANT_NAME_MAP[variant] || variant}
                  </td>
                  {keys.map((k) => (
                    <td key={k} className="border-gray-700 border text-center">
                      {variantMetadatas[variant] && k in variantMetadatas[variant]
                        ? String(variantMetadatas[variant][k])
                        : ''}
                    </td>
                  ))}
                </tr>
              ) : null
            )}
          </tbody>
        </table>
      </div>
    )

  return (
    <>
      {renderTable(accuracyKeys, 'Accuracy Metrics', ['wmd', 'attacked_wmd'])}
      {renderTable(qualityKeys, 'Quality Metrics', ['wmd'])}
    </>
  )
}

export default ExampleVariantMetricsTables
