import { FC, useEffect, useMemo } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';
import { useTranslation } from 'react-i18next';

import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import FormRadioGroup from '@material-hu/components/composed-components/RadioGroup/form';
import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import FormSwitcher from '@material-hu/components/design-system/Switcher/form';
import usePermissions from 'src/hooks/usePermissions';
import {
  GroupPrivacyPolicies,
  GroupPublicationPolicies,
} from 'src/types/groups';

import { insertIf } from 'src/utils/arrays';
import { UserPermissions } from 'src/utils/permissions';
import {
  FormCoverPicture,
  FormImageMenu,
  FormSelect,
} from 'src/components/FormInputs';

import ConfigurationSection, {
  type ConfigurationSectionProps,
} from '../../components/ConfigurationSection';
import MembersCanLeaveConfig from '../../components/MembersCanLeaveConfig';
import {
  GroupAprovalPolicyKeys,
  GroupPrivacyPoliciesKeys,
  GroupPublicationPoliciesKeys,
  getPrivacyIcon,
} from '../../constants';
import { GROUP_DETAIL_PAGE_BANNER_DIMENSIONS } from '../../utils';

const ManageConfiguration: FC = () => {
  const { t } = useTranslation(['group']);
  const { setValue } = useFormContext();
  const [isMultiCompany, publicationPolicy] = useWatch({
    name: ['isMultiCompany', 'publicationPolicy'],
  });
  const { hasAll: canCreateMultiCompanyGroups } = usePermissions([
    UserPermissions.CREATE_MULTICOMPANY_GROUPS,
    UserPermissions.VIEW_MULTICOMPANY_GROUPS,
  ]);

  // Automatically set privacy to SECRET when multi-company is turned on
  useEffect(() => {
    if (isMultiCompany) {
      setValue('privacyPolicy', GroupPrivacyPolicies.SECRET);
    }
  }, [isMultiCompany, setValue]);

  const privacyOptions = useMemo(() => {
    return GroupPrivacyPoliciesKeys.map(type => {
      const disabled = isMultiCompany;
      return {
        value: type,
        label: t(`group:group_option_${type.toLowerCase()}`),
        icon: getPrivacyIcon(type as GroupPrivacyPolicies, disabled),
        disabled,
      };
    });
  }, [isMultiCompany, t]);

  const publicationOptions = GroupPublicationPoliciesKeys.map(value => ({
    value,
    label: t(`group:post_${value.toLowerCase()}`),
    helperText: t(`group:post_${value.toLowerCase()}_info`),
  }));

  const approvalPolicyOptions = GroupAprovalPolicyKeys.map(value => ({
    value,
    label: t(`group:approval_policy_${value.toLowerCase()}`),
    helperText: t(`group:approval_policy_${value.toLowerCase()}_info`),
  }));

  const sections: ConfigurationSectionProps[] = useMemo(
    () => [
      {
        titleKey: 'group:group_name',
        gap: 1.5,
        renderContent: () => (
          <FormInputClassic
            name="title"
            inputProps={{
              hasCounter: false,
              maxLength: 50,
              placeholder: t('group:group_name_placeholder'),
            }}
            rules={{ required: true }}
          />
        ),
      },
      {
        titleKey: 'group:icon_web',
        gap: 1,
        renderContent: () => <FormImageMenu name="icon" />,
      },
      {
        titleKey: 'group:banner_image_web',
        gap: 2,
        renderContent: () => (
          <FormCoverPicture
            name="banner"
            recommendedWidth={GROUP_DETAIL_PAGE_BANNER_DIMENSIONS.WIDTH}
            recommendedHeight={GROUP_DETAIL_PAGE_BANNER_DIMENSIONS.HEIGHT}
          />
        ),
      },
      {
        titleKey: 'group:group_description_web',
        gap: 0.5,
        renderContent: () => (
          <FormInputClassic
            name="description"
            inputProps={{
              multiline: true,
              maxLength: 250,
              placeholder: t('group:group_description_placeholder_web'),
              sx: { minHeight: '120px' },
            }}
          />
        ),
      },
      ...insertIf(canCreateMultiCompanyGroups, {
        renderContent: () => (
          <FormSwitcher
            name="isMultiCompany"
            switcherProps={{
              title: t('group:multi_company_create_group'),
              description: t('group:multi_company_create_group_description'),

              titleProps: {
                sx: {
                  color: theme => theme.palette.new.text.neutral.default,
                },
              },
              descriptionProps: {
                sx: {
                  color: theme => theme.palette.new.text.neutral.lighter,
                },
              },
            }}
          />
        ),
      }),
      {
        titleKey: 'group:privacy',
        gap: 1,
        renderContent: () => (
          <FormSelect
            variant="outlined"
            name="privacyPolicy"
            label={t('group:privacy_type_web')}
            options={privacyOptions}
            disabled={isMultiCompany}
            selectProps={{
              inputProps: {
                sx: {
                  display: 'flex',
                  flexDirection: 'row',
                  alignItems: 'center',
                  gap: 1,
                  '& .MuiListItemIcon-root': {
                    minWidth: 0,
                  },
                },
              },
            }}
            MenuProps={{
              PaperProps: {
                style: {
                  maxWidth: '650px',
                },
              },
            }}
          />
        ),
      },
      {
        titleKey: 'group:post_policy',
        gap: 1,
        renderContent: () => (
          <FormRadioGroup
            name="publicationPolicy"
            options={publicationOptions}
          />
        ),
      },
      ...(publicationPolicy === GroupPublicationPolicies.ONLY_ADMINS
        ? []
        : [
            {
              titleKey: 'group:approval_policy_setting_web',
              gap: 2,
              renderContent: () => (
                <FormRadioGroup
                  name="approvalPolicy"
                  options={approvalPolicyOptions}
                />
              ),
            },
          ]),
      {
        titleKey: 'group:members_can_leave_title',
        gap: 1.5,
        renderContent: () => <MembersCanLeaveConfig />,
      },
    ],
    [canCreateMultiCompanyGroups, isMultiCompany, t, publicationPolicy],
  );

  return (
    <Stack sx={{ gap: 2 }}>
      <Stack>
        <Typography
          variant="globalL"
          fontWeight="fontWeightSemiBold"
        >
          {t('group:configuration')}
        </Typography>
        <Typography
          variant="globalS"
          color={theme => theme.palette.new.text.neutral.lighter}
        >
          {t('group:configure_info')}
        </Typography>
      </Stack>
      {sections.map(section => (
        <ConfigurationSection
          key={section.titleKey}
          {...section}
        />
      ))}
    </Stack>
  );
};

export default ManageConfiguration;
