import { type FC, useEffect, useState } from 'react';
import { useFormContext } from 'react-hook-form';

import HelpOutlineIcon from '@material-hu/icons/material/HelpOutline';
import Card from '@material-hu/mui/Card';
import CardContent from '@material-hu/mui/CardContent';
import CardHeader from '@material-hu/mui/CardHeader';
import Grid from '@material-hu/mui/Grid';
import ListItem from '@material-hu/mui/ListItem';
import ListItemText from '@material-hu/mui/ListItemText';
import Stack from '@material-hu/mui/Stack';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

import FormRadioCustomGroup from '@material-hu/components/deprecated/FormRadioCustomGroup';
import { type ButtonProps } from '@material-hu/components/design-system/Buttons/Button';

import { TIMEZONES } from 'src/constants/timezones';
import useAuth from 'src/contexts/JWTContext';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { PasswordTypeOptions } from 'src/types/instance';
import { getCurrencyOptions } from 'src/utils/currency/currency';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getLanguageOptions } from 'src/utils/languages';
import {
  validateObjectNullRule,
  validateRequiredEmailRule,
  validateRequiredStringRule,
} from 'src/utils/validation';

import CoverPicture from 'src/components/ArticleEditLayout/components/CoverPicture';
import FormAutocomplete from 'src/components/FormInputs/FormAutocomplete';
import FormSelect from 'src/components/FormInputs/FormSelect';
import FormSwitch from 'src/components/FormInputs/FormSwitch';
import FormTextField from 'src/components/FormInputs/FormTextField';

import { type FieldValues } from '../../form';

type Props = {
  SaveButton: FC<ButtonProps>;
};

