// src/components/PropertyOwnerProfile/AddOpenHouseDialog.tsx

import React, { useState } from 'react';
import {
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  MenuItem,
  Autocomplete,
} from '@mui/material';
import { PropertiesAPI, OpenHouseAPI } from 'types'; // Ensure you have OpenHouseAPI in your types

import { DatePicker, TimePicker, LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';

interface AddOpenHouseDialogProps {
  open: boolean;
  onClose: () => void;
  onAddOpenHouse: (openHouse: Omit<OpenHouseAPI, 'id'> & { listed_date: string }) => void;
  properties: PropertiesAPI[];
  errors: { [key: string]: string };
}

const AddOpenHouseDialog: React.FC<AddOpenHouseDialogProps> = ({
  open,
  onClose,
  onAddOpenHouse,
  properties,
  errors,
}) => {
  const [propertyId, setPropertyId] = useState<number | ''>('');
  const [selectedProperty, setSelectedProperty] = useState<PropertiesAPI | null>(null);
  const [startTime, setStartTime] = useState<Date | null>(new Date());
  const [endTime, setEndTime] = useState<Date | null>(new Date());
  const [date, setDate] = useState<Date | null>(new Date());
  const [inputValue, setInputValue] = useState('');

  const [options, setOptions] = useState<string[]>([]);

  const handleAddOpenHouse = () => {
    if (selectedProperty && startTime && endTime && date) {
      const newOpenHouse = {
        property: selectedProperty.id,
        start_time: startTime.toTimeString().split(' ')[0],
        end_time: endTime.toTimeString().split(' ')[0],
        listed_date: date.toISOString().split('T')[0],
      };

      onAddOpenHouse(newOpenHouse);
      // onClose();
      // selectedProperty(null);
      // setStartTime(new Date());
      // setEndTime(new Date());
    }
  };

  console.log(errors);

  const handleInputChange = async (event: React.SyntheticEvent, newInputValue: string) => {
    setInputValue(newInputValue);
    if (newInputValue) {
      const filteredPropertiesNames: string[] = properties.map((item) => {
        return item.address;
      });
      setOptions(filteredPropertiesNames);
    } else {
      setOptions([]);
    }
  };

  return (
    <Dialog open={open} onClose={onClose}>
            <DialogTitle>Add New Open House</DialogTitle>     {' '}
      <DialogContent>
               {' '}
        <LocalizationProvider dateAdapter={AdapterDateFns}>
                   {' '}
          <Autocomplete
            options={options}
            value={selectedProperty?.address || ''}
            onChange={(event, newValue) => {
              const selectedAddr = properties.find((item) => item.address === newValue);
              setSelectedProperty(selectedAddr || null);
            }}
            onInputChange={handleInputChange}
            noOptionsText={'Type the address you want to set an open house for'}
            renderInput={(params) => (
              <TextField {...params} label="Select Property" fullWidth required margin="normal" />
            )}
          />
          <DatePicker
            label="Date"
            value={date}
            onChange={(newValue) => setDate(newValue)}
            slotProps={{ textField: { fullWidth: true } }}
            helperText={errors.listed_date}
            error={!!errors.listed_date}
          />
          <TimePicker
            label="Start Time"
            value={startTime}
            onChange={(newValue) => setStartTime(newValue)}
            slotProps={{ textField: { fullWidth: true } }}
          />
          <TimePicker
            label="End Time"
            value={endTime}
            onChange={(newValue) => setEndTime(newValue)}
            slotProps={{ textField: { fullWidth: true } }}
          />
                 {' '}
        </LocalizationProvider>
             {' '}
      </DialogContent>
           {' '}
      <DialogActions>
               {' '}
        <Button onClick={onClose} color="primary">
                    Cancel        {' '}
        </Button>
               {' '}
        <Button
          onClick={handleAddOpenHouse}
          color="primary"
          variant="contained"
          disabled={!selectedProperty}
        >
                    Add        {' '}
        </Button>
             {' '}
      </DialogActions>
         {' '}
    </Dialog>
  );
};

export default AddOpenHouseDialog;
