import { flexRender, type Table as TableInstance } from '@tanstack/react-table';
import { ArrowDownIcon, ArrowUpIcon, ArrowUpDownIcon } from 'lucide-react';

import type { Post } from '@/entities/post';
import { Button } from '@/shared/ui/button';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/shared/ui/table';

type PostTableViewProps = {
  table: TableInstance<Post>;
  sort: 'asc' | 'desc' | null;
  onCycleSort: () => void;
  emptyMessage: string;
};

const ARIA_SORT = { asc: 'ascending', desc: 'descending' } as const;
const SORT_ICONS = { asc: ArrowUpIcon, desc: ArrowDownIcon } as const;
const SORT_LABELS = {
  asc: '오름차순 정렬됨',
  desc: '내림차순 정렬됨',
} as const;

export const PostTableView = ({
  table,
  sort,
  onCycleSort,
  emptyMessage,
}: PostTableViewProps) => {
  'use no memo';
  const ariaSort = sort === null ? 'none' : ARIA_SORT[sort];
  const SortIcon = sort === null ? ArrowUpDownIcon : SORT_ICONS[sort];
  const rows = table.getRowModel().rows;

  return (
    <div className="overflow-x-auto">
      <Table>
        <TableHeader>
          <TableRow>
            {table.getFlatHeaders().map((header) => {
              const isTitle = header.column.id === 'title';
              return (
                <TableHead
                  key={header.id}
                  aria-sort={isTitle ? ariaSort : undefined}
                >
                  {isTitle ? (
                    <Button variant="ghost" size="sm" onClick={onCycleSort}>
                      제목
                      <SortIcon aria-hidden className="size-3.5" />
                      <span className="sr-only">
                        {sort === null ? '정렬 없음' : SORT_LABELS[sort]}
                      </span>
                    </Button>
                  ) : (
                    flexRender(
                      header.column.columnDef.header,
                      header.getContext()
                    )
                  )}
                </TableHead>
              );
            })}
          </TableRow>
        </TableHeader>
        <TableBody>
          {rows.map((row) => (
            <TableRow key={row.id}>
              {row.getVisibleCells().map((cell) => (
                <TableCell
                  key={cell.id}
                  className="max-w-64 truncate py-3 align-middle"
                >
                  {flexRender(cell.column.columnDef.cell, cell.getContext())}
                </TableCell>
              ))}
            </TableRow>
          ))}
          {rows.length === 0 && (
            <TableRow>
              <TableCell
                colSpan={table.getAllColumns().length}
                className="text-center"
              >
                {emptyMessage}
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  );
};
