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

import SearchIcon from '@material-hu/icons/material/Search';
import Box from '@material-hu/mui/Box';
import Card from '@material-hu/mui/Card';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';

import { InputType } from 'src/types/forms';
import { useLokaliseTranslation } from 'src/utils/i18n';

import {
  GetFormInputComponent,
  GetFormInputComponentProps,
} from 'src/components/dashboard/form/formDetail/GetFormInputComponent';

import { ID_NUMBER } from './edemsa/constants';
import { EdemsaProfileValue } from './edemsa/types';

export type FormContentProps = GetFormInputComponentProps & {
  name: string;
  description?: string;
  required?: boolean;
  noUserFound?: boolean;
  isLoading?: boolean;
  currentSection?: number;
  // Panalab Total Amount Custom Form
  isPanalabSpecialForm?: boolean;
  isViaticumAmountField?: boolean;
  isViaticumTotalAmountField?: boolean;
  invalidViaticumAmount?: boolean;
  // Edemsa Vlookup Custom Form
  isSpecialFieldEdemsa?: boolean;
  handleSearchEdemsaUserId?: (name) => void;
  edemsaProfileData?: EdemsaProfileValue[];
  isEdemsaSpecialForm?: boolean;
};

const { INTEGER, AUTOCOMPLETE, TEXT, DATE } = InputType;

export const FormContent: FC<FormContentProps> = props => {
  const {
    description,
    required,
    handleSearchEdemsaUserId,
    edemsaProfileData,
    isEdemsaSpecialForm,
    isSpecialFieldEdemsa,
    noUserFound,
    isLoading = false,
    currentSection,
    isViaticumAmountField,
    isViaticumTotalAmountField,
    invalidViaticumAmount,
    ...inputProps
  } = props;
  const { t } = useLokaliseTranslation('forms');

  const { watch, setValue, resetField } = useFormContext();

  const inputType = inputProps.inputType;
  const nameInput = inputProps.name;

  const getValueByName = (
    name: string,
    profileDataArray: EdemsaProfileValue[],
  ) => {
    const result = profileDataArray?.find(elem => elem.name === name);
    return {
      value: result ? result.value : watch(nameInput),
      allowed: result?.allowed,
    };
  };

  const resetFieldValue = () => {
    switch (inputType) {
      case TEXT:
        setValue(nameInput, '');
        break;
      case INTEGER:
        setValue(nameInput, 0);
        break;
      case DATE:
        setValue(nameInput, null);
        break;
      default:
        setValue(nameInput, '');
        break;
    }
  };

  useEffect(() => {
    if (isEdemsaSpecialForm) {
      const answer = getValueByName(description, edemsaProfileData);
      if (answer.value && answer.allowed) {
        setValue(nameInput, answer.value);
      } else {
        if (description !== ID_NUMBER && isSpecialFieldEdemsa) {
          resetField(nameInput);
          resetFieldValue();
        }
      }
    }
  }, [
    description,
    edemsaProfileData,
    isEdemsaSpecialForm,
    isSpecialFieldEdemsa,
  ]);

  const showUneditableMessage =
    inputType === AUTOCOMPLETE ||
    (isEdemsaSpecialForm && isSpecialFieldEdemsa) ||
    isViaticumTotalAmountField;

  return (
    <Card sx={{ width: '100%', py: 2, px: 2, my: 2 }}>
      <Box
        sx={{
          display: 'flex',
          px: 1,
          flexDirection: 'row',
          mb: 2,
          justifyContent: 'space-between',
        }}
      >
        <Typography
          sx={theme => ({
            color: theme.palette.new.text.neutral.brand,
            fontWeight: 'bold',
            fontSize: 16,
          })}
        >
          {description}
          {required && inputType !== AUTOCOMPLETE && (
            <Typography
              component="span"
              sx={{ color: 'red', display: 'inline' }}
            >
              {' '}
              *
            </Typography>
          )}
        </Typography>
        {showUneditableMessage && (
          <Typography
            align="right"
            component="div"
            sx={{ color: 'grey', alignSelf: 'end' }}
          >
            {t('UNEDITABLE_FIELD')}
          </Typography>
        )}
        {inputType === INTEGER && (
          <Typography
            align="right"
            component="div"
            sx={{ color: 'grey', alignSelf: 'end' }}
          >
            {t('ONLY_INTEGER_FIELD')}
          </Typography>
        )}
      </Box>
      {!isEdemsaSpecialForm && (
        <Stack sx={{ gap: 0.5 }}>
          <GetFormInputComponent
            required={required}
            {...inputProps}
            formFilled={isViaticumTotalAmountField || inputProps.formFilled}
          />
          {invalidViaticumAmount && (
            <Typography
              variant="body2"
              color="error"
              sx={{ ml: 1 }}
            >
              {t('VIATICUM_ENOUGH_AMOUNT')}
            </Typography>
          )}
        </Stack>
      )}
      {isEdemsaSpecialForm && (
        <Stack sx={{ gap: 1 }}>
          <Stack sx={{ flexDirection: 'row', gap: 1, alignItems: 'center' }}>
            <GetFormInputComponent
              required={required}
              {...inputProps}
              formFilled={isSpecialFieldEdemsa}
            />
            {inputType === TEXT && description === ID_NUMBER && (
              <Button
                variant="contained"
                color="primary"
                startIcon={
                  isLoading ? <CircularProgress size={16} /> : <SearchIcon />
                }
                sx={{ maxHeight: '40px' }}
                disabled={isLoading}
                onClick={() => handleSearchEdemsaUserId(nameInput)}
              >
                {t('SEARCH')}
              </Button>
            )}
          </Stack>
          {inputType === TEXT && description === ID_NUMBER && noUserFound && (
            <Typography
              variant="body2"
              color="error"
              sx={{ ml: 1 }}
            >
              {t('NO_USER_FOUND')}
            </Typography>
          )}
        </Stack>
      )}
    </Card>
  );
};

export default FormContent;
