import { memo } from 'react'
import { Form, Input } from 'antd'
import { NamePath, Rule } from 'rc-field-form/lib/interface'

type EditableCellProps = React.DetailedHTMLProps<React.TdHTMLAttributes<HTMLTableDataCellElement>, HTMLTableDataCellElement> & {
  editing?: boolean
  dataIndex?: NamePath
  input?: React.Component
  isRequired?: boolean
  title: string
  formItemClass?: string
  formItemRules?: Rule[]
  children: React.ReactNode
  initialValue: any
}

export const EditableCell = memo<EditableCellProps>(({
  editing,
  dataIndex,
  input,
  isRequired,
  formItemClass,
  formItemRules,
  children,
  initialValue,
  ...other
}) => (
  <td style={editing ? { padding: 0 } : undefined} {...other}>
    {!editing ? children : (
      <Form.Item
        name={dataIndex}
        style={{ margin: 0 }}
        className={formItemClass}
        rules={formItemRules ?? [{
          required: isRequired,
          message: `Это обязательное поле!`,
        }]}
        initialValue={initialValue}
      >
        {input ?? <Input/>}
      </Form.Item>
    )}
  </td>
))
