import React, { ReactNode, useState } from 'react';
import classNames from 'classnames';
import Accordion from '../Accordion';
import './TableWithAccordion.scss';
import Icon from '../Icon';
import NoData from '../NoData/NoData';
import Tooltip from '../Tooltip';
import '../../../index.scss';

interface ColumnProps {
  /**
   * column name
   */
  header: string;
  /**
   * data key for particular column
   */
  accessor: string;
  /**
   * className for a column
   */
  className?: string;
  /**
   * width of a column
   */
  width?: number;
  /**
   * data for the column
   */
  cell?: (e: any) => JSX.Element | string | ReactNode;
}
interface DataProps {
  /**
   * data for each row
   */
  [key: string]: any;
}
export interface TableProps {
  /**
   * Column details for table
   */
  tableMeta: Array<ColumnProps>;
  /**
   * Data for table
   */
  tableData: Array<DataProps>;
  /**
   * Table type
   */
  accordionType: 'row' | 'column';
  /**
   *  Specific sentence to be displayed data not found
   */
  noDataText?: string;
  /**
   * Size of the image that to be displayed if you don't have data
   */
  noDataImageSize?: 'x-large' | 'large' | 'medium' | 'small' | 'x-small';
  /**
   * Header type
   */
  variant: 'primary' | 'secondary';
  /**
   * withFixedHeader prop to have non-scrollable fixed accordion table header
   */
  withFixedHeader?: boolean;
  /**
   *  Height of the table in string
   */
  height?: string;
  /**
   * Header type to have different background color
   */
  headerType: 'default' | 'primary' | 'secondary';
}
const TableWithAccordion = ({
  tableMeta = [],
  tableData = [],
  accordionType = 'row',
  noDataText = 'No Data Found',
  noDataImageSize,
  variant = 'secondary',
  height = '100%',
  withFixedHeader = false,
  headerType,
}: TableProps) => {
  const [expandedRowIndex, setExpandedRowIndex] = useState(-1);
  const onAccordionClick = (index: number) => {
    setExpandedRowIndex(index === expandedRowIndex ? -1 : index);
  };
  const prepareCellData = (dataObj: any, columnObj: ColumnProps) => {
    let cellData = dataObj[columnObj.accessor];
    if (columnObj.cell) {
      return columnObj.cell({
        value: cellData,
        row: dataObj,
        column: columnObj.accessor,
      });
    } else if (columnObj.accessor) {
      return cellData;
    } else if (cellData && typeof cellData !== 'object') {
      return cellData;
    } else {
      return '--';
    }
  };
  const prepareData = (dataArray: any) => {
    const accordionSubTable = dataArray.map((rowData: any, index: number) => {
      return (
        <table className="ff-accordion-table" cellSpacing={0}>
          <tbody>
            <tr key={rowData.id || index}>
              {tableMeta.map((column, i) => {
                return (
                  <td key={column.accessor + i} style={{ width: column.width }}>
                    {accordionType === 'column' && i === 0
                      ? ''
                      : prepareCellData(rowData, column)}
                  </td>
                );
              })}
            </tr>
          </tbody>
        </table>
      );
    });
    return accordionSubTable;
  };
  return (
    <div
      style={{ height: height }}
      className={classNames('ff-accordion-table-container', {
        'ff-accordion-fixed-header-table': withFixedHeader,
      })}
    >
      <table
        cellSpacing={0}
        className={classNames('ff-accordion-table', {
          'ff-accordion-fixed-header': withFixedHeader,
        })}
      >
        <thead>
          <tr>
            {tableMeta.map((column) => (
              <th
                key={column.header}
                style={{ width: column.width }}
                className={headerType && `ff-accordion-table--${headerType}-bg`}
              >
                <div>{column.header}</div>
              </th>
            ))}
          </tr>
        </thead>
      </table>
      {accordionType === 'row' &&
        tableData.map((row: any, index: number) => (
          <Accordion
            headerTitle={row.title}
            variant={variant}
            accordionContent={prepareData(row.data)}
            disable={row.disable}
            disableInfoMessage={row.disableInfoMessage}
          />
        ))}
      {accordionType === 'column' &&
        tableData.map((row: any, index: number) => (
          <div className="column-table-accordion">
            <div className="ff-display-flex">
              <Tooltip title={row?.disableInfoMessage}>
                <div
                  className={`accordion-header ${row.disable && 'ff-disabled'}`}
                >
                  <div className="header-title">
                    <span>{row.title}</span>
                  </div>

                  <div
                    className="accordion-arrow"
                    onClick={() => {
                      !row.disable && onAccordionClick(index);
                    }}
                  >
                    <Icon
                      name={
                        expandedRowIndex === index
                          ? 'arrow_down'
                          : 'arrow_right'
                      }
                      hoverEffect={false}
                    />
                  </div>
                </div>
              </Tooltip>
            </div>
            {expandedRowIndex === index && <div>{prepareData(row.data)}</div>}
          </div>
        ))}
      {tableData.length <= 0 && (
        <NoData content={noDataText} size={noDataImageSize} />
      )}
    </div>
  );
};

export default TableWithAccordion;
