import CountryFlag from '~/src/components/CountryFlag';
import { useI18n } from '~/src/lib/i18n';
import { getCountryName } from '~/src/lib/utils/countriesByCode';
import { Table } from '~/src/ui/components/table';
import { Layout } from '~/src/ui/layouts/layout';
import { Text } from '~/src/ui/primitives/text';
import { createTotalRow } from '../utils';
import { TotalRow } from './TotalsRow';

export const CountriesTable = ({
  data,
}: {
  data: { country: string; total: number }[];
}) => {
  const { t } = useI18n();

  const withCountryNames = data.map((row) => ({
    ...row,
    countryName: getCountryName(row.country),
  }));

  const totalsRow = createTotalRow(withCountryNames, 'country');

  return (
    <Table
      maxHeight="50rem"
      rows={[totalsRow, ...withCountryNames]}
      getRowKey={(row) => row.country}
      columns={[
        {
          key: 'country',
          header: t('dashboard.labels.country'),
          renderCell: (row, { rowIndex }) => {
            if (rowIndex === 0) {
              return <TotalRow total={data.length} />;
            }

            return (
              <Layout gap="2" align="center">
                <CountryFlag countryCode={row.country} />
                <Text variant="body-small">
                  {row.countryName || t('dashboard.labels.unknown')}
                </Text>
              </Layout>
            );
          },
        },
        {
          key: 'total',
          header: t('dashboard.labels.clicks'),
          align: 'right',
          renderCell: (row) => {
            return row.total;
          },
        },
      ]}
    />
  );
};
