import { useEffect } from 'react';
import {
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow
} from '@mui/material';

import { useAppDispatch, useAppSelector } from '../store';
import { selectPolicyExecution } from '../store/hostsSlice/selectors';
import { fetchPolicyExecution } from '../store/hostsSlice/thunks';

interface Props {
  hostkey: string;
}

export const PolicyExecutionSection = ({ hostkey }: Props) => {
  const dispatch = useAppDispatch();
  const data = useAppSelector(state => selectPolicyExecution(state, hostkey));

  useEffect(() => {
    if (hostkey) dispatch(fetchPolicyExecution(hostkey));
  }, [dispatch, hostkey]);

  if (!data || !data.rows || data.rows.length === 0) {
    return null;
  }

  return (
    <div>
      <h4>Agent execution time</h4>
      <TableContainer component={Paper}>
        <Table size="small">
          <TableHead>
            <TableRow>
              {data.header.map((col, i) => (
                <TableCell key={i}>{col.columnName}</TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {data.rows.map((row, ri) => (
              <TableRow key={ri}>
                {row.map((cell, ci) => (
                  <TableCell key={ci}>{cell == null ? '' : String(cell)}</TableCell>
                ))}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </div>
  );
};
