import { type FC, useEffect, useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useParams } from 'react-router-dom';

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

import Avatar from '@material-hu/components/design-system/Avatar';
import Button from '@material-hu/components/design-system/Buttons/Button';
import FormCheckbox from '@material-hu/components/design-system/Checkbox/Checkbox/form';
import FormRating from '@material-hu/components/design-system/Rating/form';
import Title from '@material-hu/components/design-system/Title';

import { logEvent } from 'src/config/amplitude';
import { EventName } from 'src/types/amplitude';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FormTextField from 'src/components/FormInputs/FormTextField';

const ISSUE_CATEGORIES = [
  {
    key: 'audio',
    labelKey: 'rating_issue_category_audio',
    options: [
      { key: 'audio_mine', labelKey: 'rating_issue_audio_mine' },
      { key: 'audio_others', labelKey: 'rating_issue_audio_others' },
      { key: 'audio_echo', labelKey: 'rating_issue_audio_echo' },
      { key: 'audio_cut', labelKey: 'rating_issue_audio_cut' },
    ],
  },
  {
    key: 'video',
    labelKey: 'rating_issue_category_video',
    options: [
      { key: 'video_camera_mine', labelKey: 'rating_issue_video_camera_mine' },
      {
        key: 'video_camera_others',
        labelKey: 'rating_issue_video_camera_others',
      },
      { key: 'video_quality', labelKey: 'rating_issue_video_quality' },
    ],
  },
] as const;

type IssueKey = (typeof ISSUE_CATEGORIES)[number]['options'][number]['key'];

type IssueOption = { key: IssueKey; labelKey: string };

type CallRatingFormValues = {
  rating: number | null;
  comments: string;
} & Record<IssueKey, boolean>;

const ISSUE_OPTIONS: IssueOption[] = ISSUE_CATEGORIES.flatMap(c =>
  c.options.map(o => ({ key: o.key, labelKey: o.labelKey })),
);

const CallRatingSection: FC = () => {
  const { providerCallId } = useParams();
  const { t } = useLokaliseTranslation('calls');
  const [submitted, setSubmitted] = useState(false);

  const form = useForm<CallRatingFormValues>();

  const { handleSubmit, watch, setValue } = form;

  const rating = watch('rating');

  useEffect(() => {
    if (Number(rating) !== 5) return;
    setValue('comments', '');
    for (const o of ISSUE_OPTIONS) {
      setValue(o.key, false);
    }
  }, [rating, setValue]);

  const onSubmit = (data: CallRatingFormValues) => {
    const selectedIssues = ISSUE_OPTIONS.filter(o => data[o.key]).map(
      o => o.key,
    );

    logEvent(EventName.CALLS_CSAT_ANSWERED, {
      providerCallId,
      rating: data.rating,
      selectedIssues,
      comments: data.comments,
    });
    setSubmitted(true);
  };

  if (submitted) {
    return (
      <Stack sx={{ alignItems: 'center', gap: 2.25, mt: 2.25 }}>
        <Avatar
          Icon={IconCheck}
          color="success"
          size="large"
          sx={{
            width: '64px',
            height: '64px',
          }}
        />
        <Title
          centered
          variant="M"
          title={t('rating_thank_title')}
          description={t('rating_thank_description')}
        />
      </Stack>
    );
  }

  const showIssues = rating !== null && rating < 5;

  return (
    <FormProvider {...form}>
      <Stack sx={{ alignItems: 'center', gap: 2, width: '100%' }}>
        <Typography
          variant="globalS"
          fontWeight="fontWeightSemiBold"
          sx={{ textAlign: 'center' }}
        >
          {t('rating_question')}
        </Typography>
        <FormRating
          name="rating"
          inputProps={{ size: 'large' }}
        />
        {showIssues && (
          <Stack sx={{ width: '100%', gap: 2 }}>
            <Typography
              variant="globalS"
              fontWeight="fontWeightSemiBold"
              sx={{ textAlign: 'center' }}
            >
              {t('rating_issue_question')}
            </Typography>
            {ISSUE_CATEGORIES.map(category => (
              <Stack
                key={category.key}
                sx={{ gap: 1.25 }}
              >
                <Typography
                  variant="globalS"
                  fontWeight="fontWeightSemiBold"
                >
                  {t(category.labelKey)}
                </Typography>
                {category.options.map(option => (
                  <FormCheckbox
                    key={option.key}
                    name={option.key}
                    checkBoxProps={{ label: t(option.labelKey) }}
                  />
                ))}
              </Stack>
            ))}
            <Stack sx={{ gap: 1.25 }}>
              <Typography
                variant="globalS"
                fontWeight="fontWeightSemiBold"
              >
                {t('rating_issue_category_others')}
              </Typography>
              <FormTextField
                name="comments"
                multiline
                rows={4}
                placeholder={t('rating_issue_others_placeholder')}
              />
            </Stack>
          </Stack>
        )}
        <Button
          size="small"
          variant="contained"
          disabled={!rating}
          onClick={handleSubmit(onSubmit)}
        >
          {t('send')}
        </Button>
      </Stack>
    </FormProvider>
  );
};

export default CallRatingSection;
