import CountryFlag from '~/src/components/CountryFlag';
import { useI18n } from '~/src/lib/i18n';
import { CityTotal } from '~/src/lib/songwhipApi/analytics/types';
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 CitiesTable = ({ data }: { data: CityTotal[] }) => {
  const { t } = useI18n();

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

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

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

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