//frontend/src/pages/Mypage/Mypage.tsx
import { io } from 'socket.io-client';
import { Socket } from 'socket.io-client';
import tw, { styled, css } from 'twin.macro';
import useInput from '@hooks/useInput';
import { useEffect, useState, useRef } from 'react';
import Button from '@components/Button/Button';
import { SOCKET_URL } from '@config/server';
const roomId = 'test';

let cnt = 0;
const MyPage = () => {
  const scrollRef = useRef(null);

  const [inputText, setInputText, resetInputText] = useInput('');
  const [socket, setSocket] = useState<Socket>();
  const [chats, setChats] = useState<Array<string>>([]);
  const [currChat, setCurrChat] = useState<string>('');

  useEffect(() => {
    console.log(cnt++);
    const disposableSocket = io(`${SOCKET_URL}`, {
      reconnectionDelayMax: 10000,
    });

    disposableSocket.on('connect', () => {
      setSocket(disposableSocket);
      disposableSocket.emit(
        'join',
        { roomId: roomId + Math.floor(Math.random() * (2 - 0) + 0) },
        (res: any) => console.log(res)
      );
    });

    disposableSocket.on(roomId, (msg) => {
      console.log('서버로 받은 msg : ', msg);
      setCurrChat(msg.conetents.data);
    });

    disposableSocket.on('chat', (msg) => {
      console.log(' 받은 msg : ', msg);
      setCurrChat(msg.conetents.data);
    });

    return () => {
      disposableSocket.disconnect();
    };
  }, []);

  useEffect(() => {
    setChats([...chats, currChat]);
    setCurrChat('');
  }, [currChat]);

  const handleSendChat = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!socket) {
      return;
    }
    socket.emit('chat', { data: inputText }, (res: any) => console.log(res));
    resetInputText();
  };

  useEffect(() => {
    scrollRef?.current.scrollIntoView({ behavior: 'smooth' });
  }, [chats]);

  return (
    <ChattingContainer onSubmit={handleSendChat}>
      <ChattingDisplay>
        {chats.map((chat, index) => (
          <div key={index}>{chat}</div>
        ))}
        <div ref={scrollRef}></div>
      </ChattingDisplay>
      <ChattingTextArea value={inputText} onChange={setInputText} />
      <Button isIcon={false} size="l" type="submit">
        <>채팅 보내기</>
      </Button>
    </ChattingContainer>
  );
};

export default MyPage;

const ChattingContainer = styled.form([
  css`
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 1rem;
  `,
]);

const ChattingDisplay = styled.div([
  css`
    width: 60rem;
    height: 50rem;
    bsorder: 1px solid white;
    overflow: scroll;
  `,
  tw`font-pretendard text-m rounded-[1rem] text-white`,
]);

const ChattingTextArea = styled.input([
  css`
    width: 60rem;
    height: 10rem;
    border: 1px solid white;
  `,
  tw`font-pretendard text-m rounded-[1rem] p-4`,
]);