import { useState } from 'react';
import {Table, Input, Form, Popconfirm, Typography } from 'antd'

const originData = [
  {
    key: '1', probeNumber: '', probeExtractionDepth: '', sandstone: '', siltstone: '', argillit: '', brokenArgillit: '', coal: '', sand: '', clay: '',
    camstone: '', cement: '', summary: '', drillingMud: '', sludge: '', sludge: '', maxSum: '', methan: '', ethan: '', propan: '', butan: '', pentan: ''
  }
]

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  return (
    <td {...restProps} style={{paddingLeft: 2, paddingRight: 2}}>
      <div style={{width: '100%', display: 'flex', justifyContent: 'center'}}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{ margin: 0 }}
            rules={[
              {
                required: true,
                message: '',
                pattern: '(-?[1-9]+\d*([.,]\d+)?)$|^(-?0[.,]\d*[1-9]+)$|^0$|^0.0$'
              },
            ]}
          >
            <Input size="small" />
          </Form.Item>
        ) : (
          children
        )}
      </div>
    </td>
  );
};

export function SludgeDiagram() {
  const [form] = Form.useForm();
  const [data, setData] = useState(originData);
  const [editingKey, setEditingKey] = useState('');

  const isEditing = (row) => row.key === editingKey;

  const columns = [
    {
        title: 'N пробы',
        key: 'probeNumber',
        dataIndex: 'probeNumber',
        align: 'center',
        className: 'yellow-background',
        editable: true
    },
    {
        title: 'Глубина отбора пробы',
        key: 'probeExtractionDepth',
        dataIndex: 'probeExtractionDepth',
        align: 'center',
        className: 'yellow-background',
        editable: true
    },
    {
      title: 'Литология',
      key: 'lithology',
      dataIndex: 'lithology',
      align: 'center',
      className: 'yellow-background',
      editable: true,
      children: [
        {
          title: 'Песчаник (%)',
          key: 'sandstone',
          dataIndex: 'sandstone',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        },
        {
          title: 'Алевролит (%)',
          key: 'siltstone',
          dataIndex: 'siltstone',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        },
        {
          title: 'Аргиллит (%)',
          key: 'argillit',
          dataIndex: 'argillit',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        },
        {
          title: 'Аргиллит бит. (%)',
          key: 'brokenArgillit',
          dataIndex: 'verticalDepth',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        },
        {
          title: 'Уголь (%)',
          key: 'coal',
          dataIndex: 'coal',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        },
        {
          title: 'Песок (%)',
          key: 'sand',
          dataIndex: 'sand',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        },
        {
          title: 'Глина (%)',
          key: 'clay',
          dataIndex: 'clay',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        },
        {
          title: 'Известняк (%)',
          key: 'camstone',
          dataIndex: 'camstone',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        },
        {
          title: 'Цемент (%)',
          key: 'cement',
          dataIndex: 'cement',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        }
      ]
    },
    
    {
      title: 'Краткое описание',
      key: 'summary',
      dataIndex: 'summary',
      align: 'center',
      className: 'yellow-background',
      editable: true
    },
    {
      title: 'ЛБА бурового раствора',
      key: 'drillingMud',
      dataIndex: 'drillingMud',
      align: 'center',
      className: 'lightgray-background',
      editable: true
    },
    {
      title: 'ЛБА (шлама)',
      key: 'sludge',
      dataIndex: 'sludge',
      align: 'center',
      className: 'lightorange-background',
      editable: true
    },
    {
      title: 'Газопоказания',
      key: 'gasIndications',
      dataIndex: 'gasIndications',
      align: 'center',
      className: 'yellow-background',
      children: [
        {
          title: 'Сумма УВ мах. (абс%)',
          key: 'maxSum',
          dataIndex: 'maxSum',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        },
        {
          title: 'С1 метан (отн%)',
          key: 'methane',
          dataIndex: 'depthPlanFactDifference',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        },
        {
          title: 'С2 этан (отн%)',
          key: 'ethan',
          dataIndex: 'ethan',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        },
        {
          title: 'С3 пропан (отн%)',
          key: 'propane',
          dataIndex: 'propane',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        },
        {
          title: 'С4 бутан (отн%)',
          key: 'butane',
          dataIndex: 'butane',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        },
        {
          title: 'С5 пентан (отн%)',
          key: 'pentane',
          dataIndex: 'pentane',
          align: 'center',
          className: 'lightpurple-background',
          editable: true
        }
      ]
    },
    {
      title: 'Мех. скорость',
      key: 'mechanicalSpeed',
      dataIndex: 'mechanicalSpeed',
      align: 'center',
      className: 'yellow-background',
      editable: true
    },
    {
      title: 'Предварительное заключение о насыщении по ГК',
      key: 'preliminaryConclusion',
      dataIndex: 'preliminaryConclusion',
      align: 'center',
      className: 'lightorange-background',
      editable: true
    },
    {
      title: 'Действие',
      dataIndex: 'action',
      align: 'center',
      width: 150,
      className: 'small-font',
      render: (_, row) => {
        const editable = isEditing(row);
        return editable ? (
          <span>
            <a
              href="javascript:;"
              onClick={() => save(row.key)}
              style={{ marginRight: 8 }}
            >
              Сохранить
            </a>
            <Popconfirm style={{width: '100px'}} title={<span>Отменить<br />редактирование?</span>} onConfirm={cancel}>
              <a>Отменить</a>
            </Popconfirm>
          </span>
        ) : (
          <Typography.Link disabled={editingKey !== ''} onClick={() => edit(row)}>
            Редактировать
          </Typography.Link>
        );
      },
    }
  ];

  const mapColumns = (col) => {
    if(col.children)
      col.children = col.children.map(mapColumns)

    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (row) => ({
        row,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(row)
      }),
    };
  }

  const mergedColumns = columns.map(mapColumns);
  
  const edit = (row) => {
    form.setFieldsValue({
      ...row
    });
    setEditingKey(row.key);
  };
  
  const cancel = () => {
    setEditingKey('');
  };
  
  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);
  
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey('');
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  return (<>
    <Form form={form} component={false}>
      <Table
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        columns={mergedColumns}
        dataSource={data}
        size={'small'}
        bordered={true}
        pagination={false}
      />
    </Form>
  </>
  )
}