import {Image, Text, Modal, SimpleGrid, Title, Loader, Center, Card, Group, Badge, Button, Tooltip} from '@mantine/core'
import { ExternalLink } from 'tabler-icons-react'
import {useEffect, useState } from 'react'
// import BackendAPI from '../services/backend'

const urlPrepend = "https://apps.ts.fedex.com/tsrphotos/"

function PhotoDisplay(props) {
    const { photos } = props
    //const [photosDisplay, setPhotosDisplay] = useState([])
    const [photosLoading, setPhotosLoading] = useState(false)
    const [numPhotos, setNumPhotos] = useState(photos.length)
      // Modal states
    const [photoOpened, setPhotoOpened] = useState(false)
    const [photoDetails, setPhotoDetails] = useState({
        "name": "",
        "data": null,
        "locationName": "",
    })
    const [rawPhotoArray, setRawPhotoArray] = useState([])


    useEffect(() => {
        const createPhotos = async () => {
            setPhotosLoading(true)
            if (photos.length > 0) {
                photos.forEach(async (photo) => {
                    console.log("Loading photo: ", photo.photo_path_txt)
                    const fullUrl = `${urlPrepend}${photo.photo_path_txt}`
                    let newPhoto = 
                        <Card key={photo.photo_path_txt} shadow="sm" p="lg" radius="md" withBorder>
                            <Card.Section>
                                <Image radius="md"
                                key={photo.photo_path_txt}
                                style={{ cursor: 'pointer'}} 
                                src={`${urlPrepend}${photo.photo_path_txt}`}
                                onClick={() => displayPhoto(fullUrl, photo)}
                                />
                            </Card.Section>
                            <Group position="apart" mt="md" mb="xs">
                                <Text weight={500}>{photo.photo_nm}</Text>
                                <Badge color="pink" variant="light">
                                    {photo.network_location ? photo.network_location.location_nm : "No Location"}
                                </Badge>
                            </Group>
                            <Text size="sm" mb="lg" color="dimmed">
                                {photo?.photo_notes_txt ? photo.photo_notes_txt : "No Photo Notes!"}
                            </Text>
                            {photo.latitude_nbr !== 0 && photo.longitude_nbr !== 0 &&
                                <Tooltip label={`${photo.latitude_nbr}, ${photo.longitude_nbr}`}>
                                     <Button mb="xl" color="dark" component='a' href={`https://maps.google.com/?q=${photo.latitude_nbr},${photo.longitude_nbr}`} target="_blank" leftIcon={<ExternalLink />}>View Photo in Google Maps</Button>
                                </Tooltip>
                            }
                        </Card>
                    setRawPhotoArray(currArray => [...currArray, newPhoto])
                    // }
                })
            }
        }

        if (photos.length > 0) {
            console.log("RECEIVED PHOTOS!", photos)
            setNumPhotos(photos.length)
            createPhotos()
        }
    }, [photos])

    useEffect(() => {
        if (photos.length === rawPhotoArray.length) {
            console.log("Done loading! ")
            setPhotosLoading(false) 
        }
    }, [rawPhotoArray, photos.length])

    
    

      // For displaying photos full screen
    const displayPhoto = async (photoUrl, photo) => {

        setPhotoDetails({
        // data: 'data:image/jpeg;base64,' + photoBinary,
        data: photoUrl,
        name: photo.photo_nm,
        locationName: photo.network_location ? photo.network_location.location_nm : ""
        })
        setPhotoOpened(true)
    }

    

   

    return (
        <>
        <Modal opened={photoOpened} onClose={() => setPhotoOpened(false)} title={photoDetails.name} size="full">
            <Image radius="md" 
            src={photoDetails.data}
            caption={photoDetails.locationName ? <><Text weight={700}>{photoDetails.locationName}</Text><Text>{photoDetails.name}</Text></>: <Text>{photoDetails.name}</Text>}
            withPlaceholder
            />
        </Modal>
        <Title mb="lg" order={3}>Photos: {numPhotos}</Title>
        <SimpleGrid 
            cols={4}
            breakpoints={[
                { maxWidth: 1080, cols: 2, spacing: 'md' },
                // { maxWidth: 755, cols: 2, spacing: 'sm' },
                { maxWidth: 600, cols: 1, spacing: 'sm' },
            ]}
        >
            {rawPhotoArray}
        </SimpleGrid>
        {photosLoading && <Center><Loader variant='bars' size="sm" /></Center>}

        </>
    )
}

export default PhotoDisplay