// src/pages/Meetings.jsx
import React, { useState, useEffect } from "react";
import axios from "../config/axiosInstance";
import "./Meetings.css";

const Meetings = () => {
  const [meetings, setMeetings] = useState([]);
  const [selectedMeeting, setSelectedMeeting] = useState(null);
  const [chatMessages, setChatMessages] = useState([]);
  const [loading, setLoading] = useState(false);
  const [filter, setFilter] = useState("all"); // all, completed, active

  useEffect(() => {
    fetchMeetings();
  }, [filter]);

  const fetchMeetings = async () => {
    setLoading(true);
    try {
      const response = await axios.get("/meetings", {
        params: { status: filter === "all" ? undefined : filter },
      });
      setMeetings(response.data);
    } catch (error) {
      console.error("Error fetching meetings:", error);
    } finally {
      setLoading(false);
    }
  };

  const fetchChatHistory = async (meetingId) => {
    try {
      const response = await axios.get(`/chats/${meetingId}`);
      setChatMessages(response.data);
    } catch (error) {
      console.error("Error fetching chat history:", error);
      setChatMessages([]);
    }
  };

  const handleMeetingSelect = (meeting) => {
    setSelectedMeeting(meeting);
    fetchChatHistory(meeting._id);
  };

  const formatMessageTime = (timestamp) => {
    return new Date(timestamp).toLocaleTimeString();
  };

  const getMessageTypeIcon = (type) => {
    switch (type) {
      case "image":
        return "🖼️";
      case "file":
        return "📁";
      default:
        return "💬";
    }
  };

  return (
    <div className="meetings-page">
      <div className="meetings-header">
        <h1>Meeting History</h1>

        {/* Filter Controls */}
        <div className="filter-controls">
          <button
            className={filter === "all" ? "active" : ""}
            onClick={() => setFilter("all")}
          >
            All Meetings
          </button>
          <button
            className={filter === "completed" ? "active" : ""}
            onClick={() => setFilter("completed")}
          >
            Completed
          </button>
          <button
            className={filter === "active" ? "active" : ""}
            onClick={() => setFilter("active")}
          >
            Active
          </button>
        </div>
      </div>

      <div className="meetings-content">
        {/* Meetings List */}
        <div className="meetings-list">
          {loading ? (
            <div className="loading">Loading meetings...</div>
          ) : meetings.length === 0 ? (
            <div className="no-meetings">No meetings found</div>
          ) : (
            meetings.map((meeting) => (
              <div
                key={meeting._id}
                className={`meeting-item ${
                  selectedMeeting?._id === meeting._id ? "selected" : ""
                }`}
                onClick={() => handleMeetingSelect(meeting)}
              >
                <div className="meeting-info">
                  <h3>{meeting.title}</h3>
                  <p className="room-id">Room: {meeting.roomId}</p>
                  <p className="meeting-time">
                    {meeting.endedAt
                      ? `Ended: ${new Date(meeting.endedAt).toLocaleString()}`
                      : `Started: ${new Date(
                          meeting.createdAt
                        ).toLocaleString()}`}
                  </p>
                </div>
                <div className="meeting-status">
                  <span className={`status-badge ${meeting.status}`}>
                    {meeting.status}
                  </span>
                  {meeting.participantCount && (
                    <span className="participant-count">
                      {meeting.participantCount} participants
                    </span>
                  )}
                </div>
              </div>
            ))
          )}
        </div>

        {/* Chat History Panel */}
        <div className="chat-history-panel">
          {selectedMeeting ? (
            <>
              <div className="chat-header">
                <h2>Chat History</h2>
                <div className="meeting-details">
                  <h3>{selectedMeeting.title}</h3>
                  <p>Room: {selectedMeeting.roomId}</p>
                </div>
              </div>

              <div className="chat-messages">
                {chatMessages.length === 0 ? (
                  <div className="no-messages">
                    No chat messages in this meeting
                  </div>
                ) : (
                  chatMessages.map((message) => (
                    <div key={message._id} className="message-item">
                      <div className="message-header">
                        <span className="message-icon">
                          {getMessageTypeIcon(message.messageType)}
                        </span>
                        <span className="participant-name">
                          {message.participantName || "Unknown User"}
                        </span>
                        <span className="message-time">
                          {formatMessageTime(message.timestamp)}
                        </span>
                      </div>

                      <div className="message-content">
                        {message.messageType === "text" && (
                          <p>{message.message}</p>
                        )}
                        {message.messageType === "image" && (
                          <div className="image-message">
                            <img src={message.fileUrl} alt="Shared image" />
                            <p>{message.message}</p>
                          </div>
                        )}
                        {message.messageType === "file" && (
                          <div className="file-message">
                            <a
                              href={message.fileUrl}
                              target="_blank"
                              rel="noopener noreferrer"
                            >
                              📁 {message.fileName}
                            </a>
                            <p>{message.message}</p>
                          </div>
                        )}
                      </div>
                    </div>
                  ))
                )}
              </div>

              {/* Meeting Statistics */}
              <div className="meeting-stats">
                <h3>Meeting Statistics</h3>
                <div className="stats-grid">
                  <div className="stat-item">
                    <label>Duration:</label>
                    <span>{selectedMeeting.duration || "In Progress"}</span>
                  </div>
                  <div className="stat-item">
                    <label>Messages:</label>
                    <span>{chatMessages.length}</span>
                  </div>
                  <div className="stat-item">
                    <label>Recording:</label>
                    <span>
                      {selectedMeeting.recordingUrl ? (
                        <a
                          href={selectedMeeting.recordingUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                        >
                          View Recording
                        </a>
                      ) : (
                        "Not Available"
                      )}
                    </span>
                  </div>
                </div>
              </div>
            </>
          ) : (
            <div className="no-selection">
              <h2>Select a meeting to view chat history</h2>
              <p>
                Click on any meeting from the list to see its chat messages and
                details.
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Meetings;
