import { useRouter } from 'next/router';
import React, { createContext, useEffect, useState } from 'react';
import CheckSession from 'src/api/checkSession';
import Loading from 'src/components/Loading';

const AuthContext = createContext();

const AuthProvider = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [username, setUsername] = useState(null);
  const router = useRouter();

  const performLogin = ({ values }) => {
    return fetch('/api/auth/login', { method: 'POST', body: JSON.stringify(values) })
      .then(res => res.json())
      .then(res_json => {
        let { status, username: username_found } = res_json;
        setUsername(username_found);

        if (status == 'admin login OK') {
          localStorage.setItem('session', JSON.stringify(res_json));

          router.replace('/admin');
        } else if (status == 'customer login OK') {
          localStorage.setItem('session', JSON.stringify(res_json));
          router.replace('/shopfront/customer/profile');
        } else {
          alert('Invalid username or password');
        }
      })
      .catch(error => {
        console.error(error);
      });
  };

  const performLogout = () => {
    setUsername(null);
    localStorage.clear('session');
  };

  const performChangePassword = ({ old_password, new_password }) => {
    return fetch('/api/auth/change_password', {
      method: 'POST',
      body: JSON.stringify({ username, old_password, new_password }),
    })
      .then(res => res.json())
      .then(res_json => {
        let { status } = res_json;

        if (status == 'password change ok') {
          performLogout();
          router.replace('/shopfront');
        } else {
          alert('password change failed');
        }
      })
      .catch(error => {
        console.error(error);
      });
  };

  let [loading, setLoading] = useState(true);
  useEffect(() => {
    let session_string = localStorage.getItem('session');
    if (session_string) {
      let { session } = JSON.parse(session_string);

      CheckSession({ session }).then(data => {
        let { username: username_found } = data;
        setUsername(username_found);
      });
      setLoading(false);
    } else {
      setLoading(false);
      router.replace('/shopfront');
    }
  }, []);

  const helloworld = () => {
    console.log('helloworld');
  };

  if (loading)
    return (
      <>
        <Loading />
      </>
    );

  return (
    <AuthContext.Provider
      value={{ username, setUsername, isAuthenticated, performLogin, performLogout, performChangePassword, helloworld }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export { AuthContext, AuthProvider };
