import React, { useRef } from 'react';
import { IonContent, IonPage, useIonViewDidEnter, useIonViewWillLeave } from '@ionic/react';
import back from '../../assets/back.png';
import { useHistory } from 'react-router-dom';
import { useFunctionService } from '../components/Layout';
import { useChatKeyboard } from '../hooks/useChatKeyboard';
import $ from 'jquery';


const ChatDriver: React.FC = () => {
    const { registerFunction } = useFunctionService();
    const [showDriverOptions, setShowDriverOptions] = React.useState(false);
    const history = useHistory();
    const [messages, setMessages] = React.useState([]);
    const [theMessage, setTheMessage] = React.useState("");
    const chatContainerRef = useRef<HTMLDivElement>(null);
    const { keyboardOffset, onInputFocus } = useChatKeyboard(chatContainerRef);
      const isRegisteredRef = React.useRef(false);
    const pollRef = React.useRef<ReturnType<typeof setInterval> | null>(null);
    const CHAT_POLL_MS = 5000;
    const [nombreCliente, setNombreCliente] = React.useState("");

    useIonViewDidEnter(() => {
        getChats();
        driverDetails();
        if (pollRef.current) {
            clearInterval(pollRef.current);
        }
        pollRef.current = setInterval(() => {
            getChats();
        }, CHAT_POLL_MS);

        if (!isRegisteredRef.current) {
            registerFunction('updateChatDriver', () => {
                getChats();
                driverDetails();
            });
            isRegisteredRef.current = true;
        }
    });

    useIonViewWillLeave(() => {
        if (pollRef.current) {
            clearInterval(pollRef.current);
            pollRef.current = null;
        }
    });

    const scrollToBottom = () => {
        if (chatContainerRef.current) {
            chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
        }
    };

    const insertMessage = () => {
        if (theMessage === "") {
            return;
        }
        $.post(localStorage.apiurl, {
            op: "insert_message",
            id_pedido: localStorage.id_pedido,
            id_emisor: localStorage.driver_id,
            who_sends: "driver",
            mensaje: theMessage
        },
            (data) => {
                console.log(data);
                getChats();
                setTheMessage("");
            });
    }

    const driverDetails = () => {
        $.getJSON(localStorage.apiurl, {
            op: 'carrera_detail',
            id_carrera: localStorage.id_pedido,
        }, (data) => {
            console.log("carrera_detail");
            setNombreCliente(data[0].nombrecliente);

           
        });
    }

    const getChats = () => {
        $.getJSON(localStorage.apiurl + "/ws.php?op=get_conversation&id_pedido=" + localStorage.id_pedido + "&id_emisor=" + localStorage.driver_id,
            (data) => {
                console.log(data);
                setMessages(data);
                setTimeout(scrollToBottom, 100); // Delay to ensure DOM is updated before scrolling
            });
    }



    const gototracker = () => {
        history.push('/detail');
    }

 return (
  <IonPage>
    <IonContent scrollY={false} className="v2_chat_ion_content" style={{ '--overflow': 'hidden' }}>
      <div
        className={`v2_chat_page${keyboardOffset > 0 ? ' v2_chat_keyboard_open' : ''}`}
        style={{ ['--chat-kb-offset' as string]: `${keyboardOffset}px` }}
      >

        {/* HEADER */}
        <div className="v2_chat_header v2_animate_in">
          <div className="v2_chat_driver_info">
            <div style={{
              width: 46, height: 46,
              borderRadius: '50%',
              background: 'rgba(6,47,129,0.35)',
              border: '2px solid rgba(77,139,255,0.3)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 20, flexShrink: 0
            }}>
              👤
            </div>
            <div className="v2_chat_driver_texts">
              <p className="v2_chat_driver_name">{nombreCliente}</p>
              <p className="v2_chat_driver_sub">Cliente</p>
            </div>
          </div>
          <div className="v2_back_btn" onClick={gototracker}>
            <img src={back} alt="back" />
          </div>
        </div>

        {/* MESSAGES */}
        <div
          ref={chatContainerRef}
          className="v2_chat_messages"
        >
          {messages.map((message, index) => (
            message.frommessage === "me" ? (
              <div key={index} className="v2_msg_from">
                {message.mensaje}
              </div>
            ) : (
              <div key={index} className="v2_msg_to">
                {message.mensaje}
              </div>
            )
          ))}
        </div>

        {/* FOOTER */}
        <div className="v2_chat_footer">
          <div className="v2_chat_input_wrap">
            <textarea
              value={theMessage}
              onChange={(e) => setTheMessage(e.target.value)}
              className="v2_chat_textarea"
              placeholder="Escribe un mensaje..."
              rows={1}
              onFocus={onInputFocus}
            />
          </div>
          <button className="v2_chat_send_btn" onClick={insertMessage}>
            ➤
          </button>
        </div>

      </div>
    </IonContent>
  </IonPage>
);
};

export default ChatDriver;
