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

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

type CreateOfferDialogProps = {
  showDialog: boolean;
  closeDialog: () => void;
  createConversation: () => void;
  setSelectedVendor: React.Dispatch<React.SetStateAction<VendorItem | null>>;
  vendors: VendorAPI[];
  selectedVendor: VendorAPI | null;
};

const CreateConversationDialogContent = ({
  showDialog,
  closeDialog,
  createConversation,
  setSelectedVendor,
  vendors,
  selectedVendor,
}: CreateOfferDialogProps): ReactElement => {
  const [options, setOptions] = useState<string[]>(vendors.map((vendor) => vendor.business_name));

  const [inputValue, setInputValue] = useState('');

  useEffect(() => {
    const filteredVendorNames: string[] = vendors.map((vendor) => {
      return vendor.business_name;
    });
    setOptions(filteredVendorNames);
  }, []);

  const handleInputChange = async (event, newInputValue) => {
    setInputValue(newInputValue);
    if (newInputValue) {
      const inputValue = newInputValue.toLowerCase();
      const filteredVendors = vendors.filter((vendor) =>
        vendor.business_name.toLowerCase().includes(inputValue),
      );
      const filteredVendorNames: string[] = filteredVendors.map((vendor) => {
        return vendor.business_name;
      });
      setOptions(filteredVendorNames);
    } else {
      setOptions([]);
    }
  };

  return (
    <Dialog open={showDialog} onClose={closeDialog} fullWidth>
      <DialogTitle>Start a new Conversation</DialogTitle>
      <DialogContent>
        <Autocomplete
          options={options} //vendors}
          //getOptionLabel={//(option) => option.name}
          onChange={(event, newValue) => {
            const filteredVendors = vendors.filter((vendor) => vendor.business_name === newValue);
            setSelectedVendor(filteredVendors[0]);
          }}
          inputValue={inputValue}
          onInputChange={handleInputChange}
          noOptionsText={'Type the vendor to search for'}
          renderInput={(params) => (
            <TextField {...params} label="Select a Vendor" variant="outlined" />
          )}
        />
      </DialogContent>
      <DialogActions>
        <Button onClick={closeDialog}>Cancel</Button>
        <Button onClick={createConversation} color="primary" disabled={!selectedVendor}>
          Create
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default CreateConversationDialogContent;
