import React, { useState, useEffect } from 'react';
import './BotaoVideoChamada.css';
import { FaVideo, FaExpand, FaCompress, FaPhoneSlash } from 'react-icons/fa'; 
import { JitsiMeeting } from '@jitsi/react-sdk';
import { db } from '../firebaseConfig'; 
import { ref, set, remove } from "firebase/database"; 

// MOCK PACIENTE
const mockPacientes = [
  { id: 1, name: 'Paciente' } 
];

// DADOS DO MÉDICO
const MEU_ID_MEDICO = 'medico-99';
const MEU_NOME_MEDICO = 'Dr. Rafael'; 

const BotaoVideoChamada = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [isFullScreen, setIsFullScreen] = useState(false);
  const [callActive, setCallActive] = useState(false);
  const [callingPatient, setCallingPatient] = useState(null);
  const [roomName, setRoomName] = useState('');

  // UseEffect da tecla "Esc"
  useEffect(() => {
    const handleEscKey = (event) => {
      if (event.key === 'Escape' && isFullScreen) {
        setIsFullScreen(false);
      }
    };
    document.addEventListener('keydown', handleEscKey);
    return () => document.removeEventListener('keydown', handleEscKey);
  }, [isFullScreen]); 

  // Função para INICIAR a chamada
  const handleStartCall = (paciente) => {
    // Adiciona o #config para pular o lobby
    const newRoomName = `mediconnect-call-${MEU_ID_MEDICO}-${paciente.id}-${Date.now()}#config.prejoinPageEnabled=false`;
    const callRef = ref(db, `calls/paciente-${paciente.id}`);

    set(callRef, {
      incomingCall: {
        fromId: MEU_ID_MEDICO,
        fromName: MEU_NOME_MEDICO,
        roomName: newRoomName
      }
    });

    setRoomName(newRoomName);
    setCallingPatient(paciente);
    setCallActive(true);
  };

  // Função para ENCERRAR a chamada
  const handleHangUp = () => {
    if (callingPatient) {
      const callRef = ref(db, `calls/paciente-${callingPatient.id}`);
      remove(callRef); 
    }
    setCallActive(false);
    setCallingPatient(null);
    setRoomName('');
    console.log("Chamada encerrada.");
  };
  
  // Função para fechar a janela
  const toggleVideoChat = () => {
    setIsOpen(!isOpen);
    if (isOpen) { 
      handleHangUp(); 
      setIsFullScreen(false);
    }
  };
  
  // Função de Tela Cheia
  const handleFullScreen = () => {
    setIsFullScreen(!isFullScreen);
  };

  return (
    <div className="video-chat-container">
      {isOpen && (
        <div className={`video-chat-window ${isFullScreen ? 'pseudo-fullscreen' : ''}`}>
          
          <div className="video-chat-header">
            <h3>{callActive ? `Em chamada com...` : 'Iniciar Chamada'}</h3>
            
            {/* ================================== */}
            {/* BOTÕES DE VOLTA - CORREÇÃO AQUI */}
            {/* ================================== */}
            <div className="video-chat-controls">
              <button onClick={handleFullScreen} className="control-btn fullscreen-btn">
                {isFullScreen ? <FaCompress size={14} /> : <FaExpand size={14} />}
              </button>
              <button onClick={toggleVideoChat} className="control-btn close-btn">
                &times;
              </button>
            </div>

          </div>

          <div className="video-chat-body">
            
            {callActive ? (
              // TELA DE CHAMADA ATIVA (JITSI)
              <div className="call-screen">
                <JitsiMeeting
                  roomName={roomName}
                  domain="meet.jit.si"
                  userInfo={{
                    displayName: MEU_NOME_MEDICO
                  }}
                  configOverwrite={{
                    prejoinPageEnabled: false,
                    enableWelcomePage: false,
                    enableClosePage: false,
                    toolbarButtons: [
                      'microphone', 'camera', 'desktop', 'hangup', 'chat', 'settings'
                    ],
                  }}
                  interfaceConfigOverwrite={{
                    SHOW_SUBJECT: false, 
                    DISABLE_JOIN_LEAVE_NOTIFICATIONS: true,
                  }}
                  getIFrameRef={(iframe) => { iframe.style.height = '100%'; }}
                  onApiReady={(api) => {
                    api.on('videoConferenceLeft', handleHangUp);
                  }}
                />
              </div>
            ) : (
              // TELA DE LISTA DE PACIENTES
              <div className="patient-list-container">
                <p>Selecione um paciente para iniciar a chamada:</p>
                <ul className="patient-list">
                  {mockPacientes.map((paciente) => (
                    <li key={paciente.id} className="patient-item">
                      <span>{paciente.name}</span>
                      <button onClick={() => handleStartCall(paciente)} className="call-btn">
                        <FaVideo size={14} /> Chamar
                      </button>
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        </div>
      )}
      {/* Botão flutuante */}
      <button className="video-chat-button" onClick={toggleVideoChat}>
        <FaVideo size={22} color="white" />
      </button>
    </div>
  );
};

export default BotaoVideoChamada;