import React, { useContext, useEffect } from 'react';
import { Typography, TreeSelect, Table, Collapse } from 'antd';
import { useAppContext } from '../../contexts/AppContext';
import CommonPageContext from '../../contexts/commonPage';
import ReactSimpleCodeEditor from '../../components/ReactSimpleCodeEditor';
import { useParams } from 'react-router';

// Use `Typography` so can apply dark theme to text
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
const {
  Text
} = Typography;
const {
  SHOW_PARENT
} = TreeSelect;
export default function ViewPage() {
  const {
    dbs,
    getTablesByDbName,
    getViewByDbNameViewName
  } = useAppContext();
  const {
    dbName,
    viewName
  } = useParams();
  const {
    githubDb
  } = useContext(CommonPageContext);
  const [selectedDbTableNames, setSelectedDbTableNames] = React.useState(JSON.parse(localStorage.getItem('dbm_query_page_selected_table_names') || '[]'));
  const [code, setCode] = React.useState('');
  const [result, setResult] = React.useState({
    obj: [],
    err: ''
  });
  // tablesRows={iam:[...], roles:[...]}
  const [tablesRows, setTablesRows] = React.useState({});
  const treeData = Object.keys(dbs || {}).map(dbName => ({
    title: dbName,
    value: dbName,
    key: dbName,
    children: getTablesByDbName(dbName).map(table => ({
      title: table.name,
      value: `${dbName}/${table.name}`,
      key: `${dbName}/${table.name}`
    }))
  }));
  useEffect(() => {
    selectedDbTableNames.forEach(dbTableName => {
      const [dbName, tableName] = dbTableName.split('/');
      githubDb?.getTableRows(dbName, tableName).then(response => {
        setTablesRows(prev => ({
          ...prev,
          [dbTableName]: response.content
        }));
      });
    });
  }, [githubDb, selectedDbTableNames]);
  useEffect(() => {
    const view = getViewByDbNameViewName(dbName || '', viewName || '');
    if (!view) {
      setResult({
        obj: [],
        err: 'View not found'
      });
      return;
    }
    // TODO: no hard code `query`, should defined in @db-man/github package
    const code = view.query || '';
    console.log('code:', code);
    setCode(code);
  }, [dbName, viewName, getViewByDbNameViewName]);
  useEffect(() => {
    try {
      // eslint-disable-next-line no-new-func
      const fn = Function('tablesRows', code);
      const outputRows = fn(tablesRows);
      setResult({
        obj: outputRows,
        err: ''
      });
    } catch (err) {
      // console.log('[ERROR] Failed to eval function!');

      setResult({
        obj: [],
        err: err.message
      });
    }
  }, [tablesRows, code]);
  const handleSelectedTableNamesChange = newValue => {
    // newValue=['iam/users', 'iam/roles']
    setSelectedDbTableNames(newValue);
    localStorage.setItem('dbm_query_page_selected_table_names', JSON.stringify(newValue));
  };
  const tProps = {
    treeData,
    value: selectedDbTableNames,
    onChange: handleSelectedTableNamesChange,
    treeCheckable: true,
    showCheckedStrategy: SHOW_PARENT,
    placeholder: 'Please select',
    style: {
      width: '100%'
    }
  };
  const items = [{
    key: '1',
    label: 'View Query COde',
    children: /*#__PURE__*/_jsx("div", {
      children: /*#__PURE__*/_jsx(ReactSimpleCodeEditor, {
        height: "50em",
        value: code,
        onChange: setCode
      })
    })
  }];
  return /*#__PURE__*/_jsxs("div", {
    className: "dbm-query-page",
    children: [/*#__PURE__*/_jsxs("div", {
      children: ["View Name: ", viewName]
    }), /*#__PURE__*/_jsxs("div", {
      children: [/*#__PURE__*/_jsx("div", {
        children: "DB Tables Selector:"
      }), /*#__PURE__*/_jsx(TreeSelect, {
        ...tProps
      })]
    }), /*#__PURE__*/_jsx("div", {
      children: /*#__PURE__*/_jsx(Collapse, {
        items: items,
        defaultActiveKey: ['2']
      })
    }), /*#__PURE__*/_jsxs("div", {
      children: [/*#__PURE__*/_jsx("div", {
        children: /*#__PURE__*/_jsx(Text, {
          children: "Error:"
        })
      }), /*#__PURE__*/_jsx("div", {
        style: {
          color: 'red'
        },
        children: result.err
      }), /*#__PURE__*/_jsx("div", {
        children: /*#__PURE__*/_jsx(Text, {
          children: "Result:"
        })
      }), result.obj && result.obj.length > 0 && /*#__PURE__*/_jsx(Table, {
        rowKey: record => JSON.stringify(record),
        columns: Object.keys(result.obj[0] || {}).map(key => ({
          title: key,
          dataIndex: key,
          key,
          // @ts-ignore
          sorter: (a, b) => a[key] - b[key]
        })),
        dataSource: result.obj
      })]
    })]
  });
}
//# sourceMappingURL=index.js.map