import React, { useState } from "react";
import PropTypes from "prop-types";
import { Grid, TextField, FormControlLabel, Checkbox } from "@material-ui/core";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { useTranslation } from "react-i18next";

const MimeTypeComponent = ({ mimeType, mimeTypes, onPropertyChange }) => {
  const [isAutomaticMimeType, setIsAutomaticMimeType] = useState(
    mimeType.mimeTypeId === null
  );

  const { t } = useTranslation();

  const handleChangeAutomaticMimeType = (event) => {
    const checked = event.target.checked;
    setIsAutomaticMimeType(checked);
    onPropertyChange("mimeTypeId")(null);
  };

  return (
    <>
      <Grid item xs={12} sm={9}>
        {isAutomaticMimeType ? (
          <TextField
            id="automatic-resource-mime-type"
            label={t("Resource.AutomaticMimeType")}
            fullWidth
            disabled
            value={mimeType.mimeTypeName}
          />
        ) : (
          <Autocomplete
            id="resource-mime-type"
            options={mimeTypes}
            value={mimeType.mimeTypeId}
            onChange={(_event, value, _reason, _details) =>
              onPropertyChange("mimeTypeId")(value.mimeTypeId)
            }
            getOptionLabel={(option) => {
              const optionIsObject =
                typeof option === "object" && option !== null;
              if (optionIsObject) return option.mimeTypeName;

              const mimeType = mimeTypes.find((z) => z.mimeTypeId === option);
              return mimeType.mimeTypeName;
            }}
            getOptionSelected={(option, value) => option.mimeTypeId === value}
            renderInput={(params) => (
              <TextField {...params} label={t("Resource.MimeType")} />
            )}
          />
        )}
      </Grid>
      <Grid item xs={12} sm={3}>
        <FormControlLabel
          control={
            <Checkbox
              checked={isAutomaticMimeType}
              onChange={handleChangeAutomaticMimeType}
              name="automatic-mime-type"
              color="primary"
            />
          }
          label={t("Resource.AutomaticMimeType")}
        />
      </Grid>
    </>
  );
};

MimeTypeComponent.propTypes = {
  mimeType: PropTypes.object.isRequired,
  mimeTypes: PropTypes.array.isRequired,
  onPropertyChange: PropTypes.func.isRequired
};

export default MimeTypeComponent;
