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

import {
  IconFlag3,
  IconTargetArrow,
  IconChevronRight,
  IconEdit,
} from '@material-hu/icons/tabler';
import { isNil } from 'lodash-es';
import CloseIcon from '@material-hu/icons/material/Close';
import Grid from '@material-hu/mui/Grid';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { colorPalette } from '@material-hu/theme/hugo/colors';

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

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { getGoalCycle } from 'src/services/goalsService';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import CenteredCircularProgress from 'src/components/CircularProgress';

import { goalsKeys } from '../../../queries';
import { goalRoutes } from '../../../routes';
import { isFinishedCycle } from '../../../utils';

import ExploreStep from './ExploreStep';
import ParticipationStep from './ParticipationStep';

const Cycle = () => {
  const { t } = useLokaliseTranslation('goals');
  const navigate = useNavigate();
  const HuGoThemeProvider = useHuGoTheme();
  const { id } = useParams();
  const [searchParams] = useSearchParams();
  const cycleId = parseInt(id ?? '0');
  const [activeStep, setActiveStep] = useState(0);

  const { data: cycle, isLoading: cycleLoading } = useQuery(
    goalsKeys.cycle(cycleId, false),
    () => getGoalCycle(cycleId),
    {
      select: r => r.data,
      enabled: !!cycleId,
    },
  );

  useEffect(() => {
    const stepParam = searchParams.get('initialStep');
    if (stepParam !== null) {
      const step = parseInt(stepParam, 10);
      if (!isNaN(step) && step >= 0) {
        setActiveStep(step);
        return;
      }
    }
  }, [cycle?.status, searchParams]);

  const steps = [
    {
      label: t('participation'),
      Component: ParticipationStep,
      completed: isFinishedCycle(cycle?.status),
    },
    {
      label: t('general:explore'),
      Component: ExploreStep,
      completed: isFinishedCycle(cycle?.status),
    },
  ];
  const currentStep = steps[activeStep];

  if (cycleLoading || isNil(cycle)) {
    return (
      <CenteredCircularProgress
        centered
        sx={{ mt: 6 }}
      />
    );
  }

  return (
    <HuGoThemeProvider>
      <Stack
        sx={{
          height: '100vh',
          backgroundColor: colorPalette.hugoBackground.neutralBgTerciary,
        }}
      >
        <Helmet>
          <title>{formatTitle(t('follow_up'))}</title>
        </Helmet>
        <Stack
          sx={{
            position: 'sticky',
            top: 0,
            zIndex: 1,
            backgroundColor: colorPalette.hugoBackground.neutralBgTerciary,
          }}
        >
          <Grid
            container
            spacing={3}
            sx={{ alignItems: 'center', px: 3, py: 2 }}
          >
            <Grid
              item
              xs
            >
              <Stack
                sx={{
                  gap: 2,
                  flexDirection: 'row',
                  alignItems: 'center',
                }}
              >
                <CloseIcon onClick={() => navigate(goalRoutes.cyclesBase())} />

                <Typography
                  variant="globalL"
                  fontWeight="fontWeightSemiBold"
                >
                  {cycle.name}
                </Typography>
              </Stack>
            </Grid>
            <Grid item>
              <Button
                variant="secondary"
                startIcon={<IconEdit size={16} />}
                onClick={() =>
                  navigate(goalRoutes.newCycle(cycleId), {
                    state: { backLink: goalRoutes.cycle(cycleId) },
                  })
                }
              >
                {t('general:edit')} {t('general:cycle')}
              </Button>
            </Grid>
          </Grid>
        </Stack>

        <Stack
          sx={{
            flexDirection: 'row',
            gap: 3,
            flex: 1,
            overflow: 'hidden',
          }}
        >
          <Stack
            sx={{
              gap: 2,
              pl: 3,
              pt: 3,
              position: 'sticky',
              top: 0,
              height: 'fit-content',
              alignSelf: 'flex-start',
            }}
          >
            {steps.map((step, index) => {
              const isParticipation = step.label === t('participation');
              const isExplore = step.label === t('general:explore');

              return (
                <SelectionCard
                  key={index}
                  onClick={() => setActiveStep(index)}
                  checked={activeStep === index}
                >
                  <Stack
                    sx={{
                      width: '100%',
                      flexDirection: 'row',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                    }}
                  >
                    <Stack
                      sx={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        gap: 1,
                      }}
                    >
                      <Stack
                        sx={{
                          backgroundColor:
                            colorPalette.hugoBackground.primaryBgLighter,
                          borderRadius: '50%',
                          p: 1,
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                        }}
                      >
                        {isParticipation && (
                          <IconFlag3
                            color={colorPalette.textColors.primaryText}
                          />
                        )}
                        {isExplore && (
                          <IconTargetArrow
                            color={colorPalette.textColors.primaryText}
                          />
                        )}
                      </Stack>
                      <Typography
                        variant="globalS"
                        fontWeight="fontWeightSemiBold"
                      >
                        {step.label}
                      </Typography>
                    </Stack>
                    <IconChevronRight />
                  </Stack>
                </SelectionCard>
              );
            })}
          </Stack>
          <Stack
            sx={{
              flex: 1,
              px: 3,
              pt: 3,
              backgroundColor: colorPalette.hugoBackground.neutralBg,
              overflow: 'auto',
            }}
          >
            <currentStep.Component cycle={cycle} />
          </Stack>
        </Stack>
      </Stack>
    </HuGoThemeProvider>
  );
};

export default Cycle;
