import { type ComponentProps, useMemo } from 'react';

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

import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuAutocomplete from '@material-hu/components/design-system/Inputs/Autocomplete';
import InputClassic from '@material-hu/components/design-system/Inputs/Classic';
import FormInputPhone from '@material-hu/components/design-system/Inputs/Phone/form';

import { useLokaliseTranslation } from 'src/utils/i18n';

import {
  LOAN_REASON_OTHER,
  MICROLOANS_ADVANCE_REASON_OPTIONS,
} from '../../constants';
import { trackLoanAdvanceReasonChanged } from '../../track';
import { ADVANCE_REASON_LIST_ICON } from '../advanceReasonIcons';

const LOAN_REASON_COMMENT_MAX_LENGTH = 100;
const LOAN_REASON_COMMENT_LABEL_ID = 'loan-reason-comment-label';

export type ConfirmStepContactCardProps = {
  loanReason: string;
  onLoanReasonChange: (value: string) => void;
  loanReasonComment: string;
  onLoanReasonCommentChange: (value: string) => void;
};

type FormInputPhoneInputProps = NonNullable<
  ComponentProps<typeof FormInputPhone>['inputProps']
>;

export const ConfirmStepContactCard = ({
  loanReason,
  onLoanReasonChange,
  loanReasonComment,
  onLoanReasonCommentChange,
}: ConfirmStepContactCardProps) => {
  const { t } = useLokaliseTranslation('loans');

  const reasonOptions = useMemo(
    () =>
      MICROLOANS_ADVANCE_REASON_OPTIONS.map(opt => ({
        label: t(opt.labelKey),
        value: opt.id,
      })),
    [t],
  );

  const selectedReasonOption = useMemo(
    () => reasonOptions.find(option => option.value === loanReason) ?? null,
    [reasonOptions, loanReason],
  );

  return (
    <HuCardContainer
      fullWidth
      padding={0}
      sx={{ minWidth: 0 }}
    >
      <Stack sx={{ p: 2.5, gap: 2.5 }}>
        <Typography
          variant="globalM"
          sx={{
            fontWeight: 'fontWeightBold',
            color: theme => theme.palette.new.text.neutral.default,
          }}
        >
          {t('confirm.complete_data_title')}
        </Typography>
        <Stack
          sx={{
            display: 'grid',
            gridTemplateColumns: '1fr',
            gap: 2.5,
            width: '100%',
          }}
        >
          <Stack sx={{ gap: 0.75, minWidth: 0 }}>
            <Typography
              variant="globalS"
              sx={{
                fontWeight: 'fontWeightSemiBold',
                color: theme => theme.palette.new.text.neutral.default,
              }}
            >
              {t('confirm.phone_label_full')}
            </Typography>
            <Stack
              sx={{
                '& .tabler-icon-chevron-down': {
                  display: 'none',
                },
                '& .MuiFormControl-root>div .MuiTelInput-IconButton.MuiButtonBase-root':
                  {
                    padding: 0,
                    minWidth: '70px',
                  },
              }}
            >
              <FormInputPhone
                name="phoneNumber"
                validatePhoneNumber
                inputProps={
                  {
                    showErrors: true,
                    defaultCountry: 'MX',
                    placeholder: '55 1234 5678',
                    fullWidth: true,
                    size: 'small',
                    variant: 'outlined',
                    onlyCountries: ['MX'],
                    disableDropdown: true,
                    forceCallingCode: true,
                    disableFormatting: true,
                    sx: {
                      '& .MuiFormHelperText-root.Mui-error': {
                        typography: 'globalXXS',
                        lineHeight: '25px',
                      },
                    },
                    inputProps: {
                      'aria-label': String(t('confirm.aria_phone')),
                    },
                  } as FormInputPhoneInputProps
                }
              />
            </Stack>
          </Stack>
          <Stack sx={{ gap: 0.75, minWidth: 0 }}>
            <Typography
              variant="globalS"
              sx={{
                fontWeight: 'fontWeightSemiBold',
                color: theme => theme.palette.new.text.neutral.default,
              }}
            >
              {t('confirm.reason_label_full')}
            </Typography>
            <HuAutocomplete
              value={selectedReasonOption}
              onChange={nextValue => {
                if (nextValue) {
                  trackLoanAdvanceReasonChanged();
                  onLoanReasonChange(nextValue.value);
                } else {
                  onLoanReasonChange('');
                }
              }}
              options={reasonOptions}
              placeholder={String(t('confirm.reason_placeholder_select'))}
              isServerFiltered={false}
              renderOption={(optionProps, option) => {
                const { key, ...restProps } = optionProps;
                const OptionIcon = ADVANCE_REASON_LIST_ICON[option.value];
                return (
                  <li
                    key={key}
                    {...restProps}
                  >
                    <Stack
                      sx={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        gap: 1.5,
                      }}
                    >
                      {OptionIcon && (
                        <OptionIcon
                          size={18}
                          stroke={2}
                        />
                      )}
                      <Typography variant="globalS">{option.label}</Typography>
                    </Stack>
                  </li>
                );
              }}
            />
          </Stack>
        </Stack>
        <Divider
          sx={{
            borderColor: theme => theme.palette.new.border.neutral.default,
          }}
        />
        <Typography
          variant="globalXS"
          sx={{ color: theme => theme.palette.new.text.neutral.lighter }}
        >
          {t('confirm.complete_data_subtitle')}
        </Typography>
        {loanReason === LOAN_REASON_OTHER && (
          <Stack sx={{ gap: 0.75, minWidth: 0 }}>
            <Typography
              id={LOAN_REASON_COMMENT_LABEL_ID}
              variant="globalS"
              sx={{
                fontWeight: 'fontWeightSemiBold',
                color: theme => theme.palette.new.text.neutral.default,
              }}
            >
              {t('confirm.reason_comment_label')}
            </Typography>
            <InputClassic
              multiline
              minRows={1}
              placeholder={t('confirm.reason_comment_placeholder')}
              value={loanReasonComment}
              onChange={onLoanReasonCommentChange}
              maxLength={LOAN_REASON_COMMENT_MAX_LENGTH}
              aria-labelledby={LOAN_REASON_COMMENT_LABEL_ID}
            />
          </Stack>
        )}
      </Stack>
    </HuCardContainer>
  );
};
