import React from 'react';
import { useResource } from 'rest-hooks';
import SampleResource from '../../resources/sample';
import ResponsiveTable from '../Table/ResponsiveTable';
import { getSamplePageURL } from '../../helpers';

const COLUMNS = [
  { text: '', dataField: 'id', hidden: true },
  {
    text: 'Name',
    dataField: 'name',
    sort: true,
    formatter: (name, sample) => {
      const sampleURL = getSamplePageURL(sample);
      if (!sampleURL) {
        return name;
      }

      return (
        <a target="_blank" rel="noopener noreferrer" href={sampleURL}>
          {name}
        </a>
      );
    },
  },
  {
    dataField: 'description',
    text: 'Description',
    formatter: (cell, sample) => {
      if (sample.parameters) {
        const parameter = sample.parameters.find(
          (parameter) => parameter.name === 'Sample_description'
        );
        if (parameter) return parameter.value;
      }
    },
    sort: true,
    responsiveHeaderStyle: {
      md: { hidden: false },
      lg: { hidden: false },
    },
  },
  {
    dataField: 'safety',
    text: 'Safety Mode',
    formatter: (cell, sample) => {
      if (sample.parameters) {
        const parameter = sample.parameters.find(
          (parameter) => parameter.name === 'SafetyLevel'
        );
        if (parameter) return parameter.value;
      }
    },
    sort: true,
    responsiveHeaderStyle: {
      md: { hidden: false },
      lg: { hidden: false },
    },
  },
];

function SamplesTable(props) {
  const { investigationId } = props;
  const samples = useResource(SampleResource.listShape(), { investigationId });

  return (
    <ResponsiveTable
      keyField="id"
      defaultSorted={[{ dataField: 'name', order: 'asc' }]}
      data={samples}
      columns={COLUMNS}
    />
  );
}

export default SamplesTable;
