import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { CopyToClipboard } from "react-copy-to-clipboard";

import { Title } from "../ui/title";
import Answers from './Answers'

function Poll(props) {
  console.log('Poll props:', props)

  const { user, poll, socket } = props
  const { id } = useParams();
  const navigate = useNavigate();
  const token = localStorage.getItem(id)
  const FRONT_URL = "https://poll.vaidis.eu"

  const [copied, setCopied] = useState(false);

  const randomUser = (length) => {
    let result = "";
    const characters = "abcdefghijklmnopqrstuvwxyz123456789";
    const charactersLength = characters.length;
    let counter = 0;
    while (counter < length) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
      counter += 1;
    }
    return result;
  }

  useEffect(() => {
    if (!token && poll?.anonymous) {
      const data = {poll:id, user:randomUser(24)};
      socket.emit('join', data);
    }
    if (!token && !poll?.anonymous) {
      return navigate(`/poll/${id}/join`)
    }
    if (token) {
      socket.emit('poll', token);
    }
  }, [id, token, navigate]);

  const onCopy = () => {
    console.log('onCopy')
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }


  return (
    <div className="poll">
      {poll &&
        <div className="mb-8">
          <Title variant={1} label={poll.title} />
          <p className="text-white mt-6 text-sm">Hello <strong>{poll.anonymous ? 'Anonymous' : user}</strong>, please choose the answer you like</p>
          <Answers poll={poll} id={id} user={user} socket={socket} />
        </div>
      }
      {/* SHARE */}
      <div className="mt-2 text-white">
        <p className="text-sm mb-3">Share the poll URL to the voters</p>
        <div className="flex p-4 bg-black bg-opacity-20 rounded-xl justify-between">
          <div className="text-sm">
            {FRONT_URL}/poll/{id}
          </div>
          <div className="">
            <CopyToClipboard onCopy={onCopy} text={`${FRONT_URL}/poll/${id}`}>
              <i className="flex mr-2 gg-copy"></i>
            </CopyToClipboard>
          </div>
        </div>
        <div className={`transition-opacity duration-600 flex justify-end text-sm mr-2 ${copied ? 'opacity-100' : 'opacity-0'}`}>
          Copied
        </div>
      </div>
    </div>
  );
}

export default Poll;
