import { useEffect, useMemo, useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';

import { useDrawer } from '@material-hu/hooks/useDrawer';
import { IconDownload } from '@material-hu/icons/tabler';
import {
  Card,
  CircularProgress,
  Grid,
  IconButton,
  Stack,
  Typography,
} from '@material-hu/mui';

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 HuTable from '@material-hu/components/design-system/Table';
import HuTableBody from '@material-hu/components/design-system/Table/components/TableBody';
import HuTableCell from '@material-hu/components/design-system/Table/components/TableCell';
import HuTableContainer from '@material-hu/components/design-system/Table/components/TableContainer';
import HuTableHead from '@material-hu/components/design-system/Table/components/TableHead';
import HuTableRow from '@material-hu/components/design-system/Table/components/TableRow';
import HuTitle from '@material-hu/components/design-system/Title';

import { useAuth } from 'src/contexts/JWTContext';
import useFeatureFlag from 'src/hooks/useFeatureFlag';
import useRequiredParams from 'src/hooks/useRequiredParams';
import { FeatureFlags } from 'src/types/featureFlags';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';

import HuTextInfoTooltip from 'src/components/HuTextInfoTooltip';
import TableSortingHeader from 'src/components/table/TableSortingHeader';

import {
  useGroupMostActiveMembers,
  useGroupMostActiveMembersReport,
  useGroupStatsSummary,
} from '../../hooks/useGroupStats';
import GroupMembersReportDrawer from '../Reports/GroupMembersReportDrawer';

import MetricBox from './MetricBox';

export const FeaturedMembers = () => {
  const { id } = useRequiredParams(['id']);
  const { t } = useTranslation(['post']);
  const { user } = useAuth();
  const featuredMembersReportDrawerForm = useForm({
    defaultValues: {
      email: user?.email,
    },
  });
  const userEmail = featuredMembersReportDrawerForm.watch('email');
  const [order, setOrder] = useState<'ASC' | 'DESC' | 'DESC_NULLS_LAST'>('ASC');
  const [orderBy, setOrderBy] = useState<string>('');
  const [timeSinceServerMidnight, setTimeSinceServerMidnight] =
    useState<number>(0);

  const isDownloadGroupMembersReportEnabled = useFeatureFlag(
    FeatureFlags.DOWNLOAD_GROUP_MEMBERS_REPORT,
  );

  // Calculate hours since UTC midnight
  useEffect(() => {
    const calculateTimeSinceServerMidnight = () => {
      const now = new Date();
      // Get the UTC time without any timezone adjustments
      const utcNow = new Date(
        Date.UTC(
          now.getUTCFullYear(),
          now.getUTCMonth(),
          now.getUTCDate(),
          now.getUTCHours(),
          now.getUTCMinutes(),
          now.getUTCSeconds(),
        ),
      );

      // Create UTC midnight today (00:00:00 UTC)
      const utcMidnight = new Date(
        Date.UTC(
          now.getUTCFullYear(),
          now.getUTCMonth(),
          now.getUTCDate(),
          0,
          0,
          0,
        ),
      );

      const hoursSinceMidnight = Math.ceil(
        (utcNow.getTime() - utcMidnight.getTime()) / (1000 * 60 * 60),
      );

      setTimeSinceServerMidnight(hoursSinceMidnight);
    };

    calculateTimeSinceServerMidnight();
  }, []);

  // React Query hooks
  const { data: statsSummary, isLoading: isLoadingStats } =
    useGroupStatsSummary(id);

  const { data: activeMembersData, isLoading: isLoadingMembers } =
    useGroupMostActiveMembers(id);

  const { isLoading: isGeneratingReport, refetch: generateMembersReport } =
    useGroupMostActiveMembersReport(id, userEmail || '');

  const {
    drawer: featuredMembersReportDrawer,
    showDrawer: showFeaturedMembersReportDrawer,
    closeDrawer: closeFeaturedMembersReportDrawer,
  } = useDrawer(GroupMembersReportDrawer, {
    title: t('group:group_members_report_drawer_title'),
    primaryButtonProps: {
      children: t('group:send_report'),
      sx: { flex: 1 },
      onClick: () => {
        submitFeaturedMembersReport();
        closeFeaturedMembersReportDrawer();
      },
      disabled: !featuredMembersReportDrawerForm.formState.isValid,
    },
    secondaryButtonProps: {
      children: t('general:cancel'),
      sx: { flex: 1 },
      onClick: () => closeFeaturedMembersReportDrawer(),
    },
  });

  const calculatePercentageChange = (current: number, previous: number) => {
    if (previous === 0) return current > 0 ? 100 : 0;
    return Math.round(((current - previous) / previous) * 100);
  };

  const submitFeaturedMembersReport = () => {
    if (!id || !userEmail) return;
    generateMembersReport();
  };

  const handleOrderChange = (property: string) => {
    const isCurrentASC = orderBy === property && order === 'ASC';
    const newOrder = isCurrentASC ? 'DESC_NULLS_LAST' : 'ASC';
    setOrderBy(property);
    setOrder(newOrder);
  };

  const isLoading = isLoadingStats || isLoadingMembers;
  const activeMembers = activeMembersData?.data.items || [];

  const sortedMembers = useMemo(() => {
    if (!orderBy || !activeMembers.length) return activeMembers;

    return [...activeMembers].sort((a, b) => {
      if (orderBy === 'author') {
        const nameA = getFullName(a.user).toLowerCase();
        const nameB = getFullName(b.user).toLowerCase();
        return order === 'ASC'
          ? nameA.localeCompare(nameB)
          : nameB.localeCompare(nameA);
      } else if (orderBy === 'posts') {
        return order === 'ASC'
          ? a.postsCount - b.postsCount
          : b.postsCount - a.postsCount;
      } else if (orderBy === 'comments') {
        return order === 'ASC'
          ? a.commentsCount - b.commentsCount
          : b.commentsCount - a.commentsCount;
      } else if (orderBy === 'activity') {
        return order === 'ASC'
          ? a.activityScore - b.activityScore
          : b.activityScore - a.activityScore;
      }
      return 0;
    });
  }, [activeMembers, orderBy, order]);

  const renderTableBody = () => {
    if (isLoading) {
      return (
        <>
          {[...Array(5)].map((_, index) => (
            <HuTableRow key={`skeleton-${index}`}>
              <HuTableCell>
                <Stack sx={{ flexDirection: 'row', alignItems: 'center' }}>
                  <HuSkeleton
                    variant="circular"
                    sx={{ mr: 2, width: 36, height: 36 }}
                  />
                  <Stack>
                    <HuSkeleton
                      variant="text"
                      width={150}
                      height={20}
                    />
                    <HuSkeleton
                      variant="text"
                      width={100}
                      height={16}
                    />
                  </Stack>
                </Stack>
              </HuTableCell>
              <HuTableCell align="center">
                <HuSkeleton
                  variant="text"
                  width={30}
                  height={20}
                />
              </HuTableCell>
              <HuTableCell align="center">
                <HuSkeleton
                  variant="text"
                  width={30}
                  height={20}
                />
              </HuTableCell>
              <HuTableCell align="center">
                <HuSkeleton
                  variant="text"
                  width={30}
                  height={20}
                />
              </HuTableCell>
            </HuTableRow>
          ))}
        </>
      );
    }

    if (activeMembers.length === 0) {
      return (
        <HuTableRow>
          <HuTableCell
            colSpan={4}
            align="center"
          >
            {t('group:no_active_members')}
          </HuTableCell>
        </HuTableRow>
      );
    }

    return sortedMembers.map(member => (
      <HuTableRow key={member.user.id}>
        <HuTableCell>
          <Stack sx={{ flexDirection: 'row', alignItems: 'center' }}>
            <HuAvatar
              sx={{ mr: 2, width: 36, height: 36 }}
              src={member.user.profilePicture}
              text={`${member.user.firstName[0]}${member.user.lastName[0]}`}
            />
            <Stack>
              <Typography variant="body1">
                {getFullName(member.user)}
              </Typography>
              <Typography
                variant="body2"
                color="text.secondary"
              >
                {member.user.email}
              </Typography>
            </Stack>
          </Stack>
        </HuTableCell>
        <HuTableCell align="center">{member.postsCount}</HuTableCell>
        <HuTableCell align="center">{member.commentsCount}</HuTableCell>
        <HuTableCell align="center">{member.activityScore}</HuTableCell>
      </HuTableRow>
    ));
  };

  return (
    <Stack sx={{ py: 5, width: '100%' }}>
      <FormProvider {...featuredMembersReportDrawerForm}>
        {featuredMembersReportDrawer}
      </FormProvider>
      <HuCardContainer
        sx={{ mb: 4, p: 3 }}
        fullWidth
      >
        <Stack spacing={2}>
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
            }}
          >
            <HuTitle
              title={
                <Typography
                  variant="globalM"
                  fontWeight="fontWeightSemiBold"
                >
                  {t('group:groups_general_information')}
                </Typography>
              }
              variant="M"
              description={
                <Stack
                  sx={{
                    flexDirection: 'row',
                    alignItems: 'center',
                  }}
                >
                  <Typography
                    variant="globalS"
                    color="text.secondary"
                  >
                    {t('group:groups_last_update', {
                      count: timeSinceServerMidnight,
                      timeSinceServerMidnight,
                    })}
                  </Typography>
                  <HuTextInfoTooltip
                    tooltipText={t('group:groups_last_update_tooltip')}
                  />
                </Stack>
              }
            />
          </Stack>
          <Grid container>
            <Grid
              item
              xs={4}
              pr={2}
            >
              <MetricBox
                label={t('group:publications')}
                value={statsSummary?.data.currentPostsCount || 0}
                percentageChange={
                  statsSummary
                    ? calculatePercentageChange(
                        statsSummary.data.currentPostsCount,
                        statsSummary.data.previousPostsCount,
                      )
                    : 0
                }
                tooltipText={t('group:publications_tooltip')}
                comparedToDaysText={t('group:publications_compared_to_days')}
              />
            </Grid>

            <Grid
              item
              xs={4}
              pr={2}
            >
              <MetricBox
                label={t('comments')}
                value={statsSummary?.data.currentCommentsCount || 0}
                percentageChange={
                  statsSummary
                    ? calculatePercentageChange(
                        statsSummary.data.currentCommentsCount,
                        statsSummary.data.previousCommentsCount,
                      )
                    : 0
                }
                tooltipText={t('group:comments_tooltip')}
                comparedToDaysText={t('group:comments_compared_to_days')}
              />
            </Grid>

            <Grid
              item
              xs={4}
              pr={2}
            >
              <MetricBox
                label={t('group:activity')}
                value={statsSummary?.data.currentActivityScore || 0}
                percentageChange={
                  statsSummary
                    ? calculatePercentageChange(
                        statsSummary.data.currentActivityScore,
                        statsSummary.data.previousActivityScore,
                      )
                    : 0
                }
                tooltipText={t('group:activity_tooltip')}
                comparedToDaysText={t('group:activity_compared_to_days')}
              />
            </Grid>
          </Grid>
        </Stack>
      </HuCardContainer>

      {/* Featured Members Card */}
      <HuCardContainer
        sx={{ p: 3 }}
        fullWidth
      >
        <Stack spacing={2}>
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
            }}
          >
            <HuTitle
              title={
                <Stack sx={{ flexDirection: 'row', alignItems: 'center' }}>
                  <Typography
                    variant="globalM"
                    fontWeight="fontWeightSemiBold"
                  >
                    {t('group:featured_members')}
                  </Typography>
                  <HuTextInfoTooltip
                    tooltipText={t('group:featured_members_tooltip')}
                  />
                </Stack>
              }
              variant="M"
              description={
                <Stack
                  sx={{
                    flexDirection: 'row',
                    alignItems: 'center',
                  }}
                >
                  <Typography
                    variant="globalS"
                    color="text.secondary"
                  >
                    {t('group:groups_last_update', {
                      count: timeSinceServerMidnight,
                      timeSinceServerMidnight,
                    })}
                  </Typography>
                  <HuTextInfoTooltip
                    tooltipText={t('group:groups_last_update_tooltip')}
                  />
                </Stack>
              }
            />
            {isDownloadGroupMembersReportEnabled && (
              <IconButton
                sx={{
                  border: theme =>
                    `1px solid ${theme.palette.new.border.neutral.brand}`,
                }}
                onClick={showFeaturedMembersReportDrawer}
                disabled={isGeneratingReport}
              >
                {isGeneratingReport ? (
                  <CircularProgress size={20} />
                ) : (
                  <IconDownload />
                )}
              </IconButton>
            )}
          </Stack>

          <HuTableContainer sx={{ maxWidth: '100%', overflow: 'auto' }}>
            <HuTable sx={{ tableLayout: 'auto', minWidth: '650px' }}>
              <HuTableHead>
                <HuTableRow
                  headerRow
                  sx={{
                    textTransform: 'uppercase',
                    color: 'text.secondary',
                    fontWeight: 500,
                  }}
                >
                  <TableSortingHeader
                    id="author"
                    order={order}
                    orderBy={orderBy}
                    text={t('group:groups_author')}
                    onChangeOrder={handleOrderChange}
                    sx={{ width: 'auto' }}
                  />
                  <TableSortingHeader
                    id="posts"
                    order={order}
                    orderBy={orderBy}
                    text={t('group:publications_created')}
                    onChangeOrder={handleOrderChange}
                    sx={{ width: 'auto', minWidth: '160px' }}
                    align="center"
                  />
                  <TableSortingHeader
                    id="comments"
                    order={order}
                    orderBy={orderBy}
                    text={t('group:comments_made')}
                    onChangeOrder={handleOrderChange}
                    sx={{ width: 'auto', minWidth: '160px' }}
                    align="center"
                  />
                  <TableSortingHeader
                    id="activity"
                    order={order}
                    orderBy={orderBy}
                    text={t('group:activity_score')}
                    onChangeOrder={handleOrderChange}
                    tooltipText={t('group:activity_score_tooltip')}
                    sx={{ width: 'auto', minWidth: '160px' }}
                    align="center"
                  />
                </HuTableRow>
              </HuTableHead>
              <HuTableBody>{renderTableBody()}</HuTableBody>
            </HuTable>
          </HuTableContainer>
        </Stack>
      </HuCardContainer>
    </Stack>
  );
};
