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, resClientId}) {
    const [rooms, setRooms] = useState([]);
    const [conversations, setConversations] = useState([]);

    const [users, setUsers] = useState([]);
    const [usersById, setUsersById] = useState([]);
    const [clientId, setClientId] = useState(resClientId|| null);

    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", 
      },
    });
    
    const users = await res.json();

    const map = {};
    for (const u of users) {
        map[u.id] = u.username;
    }
    setUsersById(map);

//   setUsers(users)
    return users;
  }

  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
  }

async function fetchConvUsers({ 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_conv_users/${conv_id}`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${accessTokenSingle}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(payload),
    });

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


  async function sendMessage({ conv_id, message }) {
    if (!conv_id) {    
      console.log("conv_id null at sendMessage")
      return
    };    

    const payload = {
      conv_id,
      message
    };

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

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

  async function addUserToConv({ conv_id, users}) {
    if (!conv_id || users) {
      console.log("error in convs or user to add")
    };

    const payload = {
      conv_id,
      users
    };

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


  }

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

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

      setClientId(resClientId);
      setRooms(roomsData);
      setConversations(convData);
      //console.log("USERS =",users)
      setUsers(usersData);
    }
    
    load();
    //console.log("USERS 2 =",usersById)
  }, [accessToken]);

  return (
    <HotelContext.Provider
      value={{
        rooms,
        conversations,
        users,
        usersById,
        clientId,
        updateRoomStatus,
        fetchMessages,
        fetchConvUsers,
        sendMessage,
        fetchHotelUsers,
        addUserToConv,
      }}
    >
      {children}
    </HotelContext.Provider>
  );
}
