import React, { useState, useEffect, Fragment } from 'react';
import { Input, Button, Divider } from '@easyv/antd';
import message from 'components/message';
import Key from './components/Key';
import http from '../../../../utils/fetch';
import { api } from '../../../../constants/config';
import styles from './index.less';

const { TextArea } = Input;

const KeyPanel = () => {
  const [keyList, setKeyList] = useState<any[]>([]);
  const [key, setKey] = useState('');
  const [title, setTitle] = useState('');

  useEffect(() => {
    const controller = window.AbortController && new AbortController();
    const signal = controller && controller.signal;
    getKeyList(signal);
    return () => {
      controller && controller.abort();
    };
  }, []);

  const getKeyList = (signal?: AbortSignal) => {
    http.get(api.userKeyList, {}, { signal }).then((data: any[]) => {
      setKeyList(data);
    });
  };

  const addKey = () => {
    http
      .post(api.userKeyAdd, {
        key,
        title
      })
      .then((res) => {
        if (res) {
          message.success('添加密钥成功');
          setKey('');
          setTitle('');
          getKeyList();
        } else {
          message.error('添加密钥失败');
        }
      });
  };

  const deleteKey = (uniqueTag) => {
    http.post(api.userKeyDelete, { uniqueTag }).then((res) => {
      if (res) {
        message.success('删除密钥成功');
        getKeyList();
      } else {
        message.error('删除密钥失败');
      }
    });
  };

  return (
    <div className={styles.container}>
      <div
        style={{
          width: 240
        }}>
        <h2>Public Keys</h2>
        <p style={{ marginTop: 8 }}>Public Keys 允许你在你的电脑和服务器之间建立安全的连接，并通过命令行来上传组件。</p>
      </div>
      <div style={{ marginLeft: 64, flex: 1, display: 'flex', flexDirection: 'column' }}>
        <h3>添加密钥</h3>
        <p style={{ marginTop: 8, marginBottom: 8 }}>在你添加密钥前，请先在 component 项目中生成它。</p>
        <h3>Key</h3>
        <TextArea
          value={key}
          onChange={(e) => {
            setKey(e.target.value);
          }}
          style={{
            marginTop: 8,
            height: 184
          }}
        />
        <h3 style={{ marginTop: 8 }}>标题</h3>
        <Input value={title} onChange={(e) => setTitle(e.target.value)} style={{ margin: '8px 0px 16px 0px' }} />
        <Button onClick={addKey} type="primary" style={{ width: 72 }}>
          添加
        </Button>
        <Divider />
        <h3>{`已添加的密钥(${keyList.length})`}</h3>
        <div style={{ display: 'flex', flexDirection: 'column', marginTop: 16, overflowY: 'auto', flex: 1 }}>
          {keyList.map((o, index) => (
            <Fragment key={o.keyValue}>
              {index !== 0 && <Divider style={{ margin: 0, top: 0 }} />}
              <Key uniqueTag={o.uniqueTag} title={o.title} keyValue={o.keyValue} time={o.createdAt} onDelete={deleteKey} />
            </Fragment>
          ))}
        </div>
      </div>
    </div>
  );
};

export default KeyPanel;
