'use client';

import Link from 'next/link';
import { Fragment } from 'react';
import type { ViewRowHeight, ViewSort } from '@/features/views/types';
import { cn } from '@/lib/utils/cn';
import type { ObjectColumn } from '../columns';
import { objectRecordPath } from '../paths';
import type { ObjectRecord } from '../types';
import { Icon } from './icons';
import { RowAssociations } from './RowAssociations';
import { nameInText } from '@/features/objects/paths';

/**
 * `.evl-table`: one row per record, the columns of the view. The name column has the expand
 * arrow (linked records under the row), opens the preview, and shows the preview / edit buttons
 * on hover. Headers of the columns the API can sort by sort on click.
 */
export function ObjectTable({
  objectKey,
  plural,
  rows,
  columns,
  selected,
  onToggle,
  onToggleAll,
  sort,
  onSort,
  expanded,
  onExpand,
  onPreview,
  rowHeight,
  pinned,
  linkTypes,
}: {
  objectKey: string;
  plural: string;
  rows: ObjectRecord[];
  columns: ObjectColumn[];
  selected: ReadonlySet<string>;
  onToggle: (id: string) => void;
  onToggleAll: () => void;
  sort: ViewSort;
  onSort: (field: string) => void;
  expanded: string | null;
  onExpand: (id: string | null) => void;
  onPreview: (row: ObjectRecord, edit: boolean) => void;
  rowHeight: ViewRowHeight;
  pinned: boolean;
  linkTypes: Array<{ type: string; plural: string }>;
}) {
  const allSelected = rows.length > 0 && rows.every((r) => selected.has(r.id));
  const someSelected = !allSelected && rows.some((r) => selected.has(r.id));

  return (
    <table
      className={cn(
        'evl-table',
        rowHeight !== 'default' && `evl-table--${rowHeight}`,
        pinned && 'is-pinned',
      )}
      aria-label={plural}
    >
      <thead>
        <tr>
          <th className="evl-table__check" scope="col">
            <input
              type="checkbox"
              aria-label={`Select all ${nameInText(plural)} on this page`}
              checked={allSelected}
              ref={(el) => {
                if (el) el.indeterminate = someSelected;
              }}
              onChange={onToggleAll}
            />
          </th>
          {columns.map((col, i) => {
            const active = col.sort && sort.field === col.sort;
            return (
              <th
                key={col.id}
                scope="col"
                className={cn(i === 0 && 'evl-table__name', col.numeric && 'is-num')}
                aria-sort={
                  active ? (sort.direction === 'asc' ? 'ascending' : 'descending') : undefined
                }
              >
                {col.sort ? (
                  <button
                    type="button"
                    className="evl-th"
                    onClick={() => onSort(col.sort!)}
                    title={`Sort by ${col.label}`}
                  >
                    {col.label}
                    {active ? (
                      <Icon name={sort.direction === 'asc' ? 'sortUp' : 'sortDown'} size={12} />
                    ) : null}
                  </button>
                ) : (
                  col.label
                )}
              </th>
            );
          })}
        </tr>
      </thead>
      <tbody>
        {rows.map((row) => {
          const isOpen = expanded === row.id;
          const isSelected = selected.has(row.id);
          const name = row.displayName || 'Untitled';
          return (
            <Fragment key={row.id}>
              <tr className={cn(isSelected && 'is-selected', isOpen && 'is-open')}>
                <td className="evl-table__check">
                  <input
                    type="checkbox"
                    aria-label={`Select ${name}`}
                    checked={isSelected}
                    onChange={() => onToggle(row.id)}
                  />
                </td>
                {columns.map((col, i) =>
                  i === 0 ? (
                    <td key={col.id} className="evl-table__name">
                      <div className="evl-name">
                        <button
                          type="button"
                          className="evl-name__toggle"
                          aria-expanded={isOpen}
                          aria-label={
                            isOpen ? `Hide ${name} associations` : `Show ${name} associations`
                          }
                          onClick={() => onExpand(isOpen ? null : row.id)}
                        >
                          <Icon name={isOpen ? 'chevronDown' : 'chevronRight'} size={12} />
                        </button>
                        <Link className="evl-name__link" href={objectRecordPath(objectKey, row.id)}>
                          {name}
                        </Link>
                        <span className="evl-name__tools">
                          <button
                            type="button"
                            className="ev-iconbtn ev-iconbtn--round ev-iconbtn--xs"
                            aria-label={`Preview ${name}`}
                            title="Preview"
                            onClick={() => onPreview(row, false)}
                          >
                            <Icon name="eye" size={12} />
                          </button>
                          <button
                            type="button"
                            className="ev-iconbtn ev-iconbtn--round ev-iconbtn--xs"
                            aria-label={`Edit ${name}`}
                            title="Edit"
                            onClick={() => onPreview(row, true)}
                          >
                            <Icon name="pencil" size={12} />
                          </button>
                        </span>
                      </div>
                    </td>
                  ) : (
                    <td key={col.id} className={cn(col.numeric && 'is-num')}>
                      {col.text(row)}
                    </td>
                  ),
                )}
              </tr>
              {isOpen ? (
                <tr className="evl-table__expand">
                  <td />
                  <td colSpan={columns.length}>
                    <RowAssociations objectKey={objectKey} record={row} types={linkTypes} />
                  </td>
                </tr>
              ) : null}
            </Fragment>
          );
        })}
      </tbody>
    </table>
  );
}
