'use client';

import { useT, useLocale } from '@/lib/i18n/react';
import { formatInteger } from '@/lib/format';
import { Table } from '@/components/ui/primitives/Table/Table';

type DeviceBreakdown = { mobile: number; desktop: number; bot: number; other: number };

type AudienceTabProps = {
  deviceBreakdown: DeviceBreakdown;
  countryBreakdown: Array<{ country: string; clicks: number }>;
};

function countryToFlag(iso: string): string {
  return iso
    .toUpperCase()
    .split('')
    .map((c) => String.fromCodePoint(0x1f1e6 + c.charCodeAt(0) - 65))
    .join('');
}

const DEVICE_BARS: Array<{ key: keyof DeviceBreakdown; color: string }> = [
  { key: 'mobile',  color: 'bg-blue-500' },
  { key: 'desktop', color: 'bg-green-500' },
  { key: 'other',   color: 'bg-yellow-500' },
  { key: 'bot',     color: 'bg-red-400' },
];

export function AudienceTab({ deviceBreakdown, countryBreakdown }: AudienceTabProps) {
  const t = useT('admin_sharing');
  const { locale } = useLocale();

  const deviceTotal = Object.values(deviceBreakdown).reduce((a, b) => a + b, 0);

  return (
    <div className="grid md:grid-cols-2 gap-6 mt-4">
      {/* Device breakdown */}
      <div className="border rounded-lg p-4">
        <h2 className="font-medium mb-4">{t('device_breakdown_title')}</h2>
        <ul className="space-y-3">
          {DEVICE_BARS.map(({ key, color }) => {
            const count = deviceBreakdown[key];
            const pct = deviceTotal > 0 ? Math.round((count / deviceTotal) * 100) : 0;
            return (
              <li key={key}>
                <div className="flex justify-between text-sm mb-1">
                  <span>{t(`device_${key}` as Parameters<typeof t>[0])}</span>
                  <span className="tabular-nums text-text-muted">
                    {formatInteger(count, locale)} ({pct}%)
                  </span>
                </div>
                <div className="h-2 rounded bg-muted overflow-hidden">
                  <div
                    className={`h-full rounded ${color}`}
                    style={{ width: `${pct}%` }}
                  />
                </div>
              </li>
            );
          })}
        </ul>
        {deviceTotal === 0 && (
          <p className="text-sm text-text-muted mt-4">{t('no_data')}</p>
        )}
      </div>

      {/* Country breakdown */}
      <div className="border rounded-lg p-4">
        <h2 className="font-medium mb-4">{t('country_breakdown_title')}</h2>
        {countryBreakdown.length > 0 ? (
          <Table>
            <Table.Head>
              <Table.Row>
                <Table.HeadCell>{t('country_col')}</Table.HeadCell>
                <Table.HeadCell className="text-end">{t('clicks_col')}</Table.HeadCell>
                <Table.HeadCell className="text-end">{t('pct_of_clicks')}</Table.HeadCell>
              </Table.Row>
            </Table.Head>
            <Table.Body>
              {countryBreakdown.map(({ country, clicks }) => {
                const pct = deviceTotal > 0 ? Math.round((clicks / deviceTotal) * 100) : 0;
                return (
                  <Table.Row key={country}>
                    <Table.Cell>
                      <span className="me-2">{countryToFlag(country)}</span>
                      <span>{country}</span>
                    </Table.Cell>
                    <Table.Cell className="text-end tabular-nums">
                      {formatInteger(clicks, locale)}
                    </Table.Cell>
                    <Table.Cell className="text-end tabular-nums text-text-muted">{pct}%</Table.Cell>
                  </Table.Row>
                );
              })}
            </Table.Body>
          </Table>
        ) : (
          <p className="text-sm text-text-muted">{t('no_data')}</p>
        )}
      </div>
    </div>
  );
}
