/* eslint-disable react/prop-types, react/jsx-props-no-spreading */

import React, { useState, useEffect } from 'react';
import { CheckCircleOutlined } from '@ant-design/icons';
import { Table, Input, Popconfirm, Form, Typography, Button } from 'antd';
import * as constants from '../../constants';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
function EditableCell({
  editing,
  dataIndex,
  title,
  record,
  index,
  children,
  ...restProps
}) {
  return /*#__PURE__*/_jsx("td", {
    ...restProps,
    children: editing ? /*#__PURE__*/_jsx(Form.Item, {
      name: dataIndex,
      style: {
        margin: 0
      },
      rules: [{
        required: title !== 'modes',
        message: `Please Input ${title}!`
      }],
      children: /*#__PURE__*/_jsx(Input, {
        className: `dbm-new-connection-editable-cell-title-${title}`,
        placeholder: title === 'modes' ? 'split-table' : ''
      })
    }) : children
  });
}
function EditableTable({
  storage,
  onEnable
}) {
  const [form] = Form.useForm();
  const [data, setData] = useState([]);
  const [editingKey, setEditingKey] = useState('');
  useEffect(() => {
    const connections = storage.get(constants.LS_KEY_DB_CONNECTIONS);
    if (connections) {
      setData(JSON.parse(connections));
    }
  }, []);
  const isEditing = record => record.key === editingKey;
  const saveData = d => {
    setData(d);
    storage.set(constants.LS_KEY_DB_CONNECTIONS, JSON.stringify(d));
  };
  const handleAddRow = () => {
    const newData = [...data];
    const newRow = {
      owner: '',
      token: '',
      repo: '',
      modes: ''
    };
    newData.push({
      key: '0',
      // tmp row added, will delete when cancel
      ...newRow
    });
    setData(newData);
    form.setFieldsValue({
      ...newRow
    });
    setEditingKey('0');
  };
  const edit = record => {
    form.setFieldsValue({
      owner: '',
      token: '',
      repo: '',
      modes: '',
      ...record
    });
    setEditingKey(record.key);
  };
  const cancel = record => {
    setEditingKey('');
    if (record.key === '0') {
      // Remove tmp row
      const newData = [...data];
      const index = newData.findIndex(item => item.key === '0');
      newData.splice(index, 1);
      setData(newData);
    }
  };
  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];
        if (item.key === '0') {
          item.key = data.filter(({
            key: k
          }) => k !== '0').length === 0 ? '1' : Math.max(...data.filter(({
            key: k
          }) => k !== '0').map(({
            key: k
          }) => Number(k))) + 1 + '';
        }
        newData.splice(index, 1, {
          ...item,
          ...row
        });
        saveData(newData);
        setEditingKey('');
      } else {
        alert('TODO');
        // newData.push({
        //   ...row,
        //   key: data.length === 0 ? 1 : Math.max(...data.map(({ key: k }) => k)) + 1,
        // });
        // setData(newData);
        // setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo); // eslint-disable-line no-console
    }
  };

  const handleDelete = record => {
    const newData = [...data];
    const index = newData.findIndex(item => item.key === record.key);
    newData.splice(index, 1);
    saveData(newData);
  };
  const handleEnable = record => {
    storage.set(constants.LS_KEY_GITHUB_OWNER, record.owner);
    storage.set(constants.LS_KEY_GITHUB_REPO_NAME, record.repo);
    storage.set(constants.LS_KEY_GITHUB_PERSONAL_ACCESS_TOKEN, record.token);
    storage.set(constants.LS_KEY_GITHUB_REPO_MODES, record.modes);
    onEnable();
  };
  const columns = [{
    title: 'key',
    dataIndex: 'key',
    width: '10%',
    editable: false
  }, {
    title: 'owner',
    dataIndex: 'owner',
    width: '10%',
    editable: true
  }, {
    title: 'token',
    dataIndex: 'token',
    width: '10%',
    render: token => /*#__PURE__*/_jsx("textarea", {
      style: {
        resize: 'none'
      },
      rows: 1,
      cols: 10,
      disabled: true,
      defaultValue: token
    }),
    editable: true
  }, {
    title: 'repo',
    dataIndex: 'repo',
    width: '10%',
    editable: true
  }, {
    title: 'modes',
    dataIndex: 'modes',
    width: '10%',
    editable: true
  }, {
    title: /*#__PURE__*/_jsxs("div", {
      children: ["Operation", ' ', /*#__PURE__*/_jsx(Button, {
        className: "dbm-create-connection-btn",
        size: "small",
        disabled: editingKey !== '',
        onClick: handleAddRow,
        children: "Add"
      })]
    }),
    dataIndex: 'operation',
    render: (_, record) => {
      const editable = isEditing(record);
      return editable ? /*#__PURE__*/_jsxs("span", {
        children: [/*#__PURE__*/_jsx(Typography.Link, {
          className: "dbm-save-connection-link",
          style: {
            marginRight: 8
          },
          onClick: () => save(record.key),
          children: "Save"
        }), /*#__PURE__*/_jsx(Popconfirm, {
          title: "Sure to cancel?",
          onConfirm: () => cancel(record),
          children: /*#__PURE__*/_jsx(Button, {
            type: "link",
            children: "Cancel"
          })
        })]
      }) : /*#__PURE__*/_jsxs("span", {
        children: [/*#__PURE__*/_jsx(Typography.Link, {
          disabled: editingKey !== '',
          onClick: () => edit(record),
          children: "Edit"
        }), /*#__PURE__*/_jsx(Popconfirm, {
          title: "Sure to delete?",
          onConfirm: () => handleDelete(record),
          children: /*#__PURE__*/_jsx(Button, {
            type: "link",
            danger: true,
            children: "Delete"
          })
        }), /*#__PURE__*/_jsx(Button, {
          className: "dbm-enable-connection-btn",
          type: "link",
          onClick: () => handleEnable(record),
          children: "Enable"
        })]
      });
    }
  }];
  const mergedColumns = columns.map(col => {
    if (!col.editable) {
      if (col.dataIndex !== 'key') {
        return col;
      }
      return {
        ...col,
        render: (text, record) => {
          if (record.owner === storage.get(constants.LS_KEY_GITHUB_OWNER) && record.repo === storage.get(constants.LS_KEY_GITHUB_REPO_NAME)) {
            return /*#__PURE__*/_jsxs("span", {
              children: [text, " ", /*#__PURE__*/_jsx(CheckCircleOutlined, {
                style: {
                  color: 'red'
                }
              })]
            });
          }
          return text;
        }
      };
    }
    return {
      ...col,
      onCell: record => ({
        record,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record)
      })
    };
  });
  return /*#__PURE__*/_jsx(Form, {
    form: form,
    component: false,
    children: /*#__PURE__*/_jsx(Table, {
      size: "small",
      components: {
        body: {
          cell: EditableCell
        }
      },
      bordered: true,
      dataSource: data,
      columns: mergedColumns,
      rowClassName: "editable-row",
      pagination: {
        // onChange: cancel,
      }
    })
  });
}
export default EditableTable;
//# sourceMappingURL=EditableTable.js.map