import { useEffect, useMemo } from 'react';
import { Helmet } from 'react-helmet-async';
import { FormProvider, useForm, useWatch } from 'react-hook-form';
import { useMutation, useQueryClient } from 'react-query';
import { useLocation, useNavigate, useParams } from 'react-router-dom';

import { useDebounce } from '@material-hu/hooks/useDebounce';
import { IconPlus, IconTargetArrow } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuAvatar from '@material-hu/components/design-system/Avatar';
import Button from '@material-hu/components/design-system/Buttons/Button';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import HuSearch from '@material-hu/components/design-system/Inputs/Search';
import HuList from '@material-hu/components/design-system/List';
import HuListItemSkeleton from '@material-hu/components/design-system/List/components/ListItemSkeleton';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';
import HuTitle from '@material-hu/components/design-system/Title';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { CycleProvider } from 'src/pages/dashboard/goals/CycleContext';
import CycleSelector from 'src/pages/dashboard/goals/components/CycleSelector';
import GoalCard from 'src/pages/dashboard/goals/components/GoalCard';
import { GoalFeaturesConfigProvider } from 'src/pages/dashboard/goals/components/GoalFeaturesConfigContext';
import { GoalCardVariant } from 'src/pages/dashboard/goals/constants';
import { useGoalFeaturesConfig } from 'src/pages/dashboard/goals/hooks/useGoalFeaturesConfig';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';

import GoalWeightsDrawer from '../components/GoalWeightsDrawer';
import {
  GOALS_GOAL_CARD_LIST_ITEM_SKELETON_INDIVIDUAL_SX,
  GOALS_LIST_STACK_SX,
  TEAM_GOALS_LAYOUT_MAX_WIDTH,
} from '../constants';
import { goalsKeys } from '../queries';
import { goalsRoutes } from '../routes';
import { deleteGoal } from '../services';
import { type GoalTeamUser } from '../types';
import { transformIndividualGoalsToGoals } from '../utils';

import TeamGoalsHeader from './components/TeamGoalsHeader';
import TeamGoalsSummaryCards from './components/TeamGoalsSummaryCards';
import { useTeamGoalsPageQuery } from './hooks/useTeamGoalsPageQuery';

type LocationState = {
  goalCycleId: number;
  goalUser: GoalTeamUser;
};

type TeamGoalsFormValues = {
  goalCycleId: number;
  ownerId: number;
  query: string;
};

