import React, {useState, useEffect } from 'react';
import { useAtom } from 'jotai'
import { serverConfigAtom } from '../../../state/state';
import { HiPlus } from 'react-icons/hi'
import {  Loader, Center, SimpleGrid, Title, Group, Button } from '@mantine/core'
import { useNavigate } from "react-router-dom";
import { useNotifications } from '@mantine/notifications';


import { backendAPI } from '../../../services/backend-api';
import LocationCard from '../../cards/LocationCard';


function LocationsPage() {
    // const [opened, setOpened] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [locations, setLocations] = useState([])
    const [serverConfig] = useAtom(serverConfigAtom)

    let navigate = useNavigate();



    const notifications = useNotifications();


    useEffect(() => {
        console.log("LOADING LOCATIONS PAGE!")
        setIsLoading(true)
        async function fetchSettings() {
          backendAPI.get('/locations').then(results => {
            console.log("CONFIG IN LOCATIONS: ", serverConfig)
            console.log("LOCATIONS: ", results.data)
            setLocations(results.data)
            setIsLoading(false)
          }).catch(err => {
            notifications.showNotification({
              title: 'Backend Notice',
              message: `Failed to fetch locations from backend! ${err}`,
              autoClose: false,
              color: "red",
            })
            setIsLoading(false)
          })
    
        }
        fetchSettings();
        

    }, [])

    return (
        <>
        <Center>{ isLoading && <Loader size="xl" variant="bars" />}</Center>
        <Center><Title order={1}>Locations</Title></Center>
        <Button mb="lg" leftIcon={<HiPlus />} onClick={(e) => {navigate("/locations/new")}}>Add New Location</Button>
        <SimpleGrid 
          spacing="md"
          cols={4}
          breakpoints={[
            { maxWidth: 'sm', cols: 1, spacing: 'md'},
            { maxWidth: 'md', cols: 3, spacing: "sm"},
            { maxWidth: 'lg', cols: 4, spacing: 'md'}
          ]}
        
        >
          { locations.map((location, idx) => 
             <LocationCard location={location} idx={idx}></LocationCard>
          )}
        </SimpleGrid>
        </>

    );
}

export default LocationsPage;