import { type FC, useState } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router';

import { differenceInDays } from 'date-fns';
import { IconUserOff } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import useTheme from '@material-hu/mui/styles/useTheme';
import Typography from '@material-hu/mui/Typography';

import HuDatePeriodSelector from '@material-hu/components/composed-components/DatePeriodSelector';
import { recognizePeriod } from '@material-hu/components/composed-components/DatePeriodSelector/utils';
import Alert from '@material-hu/components/design-system/Alert';
import HuAvatar from '@material-hu/components/design-system/Avatar';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuSkeleton from '@material-hu/components/design-system/Skeleton';
import HuTitle from '@material-hu/components/design-system/Title';

import { useAuth } from 'src/contexts/JWTContext';
import useProfile from 'src/hooks/queryHooks/profile';
import {
  useGetUserDaySummaries,
  useGetUserSites,
} from 'src/hooks/queryHooks/timeTracking';
import useFormatDate from 'src/hooks/useFormatDate';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import {
  Incidence,
  type LocationState,
  UserAccountStatus,
  UserTrackingStatus,
} from 'src/types/timeTracking';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { formatMetrics, getTodayInTimezone } from 'src/utils/timeTracking';
import { getFullName } from 'src/utils/userUtils';

import DropdownFilter from '../components/DropdownFilter';
import ProfilePicWithStatus from '../components/ProfilePicWithStatus';
import SectionHeader from '../components/SectionHeader';
import { COMMON_INCIDENCES_FILTERS } from '../PeriodCollaborators/components/ReportFilters/constants';
import { refetchDaySummaries } from '../queries';
import { timeTrackingRoutes } from '../routes';

import TimesheetTable from './components/TimesheetTable';
import { useTimesheetDeeplink } from './hooks/useTimesheetDeeplink';

