import React, {useState, useEffect, useContext, createContext} from 'react';
import { useAtom } from 'jotai'
import { activePageAtom, roomFilterAtom, serverConfigAtom } from '../../state/main';
import { Text, Loader, Center, Card, Image, Badge, Button, SimpleGrid, Group, Title } from '@mantine/core'
import { useNavigate } from "react-router-dom";
import { useNotifications } from '@mantine/notifications';


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


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


    const notifications = useNotifications();
    const navigate = useNavigate();

    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();
        

    }, [])

    const navigateToRooms = (locationID, locationName) => {
        setActivePage("rooms")
        setRoomsFilter({"filterType": "location", "locationID": locationID, "commonName": "location", "metadata": locationName})
        navigate("/rooms")
    }


    return (
        <>
        <Center>{ isLoading && <Loader size="xl" variant="bars" />}</Center>
        <Center><Title order={1}>Locations</Title></Center>
        <SimpleGrid cols={4} spacing="xl">
            { locations.map((location, idx) => 
                <Card key={`${idx} - ${location.ID}`} shadow="md" padding="md">
                    <Card.Section>
                        {location.CoverPhoto ? <Image src={`${serverConfig.baseURL}/photos/locations/${location.Name}/${location.CoverPhoto}`}></Image> : <Text>No Photo</Text>}
                    </Card.Section>
                    <Group position="apart">
                        <Text weight={500}>{location.Name}</Text>
                        <Badge variant="light">
                          { location.Rooms !== null && location.Rooms.length !== 0 && location.Rooms.length > 1 ? <Text>{location.Rooms.length} Rooms</Text> : <Text>{location.Rooms.length} Room</Text>}  
                        </Badge>
                    </Group>
                    <Text size="sm">{location.Description}</Text>
                    <Group>
                        <Button onClick={() => navigateToRooms(location.ID, location.Name)}>View Details</Button>
                        <Button onClick={() => navigateToRooms(location.ID, location.Name)}>View Rooms</Button>
                    </Group>

                </Card>
            )}
        </SimpleGrid>
        </>

    );
}

export default LocationsPage;