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

import LogoutIcon from '@material-hu/icons/material/Logout';
import Alert from '@material-hu/mui/Alert';
import Box from '@material-hu/mui/Box';
import Card from '@material-hu/mui/Card';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Container from '@material-hu/mui/Container';
import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

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

import { modulesOptions } from 'src/constants/recognitions';
import { useMobileLayout } from 'src/hooks/useMobileLayout';
import { useMobileToken } from 'src/hooks/useMobileToken';
import CardModules from 'src/pages/dashboard/recognitions/components/CardModules';
import CardUserInfo from 'src/pages/dashboard/recognitions/components/CardUserInfo';
import FAQsDialog from 'src/pages/dashboard/recognitions/components/FAQsDialog';
import ModuleHeader from 'src/pages/dashboard/recognitions/components/ModuleHeader';
import { useTranslation } from 'src/pages/dashboard/recognitions/i18n';
import LoginRecognitions from 'src/pages/dashboard/recognitions/LoginRecognitions';
import { recognitionsKeys } from 'src/pages/dashboard/recognitions/queries';
import { getEmployeeData, getEmployeeSones } from 'src/services/recognitions';
import { getUserId, userLogout } from 'src/utils/recognitions';

const Recognitions: FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const userId = getUserId();

  const [openFAQsDialog, setOpenFAQsDialog] = useState(false);
  const [openCredentialsDialog, setOpenCredentialsDialog] = useState(true);
  const [isLogged, setIsLogged] = useState(!!localStorage.getItem('userId'));

  useMobileToken();
  useMobileLayout();

  const { data, isLoading } = useQuery(
    [recognitionsKeys.detail(userId)],
    () => getEmployeeData(userId),
    {
      enabled: !!userId,
      onSuccess: successData => {
        localStorage.setItem(
          'userData',
          JSON.stringify(successData.data.EmployeeBasics),
        );
      },
    },
  );

  const {
    data: sonesData,
    isLoading: isLoadingSones,
    refetch,
  } = useQuery(
    [recognitionsKeys.sones(userId)],
    () => getEmployeeSones(userId),
    {
      enabled: !!userId,
    },
  );

  const handleRefetchSones = () => refetch();

  const sones = sonesData?.data?.DataSones[0];

  const user = data?.data?.EmployeeBasics;

  const handleLogout = () => {
    userLogout();
    setIsLogged(false);
  };

  const handleLoggedUser = () => setIsLogged(true);

  if (!isLogged && openCredentialsDialog) {
    return (
      <LoginRecognitions
        open={openCredentialsDialog}
        onClose={() => setOpenCredentialsDialog(false)}
        onLoggedUser={handleLoggedUser}
      />
    );
  }

  if (!isLogged && !openCredentialsDialog) {
    return (
      <Box
        sx={{
          backgroundColor: 'background.default',
          minHeight: '100%',
          pt: 3,
          pb: 3,
        }}
      >
        <Container maxWidth="sm">
          <Box sx={{ mt: '60px' }}>
            <Stack
              sx={{
                width: '100%',
                p: 2,
                pt: 0,
              }}
            >
              <Alert
                sx={{ borderRadius: '6px' }}
                severity="info"
              >
                {t('LOGIN_REQUIRED')}
              </Alert>
            </Stack>
            <Box
              sx={{
                mt: 2,
                display: 'flex',
                width: '100%',
                justifyContent: 'flex-end',
              }}
            >
              <Button
                variant="contained"
                onClick={() => setOpenCredentialsDialog(true)}
              >
                {t('LOGIN')}
              </Button>
            </Box>
          </Box>
        </Container>
      </Box>
    );
  }

  return (
    <>
      <Helmet>
        <title>{t('RECOGNITIONS')}</title>
      </Helmet>
      <Box
        sx={{
          backgroundColor: 'background.default',
          minHeight: '100%',
          pt: 3,
          pb: 3,
        }}
      >
        <Container maxWidth="md">
          <Box sx={{ mt: 3, mb: 3 }}>
            <Box
              sx={{
                py: 3,
                px: '10%',
                width: '100%',
                backgroundColor: '#ffffff',
                borderRadius: '10px',
              }}
            >
              <ModuleHeader title={t('RECOGNITIONS')} />
              <Divider sx={{ borderBottomWidth: 'medium', mt: 2, mb: 3 }} />
              {(isLoading || isLoadingSones) && (
                <Box sx={{ textAlign: 'center' }}>
                  <CircularProgress />
                </Box>
              )}
              {!isLoading && !isLoadingSones && userId && (
                <Box>
                  <Card sx={{ width: '100%' }}>
                    <Box
                      sx={{
                        p: 2,
                        pb: 0,
                        display: 'flex',
                        justifyContent: 'space-between',
                      }}
                    >
                      <Typography
                        color="textPrimary"
                        variant="h5"
                        sx={{ fontSize: '18px !important' }}
                      >
                        {t('USER_INFO')}
                      </Typography>
                      <Button
                        sx={{ display: 'flex', alignItems: ' center' }}
                        onClick={handleLogout}
                      >
                        <LogoutIcon
                          fontSize="small"
                          sx={{ mr: 0.6 }}
                        />
                        {t('LOGOUT')}
                      </Button>
                    </Box>
                    <CardUserInfo
                      user={user}
                      sones={sones}
                      onRefetch={handleRefetchSones}
                    />
                  </Card>
                  <Box
                    sx={{
                      mt: 4,
                      display: 'flex',
                      justifyContent: 'center',
                      flexWrap: 'wrap',
                    }}
                  >
                    {modulesOptions.map(module => (
                      <CardModules
                        key={module.title}
                        title={t(module.title)}
                        Icon={module.icon}
                        onClick={
                          !module.hasNavigation
                            ? () => setOpenFAQsDialog(true)
                            : () => navigate(module.navigate())
                        }
                      />
                    ))}
                    {openFAQsDialog && (
                      <FAQsDialog
                        open={openFAQsDialog}
                        onClose={() => setOpenFAQsDialog(false)}
                      />
                    )}
                  </Box>
                </Box>
              )}
            </Box>
          </Box>
        </Container>
      </Box>
    </>
  );
};

export default Recognitions;
