import * as React from 'react';
import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import FuseSplashScreen from '@fuse/core/FuseSplashScreen';
import { showMessage } from 'app/store/fuse/messageSlice';
import { logoutUser, setUser } from 'app/store/userSlice';
import { authService, firebase } from '../services';

const cards = [
  {
    id: '123',
    image:
      'https://images.unsplash.com/photo-1600585154340-be6161a56a0c?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1170&q=80',
    title: '6 Via delle Crosarolle, Crosarolle, Veneto, Crosarolle, Veneto',
    category: 'buy',
    status: 'new',
    favorite: false,
    update: '12.12.2022',
    statistics: [
      { subject: 'Monthly Cash Flow', value: '$ 78,000', mode: 'extra_positive' },
      { subject: 'Cash on Cash Return', value: '78%', mode: 'positive' },
      { subject: 'Selling Prise', value: '$500,000', mode: '' },
      { subject: 'Cash Out of Pocket', value: '$125,000', mode: '' },
      { subject: 'Annual Revenue', value: '$5,000', mode: '' },
      { subject: 'Annual Net Profit', value: '+$50,000', mode: 'extra_positive' },
    ],
  },
  {
    id: '456',
    image:
      'https://images.unsplash.com/photo-1600585154340-be6161a56a0c?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1170&q=80',
    title: '6 Via delle Crosarolle, Crosarolle, Veneto',
    category: 'buy',
    status: 'new',
    favorite: false,
    update: '12.12.2022',
    statistics: [
      { subject: 'Monthly Cash Flow', value: '$ 78,000', mode: 'extra_negative' },
      { subject: 'Cash on Cash Return', value: '78%', mode: 'negative' },
      { subject: 'Selling Prise', value: '$500,000', mode: '' },
      { subject: 'Cash Out of Pocket', value: '$125,000', mode: '' },
      { subject: 'Annual Revenue', value: '$5,000', mode: '' },
      { subject: 'Annual Net Profit', value: '+$50,000', mode: 'extra_negative' },
    ],
  },
  {
    id: '789',
    image:
      'https://images.unsplash.com/photo-1600585154340-be6161a56a0c?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1170&q=80',
    title: '6 Via delle Crosarolle, Crosarolle, Veneto',
    category: 'rent',
    status: 'new',
    favorite: false,
    update: '12.12.2022',
    statistics: [
      { subject: 'Monthly Cash Flow', value: '$ 78,000', mode: 'positive' },
      { subject: 'Cash on Cash Return', value: '78%', mode: 'positive' },
      { subject: 'Selling Prise', value: '$500,000', mode: '' },
      { subject: 'Cash Out of Pocket', value: '$125,000', mode: '' },
      { subject: 'Annual Revenue', value: '$5,000', mode: '' },
      { subject: 'Annual Net Profit', value: '+$50,000', mode: 'extra_positive' },
    ],
  },
];

const AuthContext = React.createContext();

function AuthProvider({ children }) {
  const [isAuthenticated, setIsAuthenticated] = useState(undefined);
  const [waitAuthCheck, setWaitAuthCheck] = useState(true);
  const dispatch = useDispatch();

  useEffect(() => {
    authService.on('onLogout', () => {
      pass('Signed out');

      dispatch(logoutUser());
    });

    authService.init(firebase.auth, firebase.db);

    authService.onAuthStateChanged((authUser) => {
      dispatch(showMessage({ message: 'Signing...' }));
      if (authUser) {
        const storageUser = JSON.parse(localStorage.user ?? '{}');
        authService
          .getUserData(authUser.uid)
          .then((user) => {
            if (user) {
              success({ ...user, ...storageUser }, 'Signed in');
            } else {
              // First login
              const { displayName, photoURL, email } = authUser;
              success(
                { role: 'user', data: { displayName, photoURL, email }, ...storageUser },
                'Signed in'
              );
            }
          })
          .catch((error) => {
            pass(error.message);
          });
      } else {
        pass('Signed out');
      }
    });

    function success(user, message) {
      if (message) {
        dispatch(showMessage({ message }));
      }

      Promise.all([
        dispatch(setUser(user)),
        // You can receive data in here before app initialization
      ]).then((values) => {
        setWaitAuthCheck(false);
        setIsAuthenticated(true);
      });
    }

    function pass(message) {
      if (message) {
        dispatch(showMessage({ message }));
      }

      setWaitAuthCheck(false);
      setIsAuthenticated(false);
    }
  }, [dispatch]);

  return waitAuthCheck ? (
    <FuseSplashScreen />
  ) : (
    <AuthContext.Provider value={{ isAuthenticated }}>{children}</AuthContext.Provider>
  );
}

function useAuth() {
  const context = React.useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within a AuthProvider');
  }
  return context;
}

export { AuthProvider, useAuth };
