import React, { useState } from 'react';

import type { GeneralSizeProp } from '@/mui/types';

import setupGetConfigurationErrorCode, {
  ConfigurationErrorOutputType,
} from '@/modules/feeds/Editor/components/Dialogs/ConfigurationErrorDialog/helpers/setupGetConfigurationErrorCode';
import { langSelector, metadataLanguagesSelector } from '@/modules/feeds/Editor/redux/selectors';
import { setAction } from '@/modules/feeds/Editor/redux/slices';

import { useFormSettings } from '@/modules/@common/Form';
import { useAppDispatch, useAppSelector, useAppStore } from '@/modules/@common/store/hooks';
import ConfigurationErrorDialog from '@/modules/feeds/Editor/components/Dialogs/ConfigurationErrorDialog/ConfigurationErrorDialog';
import { MenuItem, Select } from '@/mui/components';

type PropTypes = {
  disabled?: boolean;
};

function Language({ disabled = false }: PropTypes) {
  const dispatch = useAppDispatch();
  const store = useAppStore();
  const { size } = useFormSettings();
  const [configurationError, setConfigurationError] = useState<ConfigurationErrorOutputType>(null);

  const lang = useAppSelector(langSelector);
  const options = useAppSelector(metadataLanguagesSelector) || [];

  const getConfigurationErrorCode = setupGetConfigurationErrorCode(store);

  return (
    <>
      <Select
        // placeholder="Select Language"
        size={size as GeneralSizeProp}
        value={lang}
        disabled={disabled}
        onChange={(e) => {
          const selectedLang = e.target.value as string;
          const error = getConfigurationErrorCode({ inputLanguage: selectedLang });

          if (error) {
            setConfigurationError(error);
            return;
          }

          dispatch(setAction({ lang: selectedLang }));
        }}
      >
        {options.map((option) => (
          <MenuItem key={option.code} value={option.code}>
            {option.language}
          </MenuItem>
        ))}
      </Select>
      {!!configurationError && (
        <ConfigurationErrorDialog
          code={configurationError.code}
          lang={configurationError.lang}
          speechProvider={configurationError.speechProvider}
          open={!!configurationError}
          onClose={() => setConfigurationError(null)}
        />
      )}
    </>
  );
}

export default Language;
