import React, { MouseEvent, useRef, useState } from "react";

import "../css/feed.css";
import connection, { useRoom } from "../lib/Connection";
import { Button, Input, Modal } from "antd";
import Ticker from "react-ticker";

const FeedTicker = (props: any) => {
  const room = useRoom();

  const [showTickerMessageModal, setShowTickerMessageModal] = useState(false);
  const [tickerMessage, setTickerMessage] = useState("");
  const [blockMessageInput, setBlockMessageInput] = useState(false);
  const messageInput = useRef<Input>(null);
  function handleTickerMessageButton(e: MouseEvent) {
    if (blockMessageInput) return;
    setShowTickerMessageModal(true);

    setTimeout(function () {
      messageInput.current?.focus();
    }, 100);
  }

  function cancelTickerMessageModal() {
    if (blockMessageInput) return;
    setShowTickerMessageModal(false);
    setTickerMessage("");
  }

  async function okTickerMessageModal() {
    if (blockMessageInput) return;
    if (tickerMessage) {
      setBlockMessageInput(true);

      try {
        await connection.submitTickerMessage(tickerMessage);
        setBlockMessageInput(false);
        setShowTickerMessageModal(false);
        setTickerMessage("");
        if (messageInput.current) {
          messageInput.current.input.value = "";
        }
      } catch {
        setBlockMessageInput(false);
      }
    }
  }

  function getForIndex(index: number) {
    return room?.ticker[index % room.ticker.length];
  }

  return (
    <div className="ticker-container">
      <Modal
        title="Stuur berichtje naar de ticker"
        onCancel={cancelTickerMessageModal}
        onOk={okTickerMessageModal}
        visible={showTickerMessageModal}
      >
        <Input
          value={tickerMessage}
          ref={messageInput}
          placeholder="Bericht"
          onChange={(e) => setTickerMessage(e.target.value)}
          onKeyPress={(e) => {
            e.key === "Enter" && okTickerMessageModal();
          }}
        />
      </Modal>

      <div className="ticker-outer">
        <Ticker>
          {({ index }) => (
            <>
              {room?.ticker && (
                <span className="ticker-item">{getForIndex(index)}</span>
              )}
            </>
          )}
        </Ticker>

        <Button
          className="ticker-message-button"
          type="ghost"
          onClick={handleTickerMessageButton}
        >
          +
        </Button>
      </div>
    </div>
  );
};

export default FeedTicker;
