/**
 * Web Component wrapper for DataTable (hand-crafted WC adapter).
 * Custom element: <hf-data-table>
 *
 * @generated by scripts/generate-wc-components.ts
 * DO NOT EDIT MANUALLY
 */

import type { ColumnDef } from '@tanstack/react-table';
import React from 'react';
import { Avatar } from '../components';
import { Badge } from '../components';
import { createSelectColumn, DataTable } from '../components';
import {
  BaseCompoundWC,
  camelToKebab,
  dispatchEvent,
  installPropAccessors,
  type PropDefs,
  registerWC,
} from './_shared';

interface SimpleColumn {
  accessorKey: string;
  header: string;
  cellType?: 'text' | 'badge' | 'currency' | 'date' | 'avatar' | 'boolean';
  enableSorting?: boolean;
  width?: string;
  minWidth?: number;
  maxWidth?: number;
  align?: 'left' | 'center' | 'right';
  badgeColors?: Record<string, string>;
  currencyCode?: string;
  dateFormat?: string;
}

function renderCell(column: SimpleColumn, value: unknown): React.ReactElement {
  if (value == null) {
    return React.createElement(
      'span',
      { className: 'text-muted-foreground' },
      '—',
    );
  }

  switch (column.cellType) {
    case 'badge': {
      const text = String(value);
      const color = column.badgeColors?.[text] ?? 'gray';
      return React.createElement(
        Badge,
        { variant: 'pill-color', color: color as 'gray', size: 'sm' },
        text,
      );
    }
    case 'currency': {
      const numberValue = typeof value === 'number' ? value : Number(value);
      return React.createElement(
        'span',
        null,
        new Intl.NumberFormat('en-US', {
          style: 'currency',
          currency: column.currencyCode || 'USD',
        }).format(numberValue),
      );
    }
    case 'date': {
      const date = value instanceof Date ? value : new Date(String(value));
      return React.createElement(
        'span',
        null,
        date.toLocaleDateString('en-US', {
          year: 'numeric',
          month: 'short',
          day: 'numeric',
        }),
      );
    }
    case 'avatar': {
      const src = typeof value === 'string' ? value : undefined;
      return React.createElement(Avatar, { src, size: 'sm' });
    }
    case 'boolean': {
      const enabled = Boolean(value);
      return React.createElement(
        'span',
        { className: enabled ? 'text-success' : 'text-muted-foreground' },
        enabled ? 'Yes' : 'No',
      );
    }
    default:
      return React.createElement('span', null, String(value));
  }
}

function buildColumns(
  simpleColumns: SimpleColumn[],
  enableRowSelection: boolean,
): ColumnDef<Record<string, unknown>, unknown>[] {
  const columns: ColumnDef<Record<string, unknown>, unknown>[] = [];

  if (enableRowSelection) {
    columns.push(createSelectColumn<Record<string, unknown>>());
  }

  for (const column of simpleColumns) {
    const columnDef: ColumnDef<Record<string, unknown>, unknown> = {
      accessorKey: column.accessorKey,
      header: column.header,
      enableSorting: column.enableSorting ?? true,
      size: column.width
        ? Number.parseInt(column.width, 10) || undefined
        : undefined,
      minSize: column.minWidth,
      maxSize: column.maxWidth,
      meta: {
        cellClassName: column.align ? `text-${column.align}` : undefined,
        headerClassName: column.align ? `text-${column.align}` : undefined,
      },
    };

    if (column.cellType && column.cellType !== 'text') {
      columnDef.cell = ({ getValue }) => renderCell(column, getValue());
    }

    columns.push(columnDef);
  }

  return columns;
}

const PROP_DEFS: PropDefs = {
  columns: 'json',
  data: 'json',
  enableRowSelection: 'boolean',
  enableMultiRowSelection: 'boolean',
  enableSorting: 'boolean',
  enablePagination: 'boolean',
  pageSize: 'number',
  density: 'string',
  dividers: 'string',
  rounded: 'string',
  bordered: 'boolean',
  maxHeight: 'string',
  stickyHeader: 'boolean',
  caption: 'string',
  showSelectAll: 'boolean',
  paginationType: 'string',
  paginationShape: 'string',
  rowIdKey: 'string',
};

class DataTableWC extends BaseCompoundWC {
  get propDefs() {
    return PROP_DEFS;
  }

  static get observedAttributes() {
    return Object.keys(PROP_DEFS).map(camelToKebab);
  }

  protected _renderReact(): React.ReactElement {
    const props = this._readAllProps();

    const simpleColumns = (props.columns as SimpleColumn[]) || [];
    const data = (props.data as Record<string, unknown>[]) || [];
    const enableRowSelection = (props.enableRowSelection as boolean) || false;
    const rowIdKey = (props.rowIdKey as string) || 'id';

    const columns = buildColumns(simpleColumns, enableRowSelection);

    return React.createElement(DataTable, {
      columns,
      data,
      getRowId: (row: Record<string, unknown>) => String(row[rowIdKey] ?? ''),
      enableRowSelection,
      enableMultiRowSelection:
        (props.enableMultiRowSelection as boolean) ?? true,
      enableSorting: (props.enableSorting as boolean) ?? true,
      enablePagination: (props.enablePagination as boolean) ?? false,
      pageSize: (props.pageSize as number) || 10,
      dividers: (props.dividers as 'line' | 'alternating') || 'line',
      density: (props.density as 'default' | 'compact') || 'default',
      rounded: (props.rounded as 'all' | 'none' | 'top' | 'bottom') || 'all',
      bordered: props.bordered !== false,
      caption: props.caption as string | undefined,
      showSelectAll: (props.showSelectAll as boolean) ?? true,
      paginationType: props.paginationType as string | undefined,
      paginationShape:
        (props.paginationShape as 'square' | 'circle') || undefined,
      className: props.maxHeight
        ? `max-h-[${String(props.maxHeight)}] overflow-auto`
        : undefined,
      onRowClick: (row) => dispatchEvent(this, 'row-click', row.original),
      onRowSelectionChange: (updater) => {
        const nextState = typeof updater === 'function' ? updater({}) : updater;
        dispatchEvent(this, 'selection-change', nextState);
      },
      onSortingChange: (updater) => {
        const nextState = typeof updater === 'function' ? updater([]) : updater;
        dispatchEvent(this, 'sorting-change', nextState);
      },
      onPaginationChange: (updater) => {
        const defaultPagination = {
          pageIndex: 0,
          pageSize: (props.pageSize as number) || 10,
        };
        const nextState =
          typeof updater === 'function' ? updater(defaultPagination) : updater;
        dispatchEvent(this, 'page-change', nextState);
      },
    });
  }
}

installPropAccessors(DataTableWC, PROP_DEFS);
registerWC('hf-data-table', DataTableWC);

export { DataTableWC };
export default DataTableWC;
