import { ESendStatus, ISend, ISendData } from '../../../electron/types/message';
import { Button, Header, Icon, Label, List } from 'semantic-ui-react';
import React, { useEffect, useRef, useState } from 'react';
import { Apis } from '../../../electron/types/apis';

interface ISendRowProps {
  data: ISend;
  isActive: boolean;
}

export const STORAGE_KEY = 'sendList';

const SendRow = ({ data, isActive }: ISendRowProps): JSX.Element => {
  return (
    <List.Item style={{ display: 'flex', alignItems: 'center' }}>
      <List.Content style={{ paddingRight: 5 }}>
        {(() => {
          switch (data.status) {
            case ESendStatus.FAILED:
              return <Icon color={'red'} name="x" size="large" />;
            case ESendStatus.SENDING:
              return <Icon loading name={'circle notch'} size={'large'} />;
            case ESendStatus.WAIT:
              return isActive ? (
                <Icon loading name={'circle notch'} size={'large'} />
              ) : (
                <Icon name={'pause'} size={'large'} />
              );
            case ESendStatus.SUCCESS:
              return <Icon name="check" color={'green'} size="large" />;
            default:
              return '';
          }
        })()}
      </List.Content>
      <List.Content>
        <List.Header as="div">{data.value}</List.Header>
        <List.Description as="div">
          {(() => {
            switch (data.status) {
              case ESendStatus.FAILED:
                return 'ส่งไม่สำเร็จ';
              case ESendStatus.SENDING:
                return 'กำลังส่ง';
              case ESendStatus.SUCCESS:
                return 'สำเร็จแล้ว';
              case ESendStatus.WAIT:
                return 'รอดำเนินการ';
              default:
                return '-';
            }
          })()}
          {data.error && (
            <Label basic size={'tiny'} color={'red'} pointing={'left'}>
              {data.error}
            </Label>
          )}
        </List.Description>
      </List.Content>
    </List.Item>
  );
};

interface ISendPageProps {
  sendData: ISendData;
  onBack: () => void;
}

export const SendPage = ({ sendData, onBack }: ISendPageProps): JSX.Element => {
  const [list, setList] = useState(sendData.list);
  const [status, setStatus] = useState<'active' | 'wait'>('wait');
  const refStatus = useRef('wait');
  const refList = useRef(sendData.list);

  const start = () => {
    setStatus('active');
    refStatus.current = 'active';
    sendMessage();
  };
  useEffect(() => {
    refStatus.current = status;
    refList.current = list;
  });
  useEffect(() => {
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ ...sendData, list }));
  }, [list]);
  const setListByValue = (value: string, newData: ISend) => {
    setList((prevState) => {
      return prevState.map((v) => {
        if (v.value === value) {
          return newData;
        }
        return v;
      });
    });
  };
  const sendMessage = async () => {
    const target = refList.current.find((v) => v.status === ESendStatus.WAIT);
    if (target && refStatus.current === 'active') {
      try {
        setListByValue(target.value, { ...target, status: ESendStatus.SENDING });
        await window.ipcRenderer.invoke(
          Apis.SEND_MESSAGE,
          target.value,
          sendData.messages,
        );
        setListByValue(target.value, {
          ...target,
          error: undefined,
          status: ESendStatus.SUCCESS,
        });
      } catch (e) {
        setListByValue(target.value, {
          ...target,
          error: e.message,
          status: ESendStatus.FAILED,
        });
      }
      setTimeout(() => {
        sendMessage();
      });
    } else {
      stop();
    }
  };
  const stop = () => {
    setStatus('wait');
    refStatus.current = 'wait';
  };
  return (
    <div>
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 15,
        }}
      >
        <Header style={{ marginBottom: 0 }} as={'h4'}>
          รายการส่งข้อความ
        </Header>
        <div>
          {status === 'wait' && (
            <React.Fragment>
              <Button
                onClick={start}
                basic
                size={'small'}
                type={'button'}
                color={'black'}
              >
                <Icon name={'play'} />
                ทำงาน
              </Button>
              <Button
                color={'black'}
                onClick={onBack}
                basic
                size={'small'}
                type={'button'}
              >
                <Icon name={'arrow left'} />
                ย้อนกลับ
              </Button>
            </React.Fragment>
          )}
          {status === 'active' && (
            <React.Fragment>
              <Button onClick={stop} basic size={'small'} type={'button'} color={'black'}>
                <Icon name={'pause'} />
                หยุดการทำงาน
              </Button>
            </React.Fragment>
          )}
        </div>
      </div>
      <List divided relaxed>
        {list.map((v) => (
          <SendRow isActive={status === 'active'} key={`row-${v.value}`} data={v} />
        ))}
      </List>
    </div>
  );
};

export default SendPage;