const TeamGoals = () => {
  const { t } = useLokaliseTranslation('goals');
  const HuGoThemeProvider = useHuGoTheme();
  const { enqueueSnackbar } = useHuSnackbar();
  const { isApprovalFlowEnabled, isBossCanEditPublishedObjectives } =
    useGoalFeaturesConfig();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { state } = useLocation();
  const { goalCycleId: initialGoalCycleId, goalUser } =
    (state as LocationState) || {};
  const { id } = useParams();

  useEffect(() => {
    if (!initialGoalCycleId) {
      navigate(goalsRoutes.goals(), { replace: true });
    }
  }, [initialGoalCycleId, navigate]);

  const form = useForm<TeamGoalsFormValues>({
    defaultValues: {
      goalCycleId: initialGoalCycleId,
      ownerId: Number(id) || 0,
      query: '',
    },
    mode: 'onChange',
  });

  const goalCycleId = useWatch({ control: form.control, name: 'goalCycleId' });
  const query = useWatch({ control: form.control, name: 'query' });
  const debouncedQuery = useDebounce(query);

  const handleClose = () =>
    navigate(goalsRoutes.goals(), {
      state: { goalCycleId },
    });

  const {
    isLoading,
    goalWeights,
    weightedProgress: rawWeightedProgress,
  } = useTeamGoalsPageQuery({
    goalCycleId: goalCycleId ?? 0,
    userId: Number(id) || 0,
  });

  const goals = useMemo(
    () => (goalWeights ? transformIndividualGoalsToGoals(goalWeights) : []),
    [goalWeights],
  );
  const weightedProgress = rawWeightedProgress ?? 0;

  const filteredGoals = useMemo(
    () =>
      goals.filter(g =>
        g.title.toLowerCase().includes(debouncedQuery.toLowerCase()),
      ),
    [goals, debouncedQuery],
  );

  const deleteMutation = useMutation(
    ({ id: goalId }: { id: number }) => deleteGoal(goalId),
    {
      onSuccess: () => {
        queryClient.invalidateQueries(
          goalsKeys.weights(goalCycleId ?? 0, Number(id)),
        );
        enqueueSnackbar({
          title: t('delete.success'),
          variant: 'success',
        });
      },
    },
  );

  return (
    <HuGoThemeProvider>
      <CycleProvider>
        <FormProvider {...form}>
          <Helmet>
            <title>{formatTitle(t('individual_goals'))}</title>
          </Helmet>
          <Stack
            id="review-layout"
            sx={{
              backgroundColor: theme =>
                theme.palette.new?.background?.layout?.default,
              height: '100%',
              overflowY: 'scroll',
            }}
          >
            <TeamGoalsHeader
              userName={getFullName(goalUser?.ownerUser)}
              onClose={handleClose}
            />
            <Stack
              sx={{
                p: 3,
                width: TEAM_GOALS_LAYOUT_MAX_WIDTH,
                mx: 'auto',
                gap: 3,
              }}
            >
              <Stack
                sx={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  width: '100%',
                }}
              >
                <Typography
                  variant="globalL"
                  fontWeight="fontWeightSemiBold"
                >
                  {t('individual_goals')}
                </Typography>
                <Button
                  variant="contained"
                  startIcon={<IconPlus size={16} />}
                  onClick={() =>
                    navigate(goalsRoutes.create(), {
                      state: {
                        goalUser,
                        goalCycleId,
                        backLink: goalsRoutes.individual(id ?? ''),
                      },
                    })
                  }
                >
                  {t('list.create')}
                </Button>
              </Stack>
              <TeamGoalsSummaryCards
                goalUser={goalUser}
                weightedProgress={weightedProgress}
                goalsCount={goals.length}
                loading={isLoading}
              />
              <Stack
                sx={{
                  gap: 2,
                  width: '100%',
                  alignContent: 'center',
                  flexDirection: 'row',
                }}
              >
                <HuSearch
                  label={t('general:searching')}
                  placeholder={t('my_goals.search_placeholder')}
                  value={query}
                  onChange={value => form.setValue('query', value)}
                />
                <CycleSelector />
              </Stack>
              <Stack sx={{ gap: 2 }}>
                <Stack
                  flexDirection="row"
                  alignItems="center"
                  justifyContent="space-between"
                  sx={{ px: 1 }}
                >
                  <Typography
                    variant="globalM"
                    fontWeight="fontWeightSemiBold"
                  >
                    {t('general:detail')}
                  </Typography>
                  <GoalWeightsDrawer
                    goals={goals}
                    goalCycleId={goalCycleId ?? null}
                    ownerId={Number(id) || 0}
                    query={debouncedQuery}
                    fromMyGoalsPage={false}
                  />
                </Stack>
                <Stack>
                  <HuList sx={GOALS_LIST_STACK_SX}>
                    {isLoading && (
                      <>
                        <CardContainer fullWidth>
                          <HuListItemSkeleton
                            sx={
                              GOALS_GOAL_CARD_LIST_ITEM_SKELETON_INDIVIDUAL_SX
                            }
                          />
                        </CardContainer>
                        <CardContainer fullWidth>
                          <HuListItemSkeleton
                            sx={
                              GOALS_GOAL_CARD_LIST_ITEM_SKELETON_INDIVIDUAL_SX
                            }
                          />
                        </CardContainer>
                        <CardContainer fullWidth>
                          <HuListItemSkeleton
                            sx={
                              GOALS_GOAL_CARD_LIST_ITEM_SKELETON_INDIVIDUAL_SX
                            }
                          />
                        </CardContainer>
                      </>
                    )}
                    {!isLoading && (
                      <GoalFeaturesConfigProvider
                        isApprovalFlowEnabled={isApprovalFlowEnabled}
                        isBossCanEditPublishedObjectives={
                          isBossCanEditPublishedObjectives
                        }
                      >
                        {filteredGoals?.map(goal => (
                          <GoalCard
                            key={goal.id}
                            goal={goal}
                            deleteGoal={deleteMutation}
                            variant={GoalCardVariant.INDIVIDUAL}
                            weight={goal.weight}
                            customBackLink={goalsRoutes.individual(id ?? '')}
                            goalUser={goalUser}
                            goalCycleId={goalCycleId}
                            isBoss
                          />
                        ))}
                      </GoalFeaturesConfigProvider>
                    )}
                    {!isLoading && !filteredGoals?.length && (
                      <CardContainer fullWidth>
                        <Stack
                          sx={{
                            justifyContent: 'center',
                            alignItems: 'center',
                            gap: 1,
                            py: 2,
                          }}
                        >
                          <HuAvatar
                            size="large"
                            color="primary"
                            Icon={IconTargetArrow}
                          />
                          {goals.length === 0 ? (
                            <HuTitle
                              variant="M"
                              centered
                              title={t('my_team.empty_individual_goals.title')}
                              description={t(
                                'my_team.empty_individual_goals.description',
                              )}
                            />
                          ) : (
                            <HuTitle
                              variant="M"
                              centered
                              title={t('list.empty_search')}
                              description={t('list.empty_search_description')}
                            />
                          )}
                        </Stack>
                      </CardContainer>
                    )}
                  </HuList>
                </Stack>
              </Stack>
            </Stack>
          </Stack>
        </FormProvider>
      </CycleProvider>
    </HuGoThemeProvider>
  );
};

export default TeamGoals;
