import React, {useState, useEffect} from 'react';
import { Text, Title, TextInput, Button, NumberInput, Textarea, Grid, Group, useMantineTheme, MantineTheme, Image, SimpleGrid } from '@mantine/core'
import { DatePicker } from '@mantine/dates';
import dayjs from 'dayjs';
import { useForm } from '@mantine/form';
import { useAtom } from 'jotai';
import { serverConfigAtom } from '../../../state/state'
import { backendAPI } from '../../../services/backend-api';
import { IMAGE_MIME_TYPE } from '@mantine/dropzone';
import CustomDropZone from '../../CustomDropZone';



function NewLocationForm(props) {
    const {location, modify: bool} = props
    const [opened, setOpened] = useState(false);
    const [serverConfig] = useAtom(serverConfigAtom)
    // Cover Photo
    const [coverPhoto, setCoverPhoto] = useState(null)
    // Additional Photos
    const [additionalPhotos, setAdditionalPhotos] = useState([])

    const theme = useMantineTheme();


    const form = useForm({
        initialValues: {
            Name: '',
            Description: '',
            Notes: '',
            Address: '',
            SquareFeet: '',
            Latitude: '',
            Longitude: '',
            DatePurchased: '',
            PurchasePrice: '',
            CurrentValue: '',
            CoverPhoto: '',
            AdditionalPhotos: [],
        },

        validate: {
            Name: (value) => (/^\S+/.test(value) ? null : 'Invalid Name')
        },
    });

    

    const submitNewLocation = (values) => {
        console.log("VALUES: ", values)
        // let additionalPhotos = values.AdditionalPhotos
        let formData = new FormData()
        for (const [key, value] of Object.entries(values)) {
            if (key === "AdditionalPhotos" && value.length > 0) {
                value.forEach(photo => {
                    console.log("PHOTO VALUE: ", photo)
                    formData.append(key, photo)
                });
            }
            formData.append(key, value)
        }
        backendAPI.post("/locations/new", formData).then((result) => {
            console.log("STATUS: ", result.status)
            console.log("result: ", result.data)
        }).catch(err => {
            console.log("Error adding new location!", err)
        })
    }
    

    const handleFileAccept = (files) => {
        form.setFieldValue('CoverPhoto', files[0])
        const imageUrl = URL.createObjectURL(files[0]);
        setCoverPhoto(
            <Image
                key={"coverPhoto"}
                src={imageUrl}
                imageProps={{ onLoad: () => URL.revokeObjectURL(imageUrl) }}
            />
        )
    }

    const handleAdditionalPhotos = (files) => {
        setAdditionalPhotos(oldPhotos => [...oldPhotos, ...files])
        // setAdditionalPhotos(files)
        console.log("FORM VALUES: ",form.values)
        const oldValues = form.values['AdditionalPhotos']
        form.setFieldValue('AdditionalPhotos', [...oldValues, ...files])
        console.log("NEW FORM VALUES: ", form.values)

    }

    const previews = additionalPhotos.map((file, index) => {
        console.log("FILE IS: ", file)
        const imageUrl = URL.createObjectURL(file);
        return (
          <Image
            key={index}
            src={imageUrl}
            imageProps={{ onLoad: () => URL.revokeObjectURL(imageUrl) }}
          />
        )
    })

    return (
        <>
            <Title>Location Form</Title> 
            <form onSubmit={form.onSubmit((values) => submitNewLocation(values))}>
                <Grid>

                    <Grid.Col md={6} lg={4} sm={12} xs={12}>
                        <TextInput label="Location Name" value={form.values.Name} required {...form.getInputProps('Name')}/>
                        <TextInput label="Description" value={form.values.Description} {...form.getInputProps('Description')} />
                        <Textarea label="Location Notes" value={form.values.Notes} {...form.getInputProps('Notes')}/>
                        <TextInput label="Street Address" value={form.values.Address} {...form.getInputProps('Address')} />
                        <NumberInput label="Square Feet" value={form.values.SquareFeet} {...form.getInputProps('SquareFeet')} />
                        <TextInput label="Latitude" value={form.values.Latitude} {...form.getInputProps('Latitude')} />
                        <TextInput label="Longitude" value={form.values.Longitude} {...form.getInputProps('Longitude')}/>
                        <DatePicker 
                            label="Date Purchased" 
                            value={form.values.DatePurchased} 
                            maxDate={dayjs(new Date()).add(1, 'days').toDate()}
                            {...form.getInputProps('DatePurchased')} 
                        />
                        <TextInput label="Purchase Price" value={form.values.PurchasePrice} {...form.getInputProps('PurchasePrice')}/>
                        <TextInput label="Current Value" value={form.values.CurrentValue} {...form.getInputProps('CurrentValue')}/>
                        <Group><Title order={4}>Location Cover Photo </Title><Text color="red">*</Text></Group>

                        {coverPhoto ?
                        coverPhoto
                        :
                        <CustomDropZone 
                            uploadText1={"Drag Image Here or click to select File"} 
                            uploadText2={"Single File, max size: 5mb"} 
                            uploadFormat={IMAGE_MIME_TYPE} 
                            maxSize={3 * 1024 ** 2}
                            multipleFiles={false} 
                            returnFiles={handleFileAccept}
                        />
                        }
                        <Title order={4}>Additional Location Photos</Title>
                        <CustomDropZone 
                            uploadText1={"Drag Images Here or click to select Files"} 
                            uploadText2={"Multiple Files, max size per file: 5mb"} 
                            uploadFormat={IMAGE_MIME_TYPE} 
                            maxSize={3 * 1024 ** 2}
                            multipleFiles={true} 
                            returnFiles={handleAdditionalPhotos}
                        />
                         <SimpleGrid
                            cols={4}
                            breakpoints={[{ maxWidth: 'sm', cols: 1 }]}
                            mt={previews.length > 0 ? 'xl' : 0}
                        >
                            {previews}
                        </SimpleGrid>
                        <Button type="submit">Submit</Button>
                    </Grid.Col>
                </Grid>
            </form>
        </>

    );
}

export default NewLocationForm;