import React, { useState } from "react";
import { TableCell, TableRow, TextField } from "@material-ui/core";
import { Link } from "react-router-dom";
import DeleteIcon from "@material-ui/icons/Delete";

const DataDisplay = ({ data, option, onDelete }) => {
  const [text, setText] = useState(data[option.field]);
  const onChange = (e) => {
    data[e.target.id] = e.target.value;
    setText(e.target.value);
  };
  const deleteHandler = (id) => {
    if (onDelete) onDelete(id);
  };

  if (option.readonly) {
    return `${data[option.field]}`;
  } else if (option.delete) {
    const idField = option.field || "data_id";

    return (
      <Link
        to="#"
        onClick={() => {
          deleteHandler(data[idField]);
        }}
      >
        <DeleteIcon />
      </Link>
    );
  } else if (option.control) {
    return (
      <option.control
        id={option.field}
        name={option.field}
        value={text}
        changeHandler={onChange}
      ></option.control>
    );
  }

  return (
    <TextField
      id={option.field}
      name={option.field}
      placeholder={option.label}
      inputProps={option.inputProps}
      requried={option.required ? "true" : "false"}
      fullWidth
      onChange={onChange}
      value={text}
    ></TextField>
  );
};

const SubListItem = ({ data, options, onDelete }) => {
  return (
    <TableRow>
      {options.map((item) => (
        <TableCell key={item.label} width={item.delete ? 25 : null}>
          <DataDisplay data={data} option={item} onDelete={onDelete} />
        </TableCell>
      ))}
    </TableRow>
  );
};

export default SubListItem;
