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

import { IconPaperclip } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

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

import { QuestionType } from '../../../types';
import { QuestionTypeIcons } from '../../constants';
import { useFormCreation } from '../../contexts/FormCreation';
import { newServiceItemFields } from '../../forms';

import IndexBadge from './IndexBadge';
import QuestionCardForm from './QuestionCardForm';
import QuestionTypeTitle from './QuestionTypeTitle';

type Props = {
  index: number;
  showValidations?: boolean;
};

const QuestionCard: FC<Props> = ({ index, showValidations = false }) => {
  const { t } = useLokaliseTranslation('service_management');
  const { selected, select } = useFormCreation();
  const { watch } = useFormContext();
  const theme = useTheme();

  const isSelected = selected.question === index;

  const questionName = newServiceItemFields.form.sections.questions.detail(
    selected.section,
    index,
  );

  const questionAttachmentsName =
    newServiceItemFields.form.sections.questions.attachments.all(
      selected.section,
      index,
    );

  const question = watch(questionName);
  const attachments = watch(questionAttachmentsName);

  const showAttachments = attachments && attachments.length > 0;

  const Icon =
    QuestionTypeIcons[
      (question?.type as keyof typeof QuestionTypeIcons) ?? QuestionType.TEXT
    ] || null;

  if (isSelected) {
    return (
      <QuestionCardForm
        index={index}
        showValidations={showValidations}
      />
    );
  }

  if (!question) {
    return null;
  }

  return (
    <Stack
      sx={{
        p: 2,
        backgroundColor: ({ palette }) =>
          palette.new.background.layout.tertiary,
        borderRadius: ({ shape }) => shape.borderRadiusL,
        position: 'relative',
        gap: 1,
        cursor: 'pointer',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
      }}
      onClick={() => select({ section: selected.section, question: index })}
    >
      <Stack sx={{ gap: 1 }}>
        <IndexBadge value={index + 1} />
        <QuestionTypeTitle
          typeLabel={t(`${question.type}`)}
          Icon={Icon}
        />
        <Typography
          variant="globalM"
          fontWeight="fontWeightSemiBold"
        >
          {question.title}
        </Typography>
      </Stack>
      {showAttachments && (
        <IconPaperclip
          size={16}
          color={theme.palette.new.text.neutral.default}
        />
      )}
    </Stack>
  );
};

export default QuestionCard;
