import { FC, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import EventIcon from '@material-hu/icons/material/Event';
import ScheduleIcon from '@material-hu/icons/material/Schedule';
import Box from '@material-hu/mui/Box';
import Card from '@material-hu/mui/Card';
import CardActions from '@material-hu/mui/CardActions';
import CardContent from '@material-hu/mui/CardContent';
import CardHeader from '@material-hu/mui/CardHeader';
import CardMedia from '@material-hu/mui/CardMedia';
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 { getUserData } from 'src/services/nemakEvents';
import { Event } from 'src/types/nemakEvents';
import { formatDate } from 'src/utils/recognitions';

import CredentialsDialog from './CredentialsDialog';
import EventCardItem from './EventCardItem';
import EventMenu from './EventMenu';
import { useTranslation } from './i18n';
import { eventsRoutes } from './routes';

const eventCardItemStyle = {
  fontSize: '13px',
  whiteSpace: 'nowrap',
  textOverflow: 'ellipsis',
  overflow: 'hidden',
};

export type EventCardProps = Event;

export const EventCard: FC<EventCardProps> = props => {
  const {
    Id,
    Name,
    CreatedBy,
    UrlImageEvent,
    EventDate,
    RegistrationStart,
    IsRegisteringEnabled,
    EventDescription,
  } = props;

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

  const { t } = useTranslation();
  const navigate = useNavigate();
  const showGeneralError = useGeneralError();

  const { enqueueSnackbar } = useSnackbar();

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

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

  return (
    <Card sx={{ maxWidth: 360, height: '430px', position: 'relative' }}>
      <CardHeader
        sx={{ py: 1, position: 'absolute', right: '0px' }}
        action={<EventMenu id={Id} />}
      />
      <CardMedia
        image={UrlImageEvent ? UrlImageEvent : imageDefault}
        sx={{ objectFit: 'cover', height: '160px' }}
      />
      <CardContent sx={{ height: '224px' }}>
        <Typography
          sx={{
            mb: 2,
            height: '60px',
            overflow: 'hidden',
            display: '-webkit-box',
            WebkitLineClamp: 2,
            WebkitBoxOrient: 'vertical',
            textOverflow: 'ellipsis',
          }}
          variant="h5"
          component="div"
        >
          {Name}
        </Typography>
        <EventCardItem
          Icon={EventIcon}
          i18nKey="EVENT_ORGANIZED_BY"
          transValues={{ author: CreatedBy }}
          sx={eventCardItemStyle}
        />
        <EventCardItem
          Icon={ScheduleIcon}
          i18nKey="EVENT_DATE_CARD"
          transValues={{ eventDate: formatDate(EventDate.toString()) }}
          sx={eventCardItemStyle}
        />
        <EventCardItem
          Icon={ScheduleIcon}
          i18nKey="REGISTRATION_START_DATE"
          transValues={{
            registrationDate: formatDate(RegistrationStart.toString()),
          }}
          sx={eventCardItemStyle}
        />
        <Box
          sx={{
            mb: 1,
            height: '40px',
            lineHeight: '20px',
            overflow: 'hidden',
            display: '-webkit-box',
            WebkitLineClamp: 2,
            WebkitBoxOrient: 'vertical',
            textOverflow: 'ellipsis',
          }}
        >
          <Typography
            sx={{
              fontSize: '13px',
              color: '#6c757d',
            }}
          >
            {EventDescription}
          </Typography>
        </Box>
      </CardContent>
      <CardActions sx={{ pt: 0, px: 2 }}>
        {IsRegisteringEnabled !== 0 && (
          <Button
            onClick={() => setOpenDialog(true)}
            sx={{ borderRadius: '4px' }}
            size="medium"
            variant="outlined"
            fullWidth
          >
            {t('REGISTER')}
          </Button>
        )}
      </CardActions>
      {openDialog && (
        <CredentialsDialog
          open={openDialog}
          onClose={() => setOpenDialog(false)}
          onClick={fetchUserData}
          isLoading={isLoading}
        />
      )}
    </Card>
  );
};

export default EventCard;
