import React, { memo } from 'react';
import { FormTemplateResponse, FormTemplate } from 'Containers/Forms/Models';
import { Table, TableBody, TableColumn, TableHeader, TableRow, Th } from 'Components/Table';
import { Icon } from 'Components/Icons';

import { formatDate } from 'Utils/helpers';
import { areEqual } from 'Utils/equalityChecks';
import { NoFormsTable } from '../NoFormsTable';

import classes from './formsList.module.css';

interface Props {
  forms: FormTemplateResponse;
  onDelete: (id: number) => void;
  onAdd: (e: any) => void;
  onClickRow?: (form: FormTemplate) => void;
}

const FormsList = ({ forms, onClickRow, onDelete, onAdd }: Props) => {
  const onRowClick = (e: any, form: any) => {
    e.preventDefault();
    onClickRow(form);
  };

  return (
    <>
      {forms?.data?.length > 0 ? (
        <Table className={`table ${classes.formListWrapper}`}>
          <TableHeader>
            <TableRow>
              <Th>Name</Th>
              <Th>Date Created</Th>
              <Th />
            </TableRow>
          </TableHeader>
          <TableBody>
            {forms.data.map((form: FormTemplate) => (
              <TableRow key={form.id}>
                <TableColumn dataId={form.id} tdOnClick={(e) => onRowClick(e, form)}>
                  <p>{form.name}</p>
                </TableColumn>
                <TableColumn dataId={form.id} tdOnClick={(e) => onRowClick(e, form)} className={classes.columnContent}>
                  <p className={classes.numberAndDate}>{formatDate(form.created_at, 'PP')}</p>
                </TableColumn>
                <TableColumn>
                  <button
                    className={classes.deleteBtn}
                    onClick={(e) => {
                      e.stopPropagation();
                      onDelete(form.id);
                    }}
                  >
                    <Icon type="trash" />
                  </button>
                </TableColumn>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      ) : (
        <NoFormsTable onAdd={onAdd} />
      )}
    </>
  );
};

FormsList.defaultProps = {
  onClickRow: null,
};

const FormsListMemo = memo(FormsList, areEqual);

export { FormsListMemo as FormsList };
