import React, { useEffect } from 'react';
import styled from 'styled-components';

import TableRow from './TableRow';
import useInit from './useTableState';

const Table = styled.table`
  width: 100%;
  th,
  td {
    padding-right: 2em;
  }
  tr {
    border-bottom: 1px solid grey;
    border-top: 1px solid grey;
  }
`;

const LogicTable = () => {
  const [
    { isLoading, isError, logics, nextTasks, agbID },
    { onChange, onDelete, onClickUp, onClickDown, onSave, setLogics }
  ] = useInit();

  useEffect(() => {
    document.getElementById('save-mwt').onclick = (e) => {
      e.preventDefault();
      
      const saveResult = onSave();
      
      if (saveResult) {
        (window as any).saveMWT(agbID);
      }
    };
    
  });
  const onAddCondition = (rowIndex: number) => {
    setLogics((prevLogics) => {
      const updatedLogics = [...prevLogics];
      const conditions = updatedLogics[rowIndex].conditions || [];
      updatedLogics[rowIndex].conditions = [
        ...conditions,
        { condition: '', value: ''}
      ];
      return updatedLogics;
    });
  };

  const onRemoveCondition = (rowIndex: number, conditionIndex: number) => {
    setLogics((prevLogics) => {
      const updatedLogics = [...prevLogics];
      const conditions = updatedLogics[rowIndex].conditions || [];
      updatedLogics[rowIndex].conditions = conditions.filter(
        (_, index) => index !== conditionIndex
      );
      return updatedLogics;
    });
  };

  if (isError) {
    return <h1>isError</h1>;
  }

  if (isLoading) {
    return <h1>isLoading</h1>;
  }

  return (
    <form>
      <Table>
        <thead>
          <tr>
            <th></th>
            <th>Bedingung</th>
            <th>Wert</th>
            <th>Aufgabe</th>
            <th>Löschen</th>
          </tr>
        </thead>
        <tbody>
          <TableRow
            fields={logics}
            onChange={onChange}
            onDelete={onDelete}
            taskSelectOptions={nextTasks}
            onClickUp={onClickUp}
            onClickDown={onClickDown}
            onAddCondition={onAddCondition}
            onRemoveCondition={onRemoveCondition}
          />
        </tbody>
      </Table>
    </form>
  );
};

export default LogicTable;
