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

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

import HuFormCoverPictureUploader from '@material-hu/components/composed-components/CoverPictureUploader/form';
import { TextInformation } from '@material-hu/components/composed-components/learning';
import HuTitle from '@material-hu/components/design-system/Title';

import defaultSessionCover from 'src/assets/session-cover-picture.svg';
import useFormatDate from 'src/hooks/useFormatDate';
import { LearningCard } from 'src/pages/dashboard/Learning/common/components/LearningCard';
import {
  COVER_PICTURE_SIZE,
  FILE_MAX_SIZE,
} from 'src/pages/dashboard/Learning/Sessions/constants';
import { newSessionFields } from 'src/pages/dashboard/Learning/Sessions/New/form';
import { type NewSessionFormValues } from 'src/pages/dashboard/Learning/Sessions/types';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getTimeZoneInfo } from 'src/utils/timeUtils';

import { useSessionStatus } from '../../../hooks/useSessionStatus';

const SessionCoverPicture = () => {
  const { palette } = useTheme();
  const { blockSessionEdition } = useSessionStatus();
  const { t } = useLokaliseTranslation('learning');
  const { setValue, control } = useFormContext<NewSessionFormValues>();
  const { formatDate } = useFormatDate();

  const handleCoverPictureChange = () =>
    setValue('basic_information.coverPicture.url', undefined);

  const [title, description, localDate, startTime, timeZone, coverPicture] =
    useWatch({
      control,
      name: [
        newSessionFields.basic_information.title(),
        newSessionFields.basic_information.description(),
        newSessionFields.basic_information.localDate(),
        newSessionFields.basic_information.startTime(),
        newSessionFields.basic_information.timeZone(),
        newSessionFields.basic_information.coverPicture(),
      ],
    });

  const hasCoverPicture =
    coverPicture?.cropped || coverPicture?.original || coverPicture?.url;

  const timeZoneInfo = getTimeZoneInfo(timeZone);
  const date = startTime
    ? `${formatDate(startTime, 'P - HH:mm')} ${t('general:hours_short')}`
    : '';
  const dateInfo = `${date} • ${timeZoneInfo}`;
  const dateInfoPlaceholder = `${t('general:date_placeholder')} - ${t('general:time_placeholder')}`;
  const showDateInfo =
    localDate &&
    startTime &&
    !isNaN(localDate.valueOf()) &&
    !isNaN(startTime.valueOf());

  return (
    <LearningCard id="session-basic-information-cover-picture-card">
      <Stack
        sx={{
          gap: 3,
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'flex-start',
        }}
      >
        <Stack sx={{ gap: 1.5 }}>
          <HuTitle title={t('general:preview_view')} />
          <Stack sx={{ flexDirection: 'row', gap: 1 }}>
            <Typography
              fontWeight="fontWeightSemiBold"
              sx={{ color: palette.new.text.neutral.lighter }}
            >
              {`${t('general:date_label')}:`}
            </Typography>
            <Typography
              sx={{
                textTransform: showDateInfo ? undefined : 'uppercase',
                color: palette.new.text.neutral.lighter,
              }}
            >
              {showDateInfo ? dateInfo : dateInfoPlaceholder}
            </Typography>
          </Stack>
          <TextInformation
            title={title || t('session.preview.title')}
            description={description || t('session.preview.description')}
            slotProps={{ seeMoreText: { lines: 8 } }}
            sx={{
              '& span': { color: palette.textColors?.neutralTextLighter },
              '& button': {
                mt: 0.5,
                '&:hover': { backgroundColor: 'transparent' },
              },
            }}
          />
        </Stack>
        <HuFormCoverPictureUploader
          name={newSessionFields.basic_information.coverPicture()}
          uploaderProps={{
            defaultSrc: defaultSessionCover,
            aspectRatio: '1/1',
            recommendedWidth: COVER_PICTURE_SIZE.width,
            recommendedHeight: COVER_PICTURE_SIZE.height,
            maxSize: FILE_MAX_SIZE,
            recommendedSizeTooltip: !hasCoverPicture
              ? {
                  format: ['JPG', 'PNG'],
                  size: `${COVER_PICTURE_SIZE.width}x${COVER_PICTURE_SIZE.height}`,
                }
              : undefined,
            sx: {
              width: '100%',
              minWidth: '242px',
              maxWidth: '242px',
              '& .HuCoverPictureUploader-image': { p: 0 },
            },
            onFileChange: handleCoverPictureChange,
            disabled: blockSessionEdition,
          }}
        />
      </Stack>
    </LearningCard>
  );
};

export default SessionCoverPicture;
