import React, {useEffect, useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconBallFootball, IconTargetArrow} from '@tabler/icons-react-native';
import {Avatar, Dialog, Pill, Typography} from '@components';
import {RankingEntry} from '@modules/prodev2/interfaces';
import {prodeKeys} from '@modules/prodev2/constants';
import {getUserStats} from '@modules/prodev2/services';
import {useQuery} from '@shared/hooks/queries-v5/useQuery';
import {ICON_SIZES, useTheme} from '@shared/theme';

import {StatItem} from './components/StatItem';
import {UserStatsDialogSkeleton} from './components/Skeleton';
import {styles} from './styles';

export interface Props {
  isOpen: boolean;
  onClose: () => void;
  competitionId: number;
  entry: Nullable<RankingEntry>;
}

export function UserStatsDialog({
  isOpen,
  onClose,
  competitionId,
  entry,
}: Props) {
  const {t} = useTranslation();
  const {theme} = useTheme();

  const [displayEntry, setDisplayEntry] = useState(entry);
  useEffect(() => {
    if (entry) setDisplayEntry(entry);
  }, [entry]);

  const {data: stats, isFetching} = useQuery(
    prodeKeys.userStats(competitionId, displayEntry?.userId ?? 0),
    () => getUserStats(competitionId, displayEntry?.userId ?? 0),
    {enabled: isOpen && !!competitionId && !!displayEntry?.userId},
  );

  const isLoading = isFetching && !stats;

  const position = stats?.ranking.position ?? displayEntry?.position ?? 0;
  const totalPoints =
    stats?.ranking.totalPoints ?? displayEntry?.totalPoints ?? 0;

  return (
    <Dialog
      isVisible={isOpen}
      onClose={onClose}
      title={t('general.detail')}
      withCloseButton
      wrapperType="view">
      <View style={styles.body}>
        {!displayEntry ? null : isLoading ? (
          <UserStatsDialogSkeleton />
        ) : (
          <View style={styles.bodyGap}>
            <View style={styles.headerRow}>
              <Avatar
                url={displayEntry.userAvatarUrl}
                name={displayEntry.userName ?? undefined}
                size="md"
              />
              <Typography
                variant="xs"
                weight="semiBold"
                style={styles.headerName}
                numberOfLines={1}>
                {displayEntry.userName ?? ''}
              </Typography>
              <Pill
                size="sm"
                variant="highlight"
                text={t('sportsPool.ranking_page.position', {position})}
              />
              <View style={styles.headerPoints}>
                <Typography variant="xxs" color={theme.text.neutral.lighter}>
                  {t('sportsPool.ranking_page.points_header')}
                </Typography>
                <Typography
                  variant="l"
                  weight="semiBold"
                  color={theme.text.neutral.brand}>
                  {String(totalPoints)}
                </Typography>
              </View>
            </View>

            <View
              style={[
                styles.divider,
                {backgroundColor: theme.border.neutral.default},
              ]}
            />

            <View style={styles.statsRow}>
              <StatItem
                icon={
                  <IconBallFootball
                    size={ICON_SIZES.x5}
                    color={theme.text.neutral.brand}
                  />
                }
                label={t('sportsPool.ranking_page.results_label')}
                title={t('sportsPool.ranking_page.positive_title')}
                count={stats?.ranking.correctResults ?? 0}
              />
              <View
                style={[
                  styles.verticalDivider,
                  {backgroundColor: theme.border.neutral.default},
                ]}
              />
              <StatItem
                icon={
                  <IconTargetArrow
                    size={ICON_SIZES.x5}
                    color={theme.text.neutral.brand}
                  />
                }
                label={t('sportsPool.ranking_page.results_label')}
                title={t('sportsPool.ranking_page.exact_title')}
                count={stats?.ranking.exactResults ?? 0}
              />
            </View>
          </View>
        )}
      </View>
    </Dialog>
  );
}

export default UserStatsDialog;
