import * as React from "react";
import PropTypes from "prop-types";
import { Box, MenuItem, FormControl, Select } from "@mui/material";

export default function Dropdown({ dropDownData = [], dropDownKeys, onSelectChange = null, value = "" }) {
  const finalDropDownData = dropDownData || [];
  const { key, title } = dropDownKeys;

  const [selectedValue, setSelectedValue] = React.useState(
    finalDropDownData[0]?.Name || ""
  );

 React.useEffect(() => {
  if (key === "activityType") {
    setSelectedValue(finalDropDownData[2]?.Name || "");
    return;
  }
  if (finalDropDownData?.length > 0 && !value) {
    setSelectedValue(finalDropDownData[0].Name);
    return;
  }
  if (!value) {
    setSelectedValue("");
  }
}, [finalDropDownData, value, key]);



  const handleChange = (event) => {
    const newValue = event.target.value;
    setSelectedValue(newValue);
    if (onSelectChange) {
      onSelectChange(newValue, dropDownKeys.key);
    }
  };

  return (
    <Box>
      <FormControl
        sx={{
          width: 200,
          backgroundColor: "#fff",
        }}
        size="small"
      >
        <Select
          labelId="select-label"
          value={value || selectedValue}
          onChange={handleChange}
          renderValue={(selected) => selected || title}
          displayEmpty
        >
          {finalDropDownData?.map((item) => (
            <MenuItem key={item.Id} value={item.Name}>
              {item.Name}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </Box>
  );
}

Dropdown.propTypes = {
  dropDownData: PropTypes.arrayOf(
    PropTypes.shape({
      Id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
      Name: PropTypes.string.isRequired,
    })
  ),
  dropDownKeys: PropTypes.shape({
    key: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
  }).isRequired,
  onSelectChange: PropTypes.func,
  value: PropTypes.string,
};
