import { useState, useEffect } from 'react'
import { createContext } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

import { API_BASE } from './config.js'

import Login from './components/login.jsx'
import MainApp from './components/MainApp.jsx'
import AdminWidget from './components/widget/adminWidget.jsx'


export const ClientContext = createContext(null);

export function userContext() {}

export default function App() {
  const [loading, setLoading] = useState(true); // true while checking auth
  const [loggedIn, setLoggedIn] = useState(false);
  const [clientId, setClientId] = useState([]);

  const [updateUsername, setUpdateUsername] = useState("");
  const [updateCurrentPassword, setUpdateCurrentPassword] = useState("");
  const [updateNewPassword, setUpdateNewPassword] = useState("");


  const [logMenuOpen, setLogMenuOpen] = useState(false)


  useEffect(() => {
    checkAuth();
  }, []);

async function checkAuth() {
  setLoading(true);
  try {
     const res = await fetch(`${API_BASE}/auth/login_refresh_token`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "User-Agent": "react-app",
          },
          credentials: "include", // send cookies automatically
          body: JSON.stringify({
            device_id : "147ac10b-58cc-4372-a567-0e02b2c3d479", // or persistent device ID
          }),
    });

    if (!res.ok) {
      setLoggedIn(false);
      return;
    }

    const data = await res.json();
    localStorage.setItem("access_tokens", JSON.stringify(data.tokens));
    setClientId(data.user_id);
    setLoggedIn(true);
  } finally {
    setLoading(false);
  }
}


async function logoutUser() {

  try {
     const res = await fetch(`${API_BASE}/auth/logout_single_device`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "User-Agent": "react-app",
          },
          credentials: "include", // send cookies automatically
          body: JSON.stringify({
            device_id : "147ac10b-58cc-4372-a567-0e02b2c3d479", // or persistent device ID
          }),
    });

    const data = await res.json();

    localStorage.setItem("access_tokens", JSON.stringify(data.tokens));
    
    setClientId(data.user_id);
    setLoggedIn(false);
  } finally {
    checkAuth();
  }
}

async function logoutAllSessions() {
if (!accessTokenSingle) return;

  try {
     const res = await fetch(`${API_BASE}/auth/logout_all_devices`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "User-Agent": "react-app",
            Authorization: `Bearer ${accessTokenSingle}`
          },
          credentials: "include", // send cookies automatically
          body: JSON.stringify({
            //device_id : "147ac10b-58cc-4372-a567-0e02b2c3d479", // or persistent device ID
          }),
    });

    const data = await res.json();

    localStorage.setItem("access_tokens", JSON.stringify(data.tokens));
    
    setClientId(data.user_id);
    setLoggedIn(false);
  } finally {
    checkAuth();
  }
}

function RegisterUser() {

  let [username, setUserName] = useState("");
  let [password, setPassword] = useState("");
  let [displayName, setDisplayName] = useState("");

  let hotel_ids = [1];

  function registerUser(username, password, hotel_ids, displayname) {

  const payload = {
    username,
    password,
    hotel_ids,
    displayname
  } 

  console.log("Reg")

  const res = fetch(`${API_BASE}/auth/register`, {
      method: "PUT",
      headers: {"Content-Type": "application/json"},
      body: JSON.stringify(payload),
    }
  )
 
}

  return(
    <div className="CreateUserDiv">
                <input 
                value={username}
                onChange={e => setUserName(e.target.value)}
                placeholder="NomDeCompte"
                type="text" />

                <input 
                value={password}
                onChange={e => setPassword(e.target.value)}
                placeholder="Mot de Passe"
                type="text" />

                <input 
                value={displayName}
                onChange={e => setDisplayName(e.target.value)}
                placeholder="Nome afficher"
                type="text" />
                
                <button
                    onClick={() =>
                        registerUser(username, password, hotel_ids, displayName)
                    }
                >
                    Créer l'utilisateur
                </button>
          </div>
  );

}


async function updatePassword(e) {
  e.preventDefault();

  //try
  const payload = {
    username : updateUsername,
    current_password : updateCurrentPassword,
    newpassword : updateNewPassword
  }

  const res = await fetch(`${API_BASE}/auth/update_password`, {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
            "User-Agent": "react-app",
          },
          credentials: "include", // send cookies automatically
          body: JSON.stringify(payload),
        });

        if (!res.ok) {
        console.log("update password failed"+ updateCurrentPassword, updateNewPassword, updateUsername)
      }

}

  if (loading) return <p>Loading...</p>; // can show a spinner

return (
  <>
      <button className="user-btn" onClick={() => setLogMenuOpen(o => !o)}>
      ⚙️
      </button>

    {logMenuOpen && (
    <div className='log-menu'>  
      <button onClick={logoutUser}>disconnect</button>
      <button onClick={logoutAllSessions}>disconnect all session</button>

      <form onSubmit={updatePassword}>
        <h1>Update Password</h1>
        <input
          type="text"
          placeholder="Username"
          value={updateUsername}
          onChange={(e) => setUpdateUsername(e.target.value)}
        />

        <input
          type="text"
          placeholder="MDP actuel"
          value={updateCurrentPassword}
          onChange={(e) => setUpdateCurrentPassword(e.target.value)}
        />

        <input
          type="text"
          placeholder="Nouveau MDP"
          value={updateNewPassword}
          onChange={(e) => setUpdateNewPassword(e.target.value)}
        />
        <button type="submit">Uppdate</button>
      </form>
      <RegisterUser/>

      

    </div>
    )}
    

    {loggedIn ? (
      <MainApp resClientId={clientId} />
    ) : (
      <Login className='logLanding' onLogin={checkAuth} />
    )}
  </>
);
}






//export default App
