import { FC, useState } from 'react';
import { Helmet } from 'react-helmet-async';
import { useQuery } from 'react-query';
import { useParams } from 'react-router';
import { useNavigate } from 'react-router-dom';

import EventIcon from '@material-hu/icons/material/Event';
import PersonIcon from '@material-hu/icons/material/Person';
import PollIcon from '@material-hu/icons/material/Poll';
import ScheduleIcon from '@material-hu/icons/material/Schedule';
import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Container from '@material-hu/mui/Container';
import Link from '@material-hu/mui/Link';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import useSnackbar from '@material-hu/components/design-system/Snackbar';

import imageDefault from 'src/assets/images/eventDefaultImage.webp';
import useGeneralError from 'src/hooks/useGeneralError';
import { useMobileLayout } from 'src/hooks/useMobileLayout';
import { getEventData, getUserData } from 'src/services/nemakEvents';
import { formatTitle } from 'src/utils/helmetUtils';
import { formatDate } from 'src/utils/recognitions';

import CredentialsDialog from './components/CredentialsDialog';
import EventCardItem from './components/EventCardItem';
import { useTranslation } from './components/i18n';
import { eventsKeys } from './components/queries';
import { eventsRoutes } from './components/routes';

const Events: FC = () => {
  const { t } = useTranslation();

  useMobileLayout();

  const { eventId } = useParams();
  const { enqueueSnackbar } = useSnackbar();
  const navigate = useNavigate();
  const showGeneralError = useGeneralError();

  const [openDialog, setOpenDialog] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const { data, isLoading: isLoadingData } = useQuery(
    eventsKeys.detail(eventId),
    () => getEventData(eventId),
    {
      select: response => response.data,
    },
  );

  const fetchUserData = async id => {
    setIsLoading(true);

    try {
      const { data: userData } = await getUserData(id);
      if (userData?.Logger) {
        enqueueSnackbar({ title: t('NOT_USER_FOUND'), variant: 'error' });
      } else if (userData?.EmployeeBasics) {
        navigate(
          eventsRoutes.form(data.Id, userData.EmployeeBasics.PersonIdExternal),
        );
      }
    } catch (err) {
      showGeneralError(err, t('ERROR_GET_USER_INFO'));
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <>
      <Helmet>
        <title>{formatTitle(t('EVENTS'))}</title>
      </Helmet>
      <Box
        sx={{
          backgroundColor: 'background.default',
          minHeight: '100%',
          pt: 2,
          pb: 8,
        }}
      >
        <Container maxWidth="sm">
          <Box
            sx={{
              width: '100%',
              backgroundColor: '#ffffff',
              borderRadius: '16px',
              p: 3,
            }}
          >
            {isLoadingData && (
              <Box
                sx={{
                  display: 'flex',
                  width: '100%',
                  justifyContent: 'center',
                  mt: 2,
                }}
              >
                <CircularProgress />
              </Box>
            )}
            {!isLoadingData && (
              <>
                <Box
                  component="img"
                  src={
                    data.EventImage
                      ? `data:image/png;base64,${data.EventImage}`
                      : imageDefault
                  }
                  alt=""
                  sx={{
                    borderRadius: '16px',
                    display: 'block',
                    marginBottom: '30px',
                    objectFit: 'cover',
                    width: '100%',
                    height: '100%',
                  }}
                />
                <Box sx={{ mt: 2 }}>
                  <Typography variant="h4">{data.Name}</Typography>
                </Box>
                <EventCardItem
                  Icon={EventIcon}
                  i18nKey="EVENT_ORGANIZED_BY_DETAIL"
                  transValues={{ author: data.CreatedBy }}
                />
                <EventCardItem
                  Icon={ScheduleIcon}
                  i18nKey="EVENT_DATE_DETAIL"
                  transValues={{ date: formatDate(data.EventDate.toString()) }}
                />
                <EventCardItem
                  Icon={ScheduleIcon}
                  i18nKey="EVENT_REGISTRATION_DATE_DETAIL"
                  transValues={{
                    date: formatDate(data.RegistrationStart.toString()),
                  }}
                />
                <Box sx={{ mt: 2, display: 'flex', alignItems: 'center' }}>
                  <PersonIcon
                    fontSize="small"
                    sx={{ mr: 0.5 }}
                  />
                  <Typography>{data.Availability.toString()}</Typography>
                </Box>
                {data.UrlSurvey && (
                  <Box sx={{ mt: 2, display: 'flex', alignItems: 'center' }}>
                    <PollIcon
                      fontSize="small"
                      sx={{ mr: 0.5 }}
                    />
                    <Typography>
                      <Link
                        href={data.UrlSurvey}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        {data.UrlSurvey}
                      </Link>
                    </Typography>
                  </Box>
                )}
                {data.EventDescription && (
                  <Typography
                    sx={{
                      mt: 2,
                      display: 'flex',
                      alignItems: 'center',
                      fontSize: '14px',
                    }}
                    color="secondary"
                  >
                    {data.EventDescription}
                  </Typography>
                )}
                {data.IsRegisteringEnabled !== 0 && (
                  <Button
                    onClick={() => setOpenDialog(true)}
                    sx={{
                      mt: 3,
                      borderRadius: '4px',
                    }}
                    size="medium"
                    variant="outlined"
                    fullWidth
                  >
                    {t('REGISTER')}
                  </Button>
                )}
              </>
            )}
            {openDialog && (
              <CredentialsDialog
                open={openDialog}
                onClose={() => setOpenDialog(false)}
                onClick={fetchUserData}
                isLoading={isLoading}
              />
            )}
          </Box>
        </Container>
      </Box>
    </>
  );
};

export default Events;
