import { useState } from 'react';
import type { LexicalEditor } from 'lexical';
import { INSERT_TABLE_COMMAND } from '@lexical/table';

import { Button } from '../../../button';
import { Dialog } from '../../../dialog';
import { InputWithLabel } from '../../../input-with-label';
import { useTr } from '../../i18n';

export function InsertTableDialog({ activeEditor }: { activeEditor: LexicalEditor }) {
  const [rows, setRows] = useState('5');
  const [columns, setColumns] = useState('5');
  const tr = useTr();

  const onClick = () => {
    if (parseInt(rows) < 1 || parseInt(columns) < 1) {
      return;
    }
    activeEditor.dispatchCommand(INSERT_TABLE_COMMAND, {
      columns,
      rows,
      includeHeaders: {
        columns: false,
        rows: false,
      },
    });
  };

  return (
    <div className="c-rte-insert-table">
      <div className="c-rte-insert-table__dimensions">
        <InputWithLabel
          label={tr('insertTableRows')}
          value={rows}
          placeholder="0"
          type="text"
          inputMode="numeric"
          onChange={e => setRows(e.target.value)}
        />
        <span className="c-rte-insert-table__dimensions__separator" />
        <InputWithLabel
          type="text"
          label={tr('insertTableColumns')}
          placeholder="0"
          value={columns}
          inputMode="numeric"
          onChange={e => setColumns(e.target.value)}
        />
      </div>
      <div className="c-rte-insert-table__actions">
        <Button as={Dialog.Close} size="sm" intent="action" aria-label={tr('insertTableCommit')} onClick={onClick}>
          {tr('insertTableCommit')}
        </Button>
      </div>
    </div>
  );
}
