import React, { useEffect, useState } from 'react';
import { Routes, Route } from 'react-router-dom';
import { Home, Profile, Schedule, Settings } from '@src/pages';
import { Shell } from '@components';
import { useLocalStore } from '@components';
import axios from "axios";

const dept = {
  id: 1,
  company: 'Darien EMS - Post 53',
  abv: 'DEMS',
  billing_address: '0 Ledge Road',
  town: 'Darien',
  state: 'Connecticut',
  postal: '06820',
  country: 'United States',
  phone: '',
  display_time: '12',
  start_day: 'sunday',
  company_logo: '',
  employee_count: 1,
  subscription_expiration: '10/01/2025',
  schedulers: [3],
  managers: [2],
  administrators: [1]
};

const users = [
  {
    id: 1,
    first_name: 'ShiftSync-Administrator',
    last_name: 'Test-User',
    email: 'testuserA@shift-sync.com',
    is_ss_admin: false
  },
  {
    id: 2,
    first_name: 'ShiftSync-Manager',
    last_name: 'Test-User',
    email: 'testuserM@shift-sync.com',
    is_ss_admin: false
  },
  {
    id: 3,
    first_name: 'ShiftSync-Scheduler',
    last_name: 'Test-User',
    email: 'testuserS@shift-sync.com',
    is_ss_admin: false
  },
  {
    id: 4,
    first_name: 'ShiftSync-User',
    last_name: 'Test-User',
    email: 'testuserU@shift-sync.com',
    is_ss_admin: false
  },
]

const AppRouter = () => {
  const { user, setUser, setDepartment } = useLocalStore();
  const [userChanged, setUserChanged] = useState(false);
  const isDev = true; // change for it.

  const fetchAPI = async () => {
    const location = window.location;
    const uri = `${location?.protocol}//${location?.hostname}${isDev ? ':5172' : ''}/api`;
    const response = await axios.get(uri);
    console.log(response.data.fruits);
  };

  useEffect(() => {
    const localVersion = localStorage.getItem("APP_VERSION");
    const currentVersion = window.APP_VERSION;

    if (localVersion && localVersion !== currentVersion) {
      console.log("Version changed, forcing reload");
      localStorage.setItem("APP_VERSION", currentVersion);
      window.location.reload(true); // force full page reload
    } else {
      localStorage.setItem("APP_VERSION", currentVersion);
    }
    
    fetchAPI();
    // await call for getting the count of employees and any other calls to db.
    const employee_count = 1;
    const subs_expiration = '10/22/2025';
    setUser({
      ...users[0],
      scheduler: dept?.schedulers?.includes(1),
      manager: dept?.managers?.includes(1),
      administrator: dept?.administrators?.includes(1)
    });
    const newAdministrators = dept?.administrators?.map((admin) => {
      const user = users?.find((user) => {
        return user?.id === admin;
      });
      return { id: user?.id, value: `${user?.last_name}, ${user?.first_name}` };
    });
    const newManagers = dept?.managers?.map((manager) => {
      const user = users?.find((user) => {
        return user?.id === manager;
      });
      return { id: user?.id, value: `${user?.last_name}, ${user?.first_name}` };
    });
    const newSchedulers = dept?.schedulers?.map((scheduler) => {
      const user = users?.find((user) => {
        return user?.id === scheduler;
      });
      return { id: user?.id, value: `${user?.last_name}, ${user?.first_name}` };
    });
    const newUsers = users?.map((user) => {
      return { id: user?.id, value: `${user?.last_name}, ${user?.first_name}` };
    });
    setDepartment({
      ...dept,
      users: newUsers,
      schedulers: newSchedulers,
      managers: newManagers,
      administrators: newAdministrators,
      employee_count,
      subs_expiration
    });
  }, []);

  useEffect(() => {
    if (!userChanged && user) {
      if (user?.is_ss_admin) {
        setUser({
          ...user,
          scheduler: true,
          manager: true,
          administrator: true,
        });
      } else if (user?.administrator) {
        setUser({
          ...user,
          scheduler: true,
          manager: true,
        });
      } else if (user?.manager) {
        setUser({
          ...user,
          scheduler: true,
        });
      }
      setUserChanged(true);
    }
  }, [user]);


  return (
    <Shell>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/schedule" element={<Schedule />} />
        <Route path="/settings" element={<Settings />} />
        <Route path="/profile" element={<Profile />} />
      </Routes>
    </Shell>
  );
};

export default AppRouter
