import { createContext, useContext, useState, useEffect } from "react";
import { API_BASE } from "../config";

const HotelContext = createContext(null);

export function useHotel() {
  return useContext(HotelContext);
}

export function HotelProvider({ accessToken, children }) {
    const [rooms, setRooms] = useState([]);
    const [conversations, setConversations] = useState([]);
    const [users, setUsers] = useState([]);

    const tokens = JSON.parse(accessToken);
    const accessTokenSingle = tokens[0];

  // --- API FUNCTIONS ---
  async function fetchRooms() {
    const res = await fetch( `${API_BASE}/rooms/rooms`, {
      headers: { Authorization: `Bearer ${accessTokenSingle}` },
    });
    return res.json();
  }

  async function updateRoomStatus(roomId, status) {
    await fetch(`${API_BASE}/rooms/clean_db_update/${roomId}`, {
      method: "PUT",
      headers: {
        Authorization: `Bearer ${accessTokenSingle}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ status }),
    });

    // refresh cached rooms
    const updated = await fetchRooms();
    setRooms(updated);
  }

  async function fetchHotelUsers() {
    const res = await fetch(`${API_BASE}/chat/hotel_users`, {
      method: "POST",
      headers: { 
        Authorization: `Bearer ${accessTokenSingle}`,
        "Content-Type": "application/json", 
      },
    });
    return res.json();
  }

  async function fetchConversations() {
    const res = await fetch(`${API_BASE}/chat/get_conv`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${accessTokenSingle}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        conv_id: 4,
        timestamp: "2025-09-25 11:05:33",
      }),
    });
    return res.json();
  }

  async function fetchMessages({ conv_id }) {

    const payload = {
    conv_id,
    timestamp: "2025-09-25 11:05:33",
    };

    console.log(JSON.stringify(payload));

    const res = await fetch(`${API_BASE}/chat/get_message`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${accessTokenSingle}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(payload),
    });

    return res.json();
    
    //return res.json
  }


  // --- INITIAL DATA LOADING ---
  useEffect(() => {
    if (!accessToken) return;

    async function load() {
      const [roomsData, convData, usersData] = await Promise.all([
        fetchRooms(),
        fetchConversations(),
        fetchHotelUsers(),
      ]);

      setRooms(roomsData);
      setConversations(convData);
      setUsers(usersData);
    }

    load();
  }, [accessToken]);

  return (
    <HotelContext.Provider
      value={{
        rooms,
        conversations,
        users,
        updateRoomStatus,
        fetchMessages,
      }}
    >
      {children}
    </HotelContext.Provider>
  );
}
