'use client';

import {proportional, pixel} from '@astryxdesign/core/Table';
import {ResponsiveTable} from '@/shared/components/patterns/ResponsiveTable';
import type {TableColumn} from '@astryxdesign/core/Table';
import {Badge} from '@astryxdesign/core/Badge';
import {Text} from '@astryxdesign/core/Text';
import {HStack} from '@astryxdesign/core/Layout';
import {PanelCard} from '@/shared/components/patterns/PanelCard';
import {SkeletonRows} from '@/shared/components/patterns/LoadingState';
import {EmptyPanel} from '@/shared/components/patterns/EmptyPanel';
import {MetricDelta} from '@/shared/components/primitives/MetricDelta';
import {formatCompact, formatLyt} from '@/shared/utils/format';
import {REWARD_STATUS} from '@/features/lyts/utils/rewardStatus';
import {usageRate} from '@/features/lyts/services/lytsService';
import type {Reward} from '@/features/lyts/types/reward';
import type {Resource} from '@/shared/hooks/useResource';

interface Row extends Record<string, unknown> {
  id: string;
  name: string;
  status: Reward['status'];
  costLyt: number;
  claimed: number;
  used: number;
  rate: number;
  outstanding: number;
}

/**
 * The whole catalogue as rows.
 *
 * A table rather than more cards: this is the view for comparing eight
 * rewards on the same four numbers, and cards force the eye to travel in two
 * dimensions to do a one-dimensional comparison. Sorted by redemption rate so
 * the offers that aren't working surface at the bottom without hunting.
 */
export function RewardPerformanceTable({
  resource,
}: {
  resource: Resource<Reward[]>;
}) {
  const columns: TableColumn<Row>[] = [
    {
      key: 'name',
      header: 'Reward',
      width: proportional(2),
      renderCell: (row) => (
        <HStack gap={2} vAlign="center">
          <Text size="base" weight="semibold">
            {row.name}
          </Text>
          <Badge
            variant={REWARD_STATUS[row.status].variant}
            label={REWARD_STATUS[row.status].label}
          />
        </HStack>
      ),
    },
    {
      key: 'costLyt',
      header: 'Cost',
      width: pixel(104),
      align: 'end',
      renderCell: (row) => <Text size="base" weight="medium">{formatLyt(row.costLyt)}</Text>,
    },
    {
      key: 'claimed',
      header: 'Claimed',
      width: pixel(104),
      align: 'end',
      renderCell: (row) => <Text size="base" weight="medium">{formatCompact(row.claimed)}</Text>,
    },
    {
      key: 'used',
      header: 'Redeemed',
      width: pixel(112),
      align: 'end',
      renderCell: (row) => <Text size="base" weight="medium">{formatCompact(row.used)}</Text>,
    },
    {
      key: 'rate',
      header: 'Rate',
      width: pixel(112),
      align: 'end',
      renderCell: (row) => (
        <HStack hAlign="end">
          <MetricDelta value={row.rate - 50} isRiseGood size="sm" />
        </HStack>
      ),
    },
    {
      key: 'outstanding',
      header: 'Outstanding',
      width: pixel(140),
      align: 'end',
      renderCell: (row) => (
        <Text size="base" weight="semibold">{formatLyt(row.outstanding)}</Text>
      ),
    },
  ];

  return (
    <PanelCard
      title="Reward performance"
      subtitle="Sorted by redemption rate — the weakest offers sit at the bottom"
      resource={resource}
      loading={<SkeletonRows count={6} height={32} />}
      empty={
        <EmptyPanel
          icon="lyts"
          title="No rewards to compare"
          description="Performance appears once rewards have been claimed."
        />
      }
    >
      {(rewards) => {
        const rows: Row[] = rewards
          .map((r) => ({
            id: r.id,
            name: r.name,
            status: r.status,
            costLyt: r.costLyt,
            claimed: r.claimed,
            used: r.used,
            rate: usageRate(r.claimed, r.used),
            outstanding: (r.claimed - r.used) * r.costLyt,
          }))
          .sort((a, b) => b.rate - a.rate);

        return (
          <ResponsiveTable
            data={rows}
            columns={columns}
            idKey="id"
            primaryKey="name"
            density="compact"
          />
        );
      }}
    </PanelCard>
  );
}
