import React from 'react';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { solarizedDark } from 'react-syntax-highlighter/dist/esm/styles/hljs';
import { useTableSchema } from './service';

export const DrawerButton: React.FunctionComponent<{
  label: string;
  dark?: boolean;
  onClick: () => void;
}> = ({ label, dark, onClick }) => {
  return (
    <button
      type="button"
      tabIndex={-1}
      className={'drawer-button' + (dark ? ' drawer-button-dark' : '')}
      onClick={onClick}
    >
      {label}
    </button>
  );
};

export const Drawer: React.FunctionComponent<{
  show: boolean;
  dark?: boolean;
  title?: string;
  onClose: () => void;
}> = ({ show, dark, title, onClose, children }) => {
  return (
    <div
      className={
        'drawer-container' +
        (dark ? ' drawer-dark' : '') +
        (show ? '' : ' drawer-hidden')
      }
    >
      <div className="drawer-titlebar">
        <div className="drawer-title">{title}</div>
        <button
          type="button"
          tabIndex={-1}
          className="drawer-close-btn"
          onClick={onClose}
        />
      </div>
      {children}
    </div>
  );
};

export const TableShemaDrawer: React.FunctionComponent<{
  dataSource?: string;
  tableName?: string;
}> = ({ dataSource, tableName }) => {
  const { data } = useTableSchema(dataSource, tableName);
  return (
    <>
      <div className="drawer-table-header">
        <span className="drawer-table-cell" style={{ width: '20%' }}>
          序号
        </span>
        <span className="drawer-table-cell" style={{ width: '35%' }}>
          字段
        </span>
        <span className="drawer-table-cell" style={{ width: '35%' }}>
          类型
        </span>
        <span className="drawer-table-cell" style={{ width: '10%' }}>
          长度
        </span>
      </div>
      <div className="drawer-table-body">
        {data &&
          data.map((row, idx) => (
            <div key={idx} className="drawer-table-row">
              <span className="drawer-table-cell" style={{ width: '20%' }}>
                {idx + 1}
              </span>
              <span className="drawer-table-cell" style={{ width: '35%' }}>
                {row.field}
              </span>
              <span className="drawer-table-cell" style={{ width: '35%' }}>
                {row.type}
              </span>
              <span className="drawer-table-cell" style={{ width: '10%' }}>
                {row.length}
              </span>
            </div>
          ))}
      </div>
    </>
  );
};

export const JsonSchemaDrawer: React.FunctionComponent<{
  jsonSchema: any;
}> = ({ jsonSchema }) => {
  return (
    <SyntaxHighlighter showLineNumbers language="json" style={solarizedDark}>
      {JSON.stringify(jsonSchema, null, 2)}
    </SyntaxHighlighter>
  );
};
