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

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


function RoomsPage(props) {
    // const [opened, setOpened] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [rooms, setRooms] = useState([])
    const [filter, setFilter] = useState("");
    const [serverConfig] = useAtom(serverConfigAtom)
    const [roomFilter, setRoomFilter] = useAtom(roomFilterAtom)


    const notifications = useNotifications();
    const {state} = useLocation();

    useEffect(() => {
        setIsLoading(true)
        async function fetchSettings() {
            let url = `rooms`
            console.log("CURRENT STATE: ", state)
            // if we are filtering by location
            if (roomFilter.locationID) {
                url = `rooms/${roomFilter.locationID}`
            }
            backendAPI.get(url).then(results => {
                console.log("ROOMS: ", results)
                setRooms(results.data)
                setIsLoading(false)
            }).catch(err => {
                notifications.showNotification({
                title: 'Backend Notice',
                message: `Failed to fetch rooms from backend! ${err}`,
                autoClose: false,
                color: "red",
                })
                setIsLoading(false)
            })
    
        }
        fetchSettings();
        

    }, [roomFilter])

    // Check if filter changes for this page and refresh results
    useEffect(() => {
        console.log("CURRENT ROOM FILTER: ", roomFilter)

    }, [roomFilter, setRoomFilter])

    const removeFilterButton = (
        <ActionIcon size="xs" color="blue" radius="xl" variant="transparent">
          <Text>X</Text>
        </ActionIcon>
      );
    


    return (
        <>
        <Center>{ isLoading && <Loader size="xl" variant="bars" />}</Center>
        <Center><Title order={1}>Rooms</Title></Center>
        { Object.keys(roomFilter).length !== 0 && 
          <Badge sx={{ paddingLeft: 0 }} size="lg" radius="xl" color="teal" leftSection={removeFilterButton} onClick={() => {setRoomFilter({})}}>
            Filter by {roomFilter.commonName}: {roomFilter.metadata}
          </Badge>
        
        }
        <SimpleGrid cols={4} spacing="xl">
            { rooms.map((room, idx) => 
                <Card key={`${room.ID}`} component="a" onClick={(e) => {}} shadow="sm" padding="md">
                    <Card.Section>
                        {room.CoverPhoto ? <Image src={`${serverConfig.baseURL}/photos/locations/${room.CoverPhoto}`}></Image> : <Text>No Photo</Text>}
                    </Card.Section>
                    <Group position="apart">
                        <Text weight={500}>{room.Name}</Text>
                        <Group>
                            <Badge color="pink" variant="light">
                                {room.LocationName}
                            </Badge>
                            <Badge variant='light'>
                                {room.Cabinets === null ? 0 : room.Cabinets.length} Cabinets
                            </Badge>
                            <Badge color='teal' variant='light'>
                                {room.Cabinets === null ? 0 : room.Cabinets.length} Items
                            </Badge>
                        </Group>
                    </Group>
                    <Text size="sm">{room.Description}</Text>
                    <Group>
                        <Button onClick={() => console.log("test")}>View Details</Button>
                        <Button onClick={() => console.log("test")}>View Rooms</Button>
                    </Group>
                </Card>
            )}
        </SimpleGrid>
        </>

    );
}

export default RoomsPage;