import { useFormContext } from 'react-hook-form';
import { useMatch } from 'react-router-dom';

import { formatDuration } from 'date-fns';
import Divider from '@material-hu/mui/Divider';
import Paper from '@material-hu/mui/Paper';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

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

import useAuth from 'src/contexts/JWTContext';
import { STEPPER_HEIGHT } from 'src/pages/dashboard/Learning/Courses/New/constants';
import { newCourseFields } from 'src/pages/dashboard/Learning/Courses/New/forms';
import {
  getNotificationChannelLabelKey,
  getRevisionValues,
} from 'src/pages/dashboard/Learning/Courses/New/utils';
import { coursesRoutes } from 'src/pages/dashboard/Learning/Courses/routes';
import {
  CourseTypes,
  type StepsTypes,
} from 'src/pages/dashboard/Learning/Courses/types';
import { type User } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getCurrentLocale } from 'src/utils/locale';
import { getTimeUnitsFromDuration } from 'src/utils/timeUtils';

import { useSegmentationPreview } from 'src/components/FormInputs/FormSegmentation/utils';
import UsersAvatarList from 'src/components/UsersAvatarList';

import Layout from './Layout';

export type AudienceLabelProps = {
  users: User[] | undefined;
  loading: boolean;
};

const AudienceLabel = ({ users, loading }: AudienceLabelProps) => {
  const { t } = useLokaliseTranslation('learning');

  if (loading) {
    return (
      <Skeleton
        height={50}
        width={100}
      />
    );
  }

  if (users === undefined)
    return <>{t('common.colaborators.all_collaborators')}</>;

  if (!users.length) return <>{t('common.colaborators.no_collaborators')}</>;

  return (
    <Stack
      sx={{
        flexDirection: 'row',
        justifyContent: 'flex-end',
        width: 1,
        mt: 1,
      }}
    >
      <UsersAvatarList users={users} />
    </Stack>
  );
};

export const FinalRevision = () => {
  const { t } = useLokaliseTranslation(['learning', 'notifications_center']);
  const { watch } = useFormContext();
  const { user } = useAuth();
  const theme = useTheme();

  const isEdit = !!useMatch(coursesRoutes.editCourse());

  const values = getRevisionValues(watch() as StepsTypes);
  const { users, loading } = useSegmentationPreview(
    newCourseFields.configuration.segmentation(),
  );

  const locale = getCurrentLocale(user);

  const { hours, minutes } = getTimeUnitsFromDuration(values.duration);

  const fields = [
    {
      title: t('common.title'),
      descriptions: [
        {
          id: 'title',
          component: values.title,
        },
      ],
    },
    {
      title: t('common.duration_title'),
      descriptions: [
        {
          id: 'duration',
          component:
            (hours && hours > 0) || (minutes && minutes > 0)
              ? formatDuration({ hours, minutes }, { locale })
              : '-',
        },
      ],
    },
    {
      title: t('general:category'),
      descriptions: [
        {
          id: 'categories',
          component: values.category?.label || '-',
        },
      ],
    },
    {
      title: t('common.content'),
      descriptions: [
        {
          id: 'content-module-count',
          component: t('course.lesson.module_count', {
            count: values.moduleCount,
          }),
        },
        {
          id: 'content-tasks-count',
          component: t('course.lesson.lesson_count', {
            count: values.taskCount,
          }),
        },
      ],
    },
    {
      title: t('general:type'),
      descriptions: [
        {
          id: 'type',
          component:
            values.type === CourseTypes.REQUIRED
              ? t('course.required')
              : t('course.optional'),
        },
      ],
    },
    {
      title: t('common.sequentiality'),
      descriptions: [
        {
          id: 'sequentiality',
          component: values.sequentiality
            ? t('common.sequentialy_description')
            : t('common.no_sequential'),
        },
      ],
    },
    {
      title: t('course.instructor.label'),
      descriptions: [
        {
          id: 'instructor',
          component: values.instructor || t('course.instructor.unassigned'),
        },
      ],
    },
    {
      title: t('common.auto_progress_update'),
      descriptions: [
        {
          id: 'refreshFinishedCourseUsers',
          component: values.refreshFinishedCourseUsers
            ? t('general:activated')
            : t('general:inactivated'),
        },
      ],
    },
    {
      title: t('common.deadline'),
      descriptions: [
        {
          id: 'deadline',
          component: values.deadline
            ? t('common.days_from_assignment', { count: values.deadlineDays })
            : t('common.no_deadline'),
        },
      ],
    },
    {
      title: t('common.audience'),
      descriptions: [
        {
          id: 'audience',
          component: (
            <AudienceLabel
              users={users}
              loading={loading}
            />
          ),
        },
      ],
    },
    {
      title: t('common.notify_colaborators'),
      descriptions: [
        {
          id: 'notifications',
          component: t(
            getNotificationChannelLabelKey(
              values.sendPushNotification,
              values.sendEmailNotification,
            ),
          ),
        },
      ],
    },
  ];

  return (
    <Stack
      sx={{
        height: `calc(100% - ${STEPPER_HEIGHT})`,
        overflow: 'auto',
      }}
    >
      <Layout.Container>
        <Layout.Title>
          {t(isEdit ? 'course.review_and_update' : 'course.review_and_publish')}
        </Layout.Title>
        <Stack
          component={Paper}
          elevation={24}
          sx={{
            py: 4,
            px: 10,
            justifyContent: 'center',
            alignItems: 'center',
          }}
        >
          {fields.map(field => (
            <Stack
              key={field.title}
              sx={{ width: '100%' }}
            >
              <Stack
                sx={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  gap: 1,
                  py: 1.5,
                }}
              >
                <Typography variant="subtitle2">{field.title}</Typography>
                <Stack>
                  {field.descriptions.map(description => (
                    <Typography
                      key={description.id}
                      variant="body2"
                      color={theme.palette.text.secondary}
                    >
                      {description.component}
                    </Typography>
                  ))}
                </Stack>
              </Stack>
              <Divider />
            </Stack>
          ))}
        </Stack>
      </Layout.Container>
    </Stack>
  );
};

export default FinalRevision;
