'use client';

import {Table} from '@astryxdesign/core/Table';
import type {TableColumn} from '@astryxdesign/core/Table';
import {Card} from '@astryxdesign/core/Card';
import {VStack, HStack} from '@astryxdesign/core/Layout';
import {Text} from '@astryxdesign/core/Text';
import {Divider} from '@astryxdesign/core/Divider';
import {useBreakpoint} from '@/shared/hooks/useBreakpoint';

/**
 * A table on wide screens; a list of cards on a phone.
 *
 * A six-column table cannot be made to work at 375px. Horizontal scroll is the
 * usual fallback, but it hides the columns that matter most — status and
 * actions sit on the right, which is exactly what is off-screen — and it puts
 * a scroll gesture inside a vertically scrolling page, which fights the thumb.
 *
 * So below `tablet` the same column definitions are re-rendered as stacked
 * label/value rows. Crucially it is the SAME `columns` array: the cell
 * renderers, formatting and badges are reused verbatim, so the two
 * presentations cannot drift and adding a column updates both.
 *
 * `primaryKey` names the column that becomes the card's heading — usually the
 * entity's name. `summaryKeys`, when given, limits which of the remaining
 * columns appear on the card, because a phone card listing nine fields is just
 * a table rotated 90°.
 */
export function ResponsiveTable<T extends Record<string, unknown>>({
  data,
  columns,
  idKey,
  primaryKey,
  summaryKeys,
  density = 'spacious',
}: {
  data: T[];
  columns: TableColumn<T>[];
  /** Row identity. Falls back to the array index when a row has no id field. */
  idKey?: keyof T & string;
  primaryKey: string;
  summaryKeys?: string[];
  density?: 'compact' | 'balanced' | 'spacious';
}) {
  const bp = useBreakpoint();

  if (bp !== 'mobile') {
    return (
      <Table
        data={data}
        columns={columns}
        idKey={idKey}
        density={density}
        hasHover
      />
    );
  }

  const primary = columns.find((c) => c.key === primaryKey);
  const rest = columns.filter(
    (c) =>
      c.key !== primaryKey &&
      (summaryKeys ? summaryKeys.includes(c.key) : true),
  );

  return (
    <VStack gap={3}>
      {data.map((row, i) => (
        <Card key={idKey ? String(row[idKey]) : i} variant="muted">
          <VStack gap={3}>
            {primary ? (
              <VStack gap={0}>
                {primary.renderCell
                  ? primary.renderCell(row)
                  : String(row[primary.key] ?? '')}
              </VStack>
            ) : null}

            {rest.length ? <Divider /> : null}

            <VStack gap={2}>
              {rest.map((col) => (
                <HStack key={col.key} hAlign="between" vAlign="center" gap={3}>
                  <Text size="sm" color="secondary">
                    {typeof col.header === 'string' ? col.header : col.key}
                  </Text>
                  {/* The real cell renderer — badges, deltas and progress bars
                      all survive the transposition unchanged. */}
                  {col.renderCell
                    ? col.renderCell(row)
                    : <Text size="sm">{String(row[col.key] ?? '')}</Text>}
                </HStack>
              ))}
            </VStack>
          </VStack>
        </Card>
      ))}
    </VStack>
  );
}
