import { Button, Box, Dialog, DialogActions, DialogContent, DialogTitle, Stack, Typography, Autocomplete, TextField, Paper } from "@mui/material";

import { ReactElement, useState } from "react";
import {axiosInstance} from '../../../../../axiosApi'
import { PropertiesAPI } from "types";
import { AxiosResponse } from "axios";

type CreateOfferDialogProps = {
    showDialog: boolean;
    closeDialog: () => void;
    createOffer: () => void;
}

type OfferPropertyType = {
    address: string;
    marketValue: string;
    property_id: number;

}

const CreateOfferDialog = ({showDialog, closeDialog, createOffer}: CreateOfferDialogProps): ReactElement => {
    const [inputValue, setInputValue] = useState('');
    const [options, setOptions] = useState<string[]>([]);
    const [filteredProperties, setFilteredProperties]  = useState<OfferPropertyType[]>([]);
    const [selectedProperty, setSelectedProperty] = useState<OfferPropertyType | null | undefined>(null);
    
    const [offerAmount, setOfferAmount] = useState<number | ''>('');
    const [closingDuration, setClosingDuration] = useState<number | ''>('');

    const handleInputChange = async (event, newInputValue) => {
        setInputValue(newInputValue);
        if(newInputValue){
            const {data,}: AxiosResponse<PropertiesAPI[]> = await axiosInstance.get(`/properties/?search=${newInputValue}`)
            
            const filteredPropertieResults: OfferPropertyType[]= data.map(item => {
                return {
                    address: item.address,
                    marketValue: item.market_value,
                    property_id: item.id
                }
            })
            setFilteredProperties(filteredPropertieResults);
            const filteredPropertiesNames: string[] = data.map(item => {
                return item.address
            })
            setOptions(filteredPropertiesNames);
            
        }else{
            setOptions([]);
        }
        
    };
    return(
        <Dialog
            open={showDialog}
            onClose={closeDialog}
          
          >
            <DialogTitle>
              Create new offer
            </DialogTitle>
            <DialogContent>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Stack direction='column' sx={{flexGrow: 1}}>
                        <Autocomplete 
                        value={null}
                        options={options}
                        onChange={(event, newValue) => {
                            const selectedAddress = options.find(item => item === newValue)
                            if(selectedAddress){
                                setSelectedProperty(filteredProperties.find(item => item.address === selectedAddress))

                            }
                            
                        }}
                        inputValue={inputValue}
                        onInputChange={handleInputChange}
                        noOptionsText={"Type the address to search for"}
                        renderInput={(params) => (<TextField {...params} label="search for a property" variant="outlined" />)}>

                        </Autocomplete>
                        {!selectedProperty? (
                            <Box sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', p: 3, color: 'grey.500' }}>
                                
                                <Typography variant="h6">Search for a property to create an offer </Typography>
                                <Typography variant="body2">Click on an offer from the left panel to get started.</Typography>
                            </Box>

                        ):(
                            <Box sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', p: 3, color: 'grey.500' }}>
                                
                                <Typography variant="h6">{selectedProperty.address} </Typography>
                                
                            </Box>

                        )}
                    </Stack>
                    <Stack direction='column' >
                        
                        <Typography>
                        Offer Price
                        </Typography>
                        <TextField
                            label="Offer Amount ($)"
                            type="number"
                            defaultValue={selectedProperty? selectedProperty.marketValue : ''}
                            value={offerAmount}
                            onChange={(e) => setOfferAmount(e.target.value === '' ? '' : Number(e.target.value))}
                            fullWidth
                            variant="outlined"
                            inputProps={{ min: 0 }}
                            disabled={!selectedProperty}
                        />
                        <TextField
                            label="Closing Duration (days)"
                            type="number"
                            value={closingDuration}
                            onChange={(e) => setClosingDuration(e.target.value === '' ? '' : Number(e.target.value))}
                            fullWidth
                            variant="outlined"
                            inputProps={{ min: 0 }}
                            disabled={!selectedProperty}
                        />
                        <TextField
                            label="Other"
                            type="text"
                            // value={closingDuration}
                            // onChange={(e) => setClosingDuration(e.target.value === '' ? '' : Number(e.target.value))}
                            fullWidth
                            variant="outlined"
                            inputProps={{ min: 0 }}
                            disabled={!selectedProperty}
                        />
                    </Stack>

                </Box>
            </DialogContent>
            <DialogActions>
                <Button onClick={closeDialog}>Cancel</Button>
                <Button 
                    onClick={async () => 
                        await createOffer(selectedProperty.property_id)
                    }
                    disabled={!selectedProperty}
                >Create</Button>
            </DialogActions>

          </Dialog>
    )
}

export default CreateOfferDialog;