const EmployeeTimesheet: FC = () => {
  const { state } = useLocation();
  const { deeplinkRange, deeplinkDate, deeplinkIncidenceType } =
    useTimesheetDeeplink();

  /*
    We are not using the outlet context because we don't want to update it,
    this state will only be persisted on this component
  */
  const [fromDate, setFromDate] = useState(
    deeplinkRange?.from ?? (state as LocationState)?.fromDate ?? new Date(),
  );
  const [toDate, setToDate] = useState(
    deeplinkRange?.to ?? (state as LocationState)?.toDate ?? new Date(),
  );
  const [selectedIncidences, setSelectedIncidences] = useState<Incidence[]>([]);

  const { instance } = useAuth();
  const { t } = useLokaliseTranslation('time_tracker');
  const navigate = useNavigate();
  const { id: userId } = useParams();
  const HuGoThemeProvider = useHuGoTheme();
  const { formatDate } = useFormatDate();
  const { palette } = useTheme();

  const { registers, isFetching: isFetchingSummaries } = useGetUserDaySummaries(
    {
      startDate: formatDate(fromDate, 'yyyy-MM-dd'),
      endDate: formatDate(toDate, 'yyyy-MM-dd'),
      userIds: userId!,
      includeDeactivated: true,
    },
  );

  const { isFetching: isFetchingSites } = useGetUserSites(Number(userId));

  const {
    data: userData,
    isLoading: isLoadingUser,
    isFetching: isFetchingUser,
  } = useProfile(Number(userId), !!userId);

  const handleGoBack = () => {
    refetchDaySummaries();
    navigate(timeTrackingRoutes.collaborators());
  };

  const handleIncidencesChange = (incidences: Incidence[]) => {
    setSelectedIncidences(incidences);
  };

  const userInfo = registers?.[0];

  const isDeactivatedUser =
    userInfo?.userAccountStatus === UserAccountStatus.DEACTIVATED;

  const filteredDaySummaries = userInfo?.daySummaries
    .filter(
      ds =>
        selectedIncidences.length === 0 ||
        ds.incidences.some(i => selectedIncidences.includes(i)),
    )
    .sort((prev, next) =>
      differenceInDays(new Date(next.dateString), new Date(prev.dateString)),
    );

  const metrics = [
    { label: t('WORKED'), value: userInfo?.workedHours },
    { label: t('PROGRAMMED'), value: userInfo?.estimatedHours },
    {
      label: t('BALANCE'),
      value: userInfo?.differenceHours,
      tooltip: t('BALANCE_TOOLTIP'),
    },
    {
      label: t('EXTRAS'),
      value: userInfo?.extraHours || 0,
      tooltip: t('EXTRA_HOURS_TOOLTIP'),
    },
  ];

  const isFetchingUserInfo = isLoadingUser || isFetchingUser;

  return (
    <HuGoThemeProvider>
      <Stack
        sx={{
          backgroundColor: palette.new.background.layout.default,
          minHeight: '100%',
        }}
      >
        <SectionHeader
          onClose={handleGoBack}
          onGoBack={handleGoBack}
          title={t('TRACKING_SHEET')}
          sticky
        />
        <Stack
          sx={{
            alignItems: 'center',
            backgroundColor: palette.new.background.layout.default,
            minHeight: '100%',
            py: 4,
            px: '15%',
          }}
        >
          <Stack sx={{ alignItems: 'center', width: '100%' }}>
            <Stack
              sx={{
                alignItems: 'center',
                flexDirection: 'row',
                justifyContent: 'space-between',
                mb: 1,
                width: '100%',
              }}
            >
              <Typography
                variant="globalM"
                fontWeight="fontWeightSemiBold"
              >
                {t('COLLABORATOR_SUMMARY')}
              </Typography>
              <HuDatePeriodSelector
                fromDate={fromDate}
                handleFromChange={setFromDate}
                toDate={toDate}
                handleToChange={setToDate}
                initialPeriod={recognizePeriod(fromDate, toDate)}
                currentDate={getTodayInTimezone(instance?.timezone!)}
                dateFormatter={(date, format) => formatDate(date, format)}
                showDateReference
              />
            </Stack>
            <HuCardContainer
              sx={{
                width: '100%',
                '.MuiCardContent-root': {
                  display: 'flex',
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  gap: 2,
                },
              }}
            >
              <Stack
                sx={{
                  alignItems: 'center',
                  flexDirection: 'row',
                  justifyContent: 'center',
                  gap: 1,
                }}
              >
                {isFetchingUserInfo && (
                  <Stack sx={{ display: 'flex', flexDirection: 'row', gap: 1 }}>
                    <HuSkeleton
                      variant="circular"
                      width={60}
                      height={60}
                    />
                    <Stack sx={{ gap: 0.5 }}>
                      <HuSkeleton
                        variant="rounded"
                        width={100}
                        height={16}
                      />
                      <HuSkeleton
                        variant="rounded"
                        width={80}
                        height={20}
                      />
                    </Stack>
                  </Stack>
                )}
                {!isFetchingUserInfo && userData && (
                  <>
                    {isDeactivatedUser && (
                      <HuAvatar
                        Icon={IconUserOff}
                        size="large"
                        sx={{
                          color: ({ palette }) =>
                            palette.new.text.neutral.disabled,
                          backgroundColor: ({ palette }) =>
                            palette.new.background.layout.default,
                        }}
                      />
                    )}
                    {!isDeactivatedUser && (
                      <ProfilePicWithStatus
                        status={userInfo?.status || UserTrackingStatus.INACTIVE}
                        userAccountStatus={
                          userInfo?.userAccountStatus ||
                          UserAccountStatus.ACTIVE
                        }
                        userInfo={{
                          id: 1,
                          profilePicture:
                            userData?.data?.profilePicture || null,
                          fullName: getFullName(userData?.data),
                        }}
                        size="large"
                      />
                    )}
                    {isDeactivatedUser && (
                      <Stack sx={{ gap: 0.5 }}>
                        <Stack
                          sx={{
                            flexDirection: 'row',
                            alignItems: 'center',
                            gap: 0.5,
                          }}
                        >
                          <Typography
                            variant="globalS"
                            fontWeight="fontWeightSemiBold"
                          >
                            {getFullName(userData?.data)}
                          </Typography>
                        </Stack>
                        {userData?.data.department && (
                          <Typography
                            variant="globalXS"
                            sx={{
                              color: palette.new.text.neutral.lighter,
                            }}
                          >
                            {userData?.data.department?.name}
                          </Typography>
                        )}
                        <Typography
                          variant="globalXXS"
                          sx={{
                            color: palette.new.text.neutral.lighter,
                          }}
                        >
                          {userData?.data.email ||
                            userData?.data.employeeInternalId}
                        </Typography>
                      </Stack>
                    )}
                    {!isDeactivatedUser && (
                      <HuTitle
                        variant="S"
                        title={getFullName(userData?.data)}
                        description={userData?.data.department?.name}
                        copetin={
                          userData?.data.email ||
                          userData?.data.employeeInternalId
                        }
                      />
                    )}
                  </>
                )}
              </Stack>
              <Stack
                sx={{ alignItems: 'center', flexDirection: 'row', gap: 2 }}
              >
                {metrics.map(metric => (
                  <Stack
                    key={metric.label}
                    sx={{
                      alignItems: 'center',
                      backgroundColor: palette.new.background.layout.default,
                      borderRadius: 1,
                      width: 144,
                      height: 104,
                      justifyContent: 'center',
                      px: 2,
                    }}
                  >
                    <Typography
                      variant="globalM"
                      fontWeight="fontWeightSemiBold"
                    >
                      {metric.label}
                    </Typography>
                    {isFetchingSummaries && (
                      <HuSkeleton
                        variant="rounded"
                        width={64}
                        height={20}
                      />
                    )}
                    {!isFetchingSummaries && (
                      <Typography
                        variant="globalXS"
                        color={({ palette }) =>
                          palette.new.text.neutral.lighter
                        }
                      >
                        {formatMetrics(metric.value)}
                      </Typography>
                    )}
                  </Stack>
                ))}
              </Stack>
            </HuCardContainer>
            {isDeactivatedUser && (
              <Alert
                sx={{ width: '100%', mt: 1 }}
                severity="info"
                loading={isFetchingUserInfo}
                title={t('general:deactivated_collaborator')}
                hasClose
                description={t(
                  'general:deactivated_collaborator_alert_description',
                )}
              />
            )}
            <DropdownFilter
              applyFilters={handleIncidencesChange}
              options={COMMON_INCIDENCES_FILTERS}
              dropdownLabel={t('INCIDENCES')}
              state={selectedIncidences}
              sx={{
                alignSelf: 'flex-end',
                mb: 2,
                mt: 3,
              }}
            />
            <TimesheetTable
              daySummaries={filteredDaySummaries}
              userStatus={userInfo?.status}
              currentDate={userInfo?.currentDate}
              isLoadingSummaries={isFetchingSummaries}
              isLoadingSites={isFetchingSites}
              userAccountStatus={userInfo?.userAccountStatus}
              deeplinkDate={deeplinkDate ?? undefined}
              deeplinkIncidenceType={deeplinkIncidenceType ?? undefined}
            />
          </Stack>
        </Stack>
      </Stack>
    </HuGoThemeProvider>
  );
};

export default EmployeeTimesheet;
