import React from 'react';
import { Text, Button, Card, Group, Menu, Image, Badge } from '@mantine/core'
import { useAtom } from 'jotai';
import { useNavigate } from "react-router-dom";
import { activePageAtom, roomFilterAtom, serverConfigAtom } from '../../state/main';



function LocationCard(props) {
    const {location, idx} = props
    const [serverConfig] = useAtom(serverConfigAtom)
    const [, setRoomsFilter] = useAtom(roomFilterAtom)
    const [, setActivePage] = useAtom(activePageAtom)

    const navigate = useNavigate();

    const setRoomNumber = (rooms) => {
        if (rooms === null) {
          return <Text>0 Rooms</Text>
        } else if (rooms.length > 1) {
          return <Text>{rooms.length} Rooms</Text>
        } else {
          return <Text>1 Room</Text>
        }
      }

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


    return (
        <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>}
                <Group position='right' style={{position: 'absolute', top: '5px', right: '5px', backgroundColor: 'grey', borderRadius: '25%'}}>
                    <Menu>
                    <Menu.Label>Edit</Menu.Label>
                    <Menu.Label>Delete</Menu.Label>
                    </Menu>
                </Group>

            </Card.Section>
            <Group position="apart">
                <Text weight={500}>{location.Name}</Text>
                <Badge variant="light">
                    { setRoomNumber(location.Rooms) }  
                </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>
    );
}

export default LocationCard;