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

export const DraftAdmin = ({ draftSessionId }) => {
  const [latestMessage, setLatestMessage] = useState(null);
  const socketRef = useRef(null);
  const wsUrl = `ws://${window.location.host}/ws/draft/session/${draftSessionId}/`;

  useEffect(() => {
    socketRef.current = new WebSocket(wsUrl);

    socketRef.current.onmessage = (event) => {
      const data = JSON.parse(event.data);
      setLatestMessage(data);
    };

    socketRef.current.onclose = () => {
      console.warn("WebSocket connection closed.");
    };

    return () => {
      socketRef.current.close();
    };
  }, [wsUrl]);

  const handleStartDraft = () => {
    socketRef.current.send(JSON.stringify({ type: "start_draft" }));
  }

  return (
    <div className="container mt-4">
      <h1>Draft Admin Panel</h1>
      <label>Latest Message</label>
      <input
        type="text"
        className="form-control"
        readOnly disabled
        value={latestMessage ? JSON.stringify(latestMessage) : ""}
      />
      <button onClick={handleStartDraft} className="btn btn-primary">
        Start Draft
      </button>
    </div>
  );
};