const GeneralSettings = ({ SaveButton }: Props) => {
  const { t } = useLokaliseTranslation('settings');
  const NewThemeProvider = useHuGoTheme();
  const { instance } = useAuth();
  const [timezoneSearch, setTimezoneSearch] = useState('');

  const {
    formState: { errors },
    watch,
    setValue,
  } = useFormContext<FieldValues>();
  const { logo, ssoDomains } = watch();

  const hasDomains = !!ssoDomains.length;

  useEffect(() => {
    if (!hasDomains) {
      setValue('forceSSO', false, { shouldDirty: true });
    }
  }, [hasDomains]);

  const languageOptions = getLanguageOptions().map(option => ({
    ...option,
    label: t(option.label),
  }));

  return (
    <NewThemeProvider>
      <Stack sx={{ gap: 2 }}>
        <Card>
          <CardContent>
            <Grid
              container
              spacing={3}
            >
              <Grid
                item
                xs={12}
                sm={10}
              >
                <FormTextField
                  label={t('GENERAL.INSTANCE_NAME')}
                  name="name"
                  required
                  rules={{ validate: validateRequiredStringRule }}
                />
              </Grid>
              <Grid
                item
                xs={12}
                sm={2}
              >
                <FormTextField
                  label={t('GENERAL.COLOR')}
                  name="color"
                  type="color"
                  required
                />
              </Grid>
              <Grid
                item
                xs={12}
              >
                <FormTextField
                  name="adminEmail"
                  label={t('GENERAL.SUPPORT_EMAIL')}
                  type="email"
                  required
                  rules={{ validate: validateRequiredEmailRule }}
                />
              </Grid>
              <Grid
                item
                xs={12}
              >
                <FormSelect
                  name="language"
                  label={t('GENERAL.INSTACE_LANGUAGE')}
                  options={languageOptions}
                  formControlProps={{ fullWidth: true }}
                />
              </Grid>
              <Grid
                item
                xs={12}
              >
                <FormAutocomplete
                  name="timezone"
                  autocompleteProps={{
                    limitTags: 2,
                    options: TIMEZONES,
                    isOptionEqualToValue: (option, value) =>
                      option.id === value.id,
                    getOptionLabel: option => option.label,
                    renderOption: (renderProps, option) => (
                      <ListItem
                        {...renderProps}
                        key={option.id}
                      >
                        <ListItemText
                          primary={option.label}
                          primaryTypographyProps={{
                            color: 'textPrimary',
                            noWrap: true,
                            variant: 'subtitle2',
                          }}
                        />
                      </ListItem>
                    ),
                    filterOptions: timezoneOption =>
                      timezoneOption.filter(tz =>
                        tz.label
                          .toLowerCase()
                          .includes(timezoneSearch.toLowerCase()),
                      ),
                    clearOnBlur: false,
                    onInputChange: (_, value) => {
                      setTimezoneSearch(value);
                    },
                  }}
                  textFieldProps={{
                    label: t('GENERAL.INSTANCE_TIMEZONE'),
                  }}
                  rules={{
                    validate: validateObjectNullRule(
                      t('GENERAL.MUST_SELECT_TIMEZONE'),
                    ),
                  }}
                  hideCheckbox
                  resetOnBlur
                />
              </Grid>
              <Grid
                item
                xs={12}
              >
                <FormSelect
                  name="defaultCurrencyCode"
                  label={t('GENERAL.CURRENCY')}
                  options={getCurrencyOptions()}
                  formControlProps={{ fullWidth: true }}
                  MenuProps={{
                    PaperProps: {
                      sx: {
                        maxHeight: '250px',
                      },
                    },
                  }}
                />
              </Grid>
              <Grid
                item
                xs={12}
              >
                <CoverPicture
                  title={t('GENERAL.THE_LOGO')}
                  name="logo"
                  value={logo}
                  error={errors.logo}
                  hideHeader
                  validationRule={{
                    validate: validateObjectNullRule(
                      t('GENERAL.MUST_UPLOAD_LOGO'),
                    ),
                  }}
                />
              </Grid>
            </Grid>
          </CardContent>
        </Card>
        <Card>
          <CardHeader
            title={t('GENERAL.LOG_IN_EXTERNAL')}
            subheader={t('GENERAL.LOG_IN_EXTERNAL_DOMAINS')}
          />
          <CardContent>
            <Grid
              item
              xs={12}
            >
              <Stack
                direction="row"
                alignItems="center"
              >
                <FormSwitch
                  disabled={!hasDomains}
                  name="forceSSO"
                  label={t('GENERAL.FORCE_SSO_LOGIN')}
                  formControlLabelProps={{ sx: { mr: 1 } }}
                />
                <Tooltip title={t('GENERAL.FORCE_SSO_LOGIN_TOOLTIP')}>
                  <HelpOutlineIcon fontSize="small" />
                </Tooltip>
              </Stack>
              <Stack sx={{ flexDirection: 'row', alignItems: 'center' }}>
                <FormSwitch
                  name="usersCreationBySSOEnabled"
                  label={t('GENERAL.BLOCK_SSO_LOGIN')}
                  formControlLabelProps={{ sx: { mr: 1 } }}
                />
                <Tooltip title={t('GENERAL.BLOCK_SSO_LOGIN_TOOLTIP')}>
                  <HelpOutlineIcon fontSize="small" />
                </Tooltip>
              </Stack>
              <Stack sx={{ mt: 2 }}>
                <FormAutocomplete
                  name="ssoDomains"
                  textFieldProps={{ label: t('GENERAL.AZURE_SSO_DOMAIN') }}
                  autocompleteProps={{
                    multiple: true,
                    freeSolo: true,
                  }}
                />
              </Stack>
            </Grid>
          </CardContent>
        </Card>
        {instance?.passwordType && (
          <Card>
            <CardHeader
              title={t('GENERAL.SECURITY_PASSWORD_TITLE')}
              subheader={t('GENERAL.SECURITY_PASSWORD_DESCRIPTION')}
            />
            <CardContent sx={{ px: 2, py: 0 }}>
              <Grid
                item
                xs={12}
              >
                <FormRadioCustomGroup
                  name="passwordType"
                  column
                  options={Object.keys(PasswordTypeOptions).map(value => ({
                    label: (
                      <Stack>
                        <Typography variant="subtitle1">
                          {t('GENERAL.STRONG_PASSWORD_TITLE', {
                            context: value,
                          })}
                        </Typography>
                        <Typography variant="body2">
                          {t('GENERAL.STRONG_PASSWORD_DESCRIPTION', {
                            context: value,
                          })}
                        </Typography>
                      </Stack>
                    ),
                    value,
                  }))}
                />
              </Grid>
            </CardContent>
          </Card>
        )}
        <SaveButton sx={{ alignSelf: 'flex-end' }} />
      </Stack>
    </NewThemeProvider>
  );
};

export default GeneralSettings;
