import React, { ChangeEvent, useEffect, useRef, useState } from 'react';
import s from './home.scss';
import { Button, Container, Form, Header, Icon, Label } from 'semantic-ui-react';
import TextareaAutosize from 'react-textarea-autosize';
import FormCustom from '../components/form/FormCustom';
import { useFieldArray, useForm } from 'react-hook-form';
import {
  EMessageType,
  ESendStatus,
  IFormMessage,
  ISend,
  ISendData,
} from '../../electron/types/message';
import { randomString } from '../utils';
import { Apis } from '../../electron/types/apis';
import SendPage, { STORAGE_KEY } from '../components/sendPage/SendPage';

const defaultMessage = () => ({
  messageId: randomString(10),
  type: EMessageType.MESSAGE,
  value: '',
});

const Home = (): JSX.Element => {
  const [username, setUsername] = useState<string>('');
  const [sendPage, setSendPage] = useState(false);
  const [sendList, setSendList] = useState<ISendData | null>(null);
  const [mainLoading, setMainLoading] = useState(true);
  const [resetFileInput, setResetFileInput] = useState(false);
  const refFile = useRef(null);
  const {
    register,
    control,
    handleSubmit,
    reset,
    trigger,
    errors,
  } = useForm<IFormMessage>({
    defaultValues: {
      messages: [defaultMessage()],
    },
  });
  const { fields, append, remove, swap } = useFieldArray({
    control,
    name: 'messages',
  });

  useEffect(() => {
    (async () => {
      const name = await window.ipcRenderer.invoke(Apis.GET_USERNAME);
      setUsername(name);
    })();
    reloadStorage();
    setMainLoading(false);
  }, []);

  const reloadStorage = () => {
    const data = window.localStorage.getItem(STORAGE_KEY);
    if (data) {
      try {
        const sendData = JSON.parse(data) as ISendData;
        setSendList(sendData);
        reset({
          sendTo: sendData.list
            .filter((v) => v.status !== ESendStatus.SUCCESS)
            .map((v) => v.value)
            .join('\n'),
          messages: sendData.messages,
        });
      } catch (e) {
        console.error(e);
        window.localStorage.removeItem(STORAGE_KEY);
      }
    }
  };

  const onDeleteMessage = (i: number) => {
    remove(i);
  };

  const onMoveUp = (i: number) => {
    swap(i, i - 1);
  };

  const onMoveDown = (i: number) => {
    swap(i, i + 1);
  };

  const onSubmit = (data: IFormMessage) => {
    const sendToList = data.sendTo.split('\n');
    if (sendToList.length > 0) {
      const list: ISend[] = [];
      const checkDup: string[] = [];
      sendToList.forEach((v) => {
        if (checkDup.indexOf(v) <= -1 && !!v) {
          checkDup.push(v);
          list.push({ status: ESendStatus.WAIT, value: v });
        }
      });
      const sendData: ISendData = {
        messages: data.messages,
        list,
      };
      window.localStorage.setItem(STORAGE_KEY, JSON.stringify(sendData));
      setSendList(sendData);
      setSendPage(true);
    }
  };

  const onBackFromSendPage = () => {
    setMainLoading(true);
    reloadStorage();
    setTimeout(() => {
      setSendPage(false);
      setMainLoading(false);
    });
  };

  const onFileChanged = (e: any) => {
    const filePath = e.target['files'][0].path;
    setResetFileInput(true);
    setTimeout(() => {
      append({
        ...defaultMessage(),
        type: EMessageType.IMAGE,
        value: filePath,
      });
      setResetFileInput(false);
    }, 10);
  };

  return (
    <div className={s.container}>
      <Container fluid>
        <Header className={s.mainHeader} as="h2">
          <div>Apple message v1.0.7</div>
          {username && (
            <Label color={'green'} className={s.username}>
              ผู้ส่ง: {username}
            </Label>
          )}
        </Header>
        {!mainLoading && sendPage && (
          <SendPage onBack={onBackFromSendPage} sendData={sendList} />
        )}
        {!mainLoading && !sendPage && (
          <Form onSubmit={handleSubmit(onSubmit)}>
            <div className={s.messageBlock}>
              {fields.map((field, index) => {
                const name = `messages[${index}].value`;
                const nameType = `messages[${index}].type`;
                const nameId = `messages[${index}].messageId`;
                return (
                  <FormCustom
                    error={
                      errors.messages && errors.messages[index]
                        ? errors.messages[index].value
                        : undefined
                    }
                    key={`message-${field.messageId}`}
                    className={s.messageRow}
                  >
                    <React.Fragment>
                      {fields.length > 1 && (
                        <div className={s.toolBox}>
                          <div>
                            <Button
                              type={'button'}
                              disabled={fields.length === 1}
                              color={'red'}
                              size={'tiny'}
                              icon={'trash'}
                              basic
                              onClick={() => onDeleteMessage(index)}
                            />
                            <Button
                              type={'button'}
                              disabled={index === 0}
                              size={'tiny'}
                              icon={'chevron up'}
                              basic
                              onClick={() => onMoveUp(index)}
                            />
                            <Button
                              type={'button'}
                              disabled={fields.length - 1 === index}
                              size={'tiny'}
                              icon={'chevron down'}
                              basic
                              onClick={() => onMoveDown(index)}
                            />
                          </div>
                        </div>
                      )}
                      <input
                        type={'hidden'}
                        name={nameType}
                        ref={register()}
                        defaultValue={field.type}
                      />
                      <input
                        type={'hidden'}
                        name={nameId}
                        ref={register()}
                        defaultValue={field.messageId}
                      />
                      {field.type === EMessageType.IMAGE && (
                        <React.Fragment>
                          <img src={`atom://${field.value}`} />
                          <input
                            type={'hidden'}
                            name={name}
                            ref={register()}
                            defaultValue={field.value}
                          />
                        </React.Fragment>
                      )}
                      {field.type === EMessageType.MESSAGE && (
                        <TextareaAutosize
                          placeholder={'ข้อความที่ต้องการส่ง...'}
                          name={name}
                          minRows={3}
                          maxRows={5}
                          defaultValue={field.value}
                          ref={register({
                            required: 'กรอกข้อความ',
                          })}
                          onChange={() => {
                            trigger(name);
                          }}
                        />
                      )}
                    </React.Fragment>
                  </FormCustom>
                );
              })}
            </div>
            <div className={s.toolRow}>
              <Button
                type={'button'}
                basic
                size={'tiny'}
                color={'blue'}
                onClick={() => {
                  append(defaultMessage());
                }}
              >
                <Icon name={'plus'} /> ข้อความ
              </Button>
              <Button
                type={'button'}
                basic
                size={'tiny'}
                color={'blue'}
                onClick={() => {
                  refFile.current.click();
                }}
              >
                <Icon name={'image outline'} /> รูปภาพ
              </Button>
              {!resetFileInput && (
                <input
                  style={{ display: 'none' }}
                  ref={refFile}
                  type={'file'}
                  accept={`image/*`}
                  onChange={onFileChanged}
                />
              )}
            </div>
            <div className={s.phoneBlock}>
              <FormCustom error={errors.sendTo}>
                <React.Fragment>
                  <div className={s.label}>เบอร์โทรศัพท์ หรืออีเมล 1 รายการ/บรรทัด</div>
                  <TextareaAutosize
                    name={'sendTo'}
                    minRows={10}
                    maxRows={20}
                    ref={register({
                      required: 'กรอกเบอร์โทรศัพท์ หรืออีเมล อย่างน้อย 1 รายการ',
                    })}
                    onChange={() => {
                      trigger('sendTo');
                    }}
                    placeholder={`0811111111\n0999999999\ntest1@test.com\ntest2@test.com\n...`}
                  />
                </React.Fragment>
              </FormCustom>
            </div>
            <Button
              style={{ maxWidth: 480, marginLeft: 'auto', marginRight: 'auto' }}
              fluid
              color={'blue'}
              type={'submit'}
            >
              เริ่มทำงาน
            </Button>
          </Form>
        )}
      </Container>
    </div>
  );
};

export default Home;
