import { useState } from 'react';

function TextShare({ textHistory, setTextHistory, dataChannels, useFallback, socket, code }) {
  const [textInput, setTextInput] = useState('');

  const handleSend = () => {
    if (!textInput.trim()) return;
    console.log('handleSend:', { dataChannels, useFallback, code });
    if (!useFallback && Object.keys(dataChannels).length > 0) {
      Object.keys(dataChannels).forEach((peerId) => {
        if (dataChannels[peerId].readyState === 'open') {
          dataChannels[peerId].send(JSON.stringify({ type: 'text', text: textInput }));
          console.log(`Sent text to peer ${peerId}`);
        }
      });
    } else if (useFallback && socket && code) {
      socket.emit('text', { code, text: textInput });
      console.log(`Sending text via socket for room ${code}: ${textInput}`);
    }
    setTextHistory((prev) => [...prev, textInput]); // Update sender's textHistory
    setTextInput('');
  };

  const handleKeySend = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault(); // Prevent adding a new line
      handleSend(); // Trigger send action
    }
  };

  const selectText = (x) => {
    const element = document.getElementById(`msg-${x}`);
    if (element && window.getSelection) {
      const selection = window.getSelection();
      selection.removeAllRanges();
      const range = document.createRange();
      range.selectNodeContents(element);
      selection.addRange(range);
      //document.execCommand('copy') // deprecated
      //navigator.clipboard.writeText(element.textContent); // new way
    } else {
      console.warn(`Element msg-${x} not found or selection API unavailable`);
    }
  };

  return (
    <div className="mb-4">
      <h2 className="text-xl font-semibold mb-2">Share Text</h2>
      <textarea
        className="w-full p-2 border rounded bg-pink-100 text-purple-900"
        value={textInput}
        onChange={(e) => setTextInput(e.target.value)}
        onKeyDown={handleKeySend}
        placeholder="Enter text to share"
      />
      <button
        className="bg-emerald-600 text-darkPurple px-4 py-2 rounded hover:bg-emerald-500"
        onClick={handleSend}
      >
        Send
      </button>
      <br />
      <div className="mt-2" id="textview">
        <h3 className="text-lg font-semibold">Messages</h3>
        <ul className="list-disc pl-5">
          {textHistory?.length > 0 ? (
            textHistory.map((msg, index) => (
              <li key={index}>
                <button
                  className="bg-sky-600 text-darkPurple px-4 py-2 rounded hover:bg-sky-500"
                  onClick={() => selectText(index)}
                >
                  {`{}`}
                </button>
                <pre id={`msg-${index}`}>{msg}</pre></li>
            ))
          ) : (
            <li><pre>No messages yet</pre></li>
          )}
        </ul>
      </div>
    </div>
  );
}

export default TextShare;
