import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import "./JoinRoom.css";

const CreateMeeting = () => {
    //   const [room, setRoom] = useState("");
    //   const [name, setName] = useState("");
    //   const [created, setCreated] = useState(false);
    //   const navigate = useNavigate();
    //   const [Meetings, setMeeting] = useState([]);  

    //   const handleCreate = () => {
    //     if (room && name) {
    //       const newMeeting = { room, name };
    //       const savedMeetings = JSON.parse(localStorage.getItem("meetings") || "[]");
    //       localStorage.setItem("meetings", JSON.stringify([...savedMeetings, newMeeting]));
    //         setRoom("");
    //         setName("");
    //       setCreated(true);
    //     }
    //   };

    //   useEffect(() => {
    //     const savedMeetings = JSON.parse(localStorage.getItem("meetings") || "[]");
    //     if (savedMeetings.length > 0) {
    //       setMeeting(savedMeetings);
    //       setCreated(true);
    //     }
    //   }, []);  
    const [room, setRoom] = useState("");
    const [name, setName] = useState("");
    const [created, setCreated] = useState(false);
    const [meetings, setMeetings] = useState([]);
    const navigate = useNavigate();

    useEffect(() => {
        const savedMeetings = JSON.parse(localStorage.getItem("meetings") || "[]");
        if (savedMeetings.length > 0) {
            setMeetings(savedMeetings);
            setCreated(true);
        }
    }, []);

    const handleCreate = () => {
        if (room && name) {
            const newMeeting = { room, name };
            const updatedMeetings = [...meetings, newMeeting];

            localStorage.setItem("meetings", JSON.stringify(updatedMeetings));
            setMeetings(updatedMeetings);  // ✅ Update state immediately
            setRoom("");
            setName("");
            setCreated(true);
        }
    };

    const handleCopy = (room) => {
        // navigator.clipboard.writeText(`https://vpd.zrix.com/${room}`);
        // alert("Link copied to clipboard!");
        const origin = window.location.origin; // Gets the current domain like http://localhost:3000 or https://yourdomain.com
        const meetingURL = `${origin}/meeting?room=${room}`;
        navigator.clipboard.writeText(meetingURL)
            .then(() => alert("Link copied to clipboard!"))
            .catch(() => alert("Failed to copy link."));
    };

    const handleStartMeeting = (room, name) => {
        navigate(`/meeting?room=${room}&name=${encodeURIComponent(name)}`);
    };

    return (
        <div className="form-wrapper">
            <h2>Create New Meeting</h2>
            <input
                type="text"
                placeholder="Room Name"
                value={room}
                onChange={(e) => setRoom(e.target.value)}
            />
            <input
                type="text"
                placeholder="Your Name"
                value={name}
                onChange={(e) => setName(e.target.value)}
            />
            <button className="create-meeting" onClick={handleCreate}>Create Meeting</button>

            {created && (
                <div className="meeting-info">
                    <h3>Upcoming Meetings</h3>
                    {meetings.map((meeting, index) => (
                        <div key={index}>
                            <p><strong>Room:</strong> {meeting.room} </p>
                            <p><strong>Name:</strong> {meeting.name}</p>
                            <button className="cpy" onClick={() => handleCopy(meeting.room)}>Copy Link</button>
                            <button className="start-btn" onClick={() => handleStartMeeting(meeting.room, meeting.name)}>Join Meeting</button>
                        </div>
                    ))}
                </div>
            )}

        </div>
    );
};

export default CreateMeeting;
