import React, {useEffect, useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconArrowNarrowRight} from '@tabler/icons-react-native';
import {Dialog, Image, Pill, Skeleton, Typography} from '@components';
import {
  Match,
  MatchInPrediction,
  Prediction,
} from '@modules/prodev2/interfaces';
import {prodeKeys} from '@modules/prodev2/constants';
import {getMatchBreakdown} from '@modules/prodev2/services';
import {
  formatBreakdownPoints,
  formatScorePoints,
  getFlagEmoji,
  getScorePointsPillType,
} from '@modules/prodev2/utils';
import {useQuery} from '@shared/hooks/queries-v5/useQuery';
import {ICON_SIZES, useTheme} from '@shared/theme';

import {styles} from './styles';

export interface Props {
  isOpen: boolean;
  onClose: () => void;
  competitionId: number;
  match: Nullable<Match | MatchInPrediction>;
  prediction: Nullable<Prediction>;
}

export function MatchDetailModal({
  isOpen,
  onClose,
  competitionId,
  match,
  prediction,
}: Props) {
  const {t} = useTranslation();
  const {theme} = useTheme();

  const [display, setDisplay] = useState<{
    match: Nullable<Match | MatchInPrediction>;
    prediction: Nullable<Prediction>;
  }>({match, prediction});
  useEffect(() => {
    if (match) setDisplay({match, prediction});
  }, [match, prediction]);
  const displayMatch = display.match;
  const displayPrediction = display.prediction;

  const isFinishedWithPrediction =
    displayMatch?.status === 'FINISHED' && !!displayPrediction;

  const {data: breakdownData, isLoading: isBreakdownLoading} = useQuery(
    prodeKeys.matchBreakdown(competitionId, displayMatch?.id ?? 0),
    () => getMatchBreakdown(competitionId, displayMatch?.id ?? 0),
    {enabled: isOpen && isFinishedWithPrediction && !!displayMatch},
  );

  const homeFlagEmoji = getFlagEmoji(displayMatch?.homeTeam);
  const awayFlagEmoji = getFlagEmoji(displayMatch?.awayTeam);

  const homeName =
    (displayMatch?.homeTeam?.localizedName ?? displayMatch?.homeTeam?.name) ||
    displayMatch?.homeTeamPlaceholder ||
    t('sportsPool.matches.tbd');
  const awayName =
    (displayMatch?.awayTeam?.localizedName ?? displayMatch?.awayTeam?.name) ||
    displayMatch?.awayTeamPlaceholder ||
    t('sportsPool.matches.tbd');

  const isFinished = displayMatch?.status === 'FINISHED';
  const finalScore = isFinished
    ? `${displayMatch?.homeScore ?? 0} - ${displayMatch?.awayScore ?? 0}`
    : t('sportsPool.matches.vs');
  const predictionScore = displayPrediction
    ? `${displayPrediction.predictedHomeScore}-${displayPrediction.predictedAwayScore}`
    : null;

  const pointsEarned =
    breakdownData?.totalPoints ?? displayPrediction?.pointsEarned ?? 0;
  const breakdownItems = breakdownData?.items ?? [];

  return (
    <Dialog
      isVisible={isOpen}
      onClose={onClose}
      title={t('sportsPool.prediction.detail_title')}
      wrapperType="scrollable">
      {displayMatch ? (
        <View style={styles.body}>
          <View style={styles.header}>
            {homeFlagEmoji ? (
              <Typography style={styles.flagEmoji}>{homeFlagEmoji}</Typography>
            ) : displayMatch.homeTeam?.flagUrl ? (
              <Image
                source={{uri: displayMatch.homeTeam.flagUrl}}
                style={styles.flagImage}
                contentFit="cover"
              />
            ) : null}
            <Typography variant="m" weight="semiBold" align="center">
              {`${homeName} ${finalScore} ${awayName}`}
            </Typography>
            {awayFlagEmoji ? (
              <Typography style={styles.flagEmoji}>{awayFlagEmoji}</Typography>
            ) : displayMatch.awayTeam?.flagUrl ? (
              <Image
                source={{uri: displayMatch.awayTeam.flagUrl}}
                style={styles.flagImage}
                contentFit="cover"
              />
            ) : null}
          </View>

          {displayPrediction && (
            <View
              style={[
                styles.predictionRow,
                {borderBottomColor: theme.border.neutral.default},
              ]}>
              <View style={styles.pillsRow}>
                <Pill
                  size="sm"
                  variant="neutral"
                  text={t('sportsPool.prediction.my_prediction', {
                    score: predictionScore,
                  })}
                />
                <IconArrowNarrowRight
                  size={ICON_SIZES.x5}
                  color={theme.text.neutral.default}
                />
                <Pill
                  size="sm"
                  variant={getScorePointsPillType(pointsEarned)}
                  text={t('sportsPool.prediction.points_earned', {
                    points: formatScorePoints(pointsEarned),
                  })}
                />
              </View>
              {displayPrediction.predictedHomeScore ===
                displayPrediction.predictedAwayScore &&
                displayPrediction.predictedQualifierId && (
                  <View style={styles.bullet}>
                    <View
                      style={[
                        styles.bulletDot,
                        {backgroundColor: theme.text.neutral.default},
                      ]}
                    />
                    <Typography variant="xxs">
                      {t('sportsPool.matches.penalty_winner', {
                        team:
                          displayPrediction.predictedQualifierId ===
                          displayMatch.homeTeam?.id
                            ? displayMatch.homeTeam?.localizedName ??
                              displayMatch.homeTeam?.name
                            : displayMatch.awayTeam?.localizedName ??
                              displayMatch.awayTeam?.name,
                      })}
                    </Typography>
                  </View>
                )}
            </View>
          )}

          {isFinishedWithPrediction && (
            <View style={styles.pointsList}>
              {isBreakdownLoading && (
                <Skeleton style={styles.pointsList}>
                  <Skeleton.Item style={styles.skeletonRow} width="80%" />
                  <Skeleton.Item style={styles.skeletonRow} width="60%" />
                </Skeleton>
              )}
              {!isBreakdownLoading && breakdownItems.length > 0 && (
                <View style={styles.pointsList}>
                  {breakdownItems.map((item, index) => (
                    <View key={index} style={styles.bullet}>
                      <View
                        style={[
                          styles.bulletDot,
                          {backgroundColor: theme.text.neutral.default},
                        ]}
                      />
                      <Typography variant="xxs">
                        {`${t(
                          `sportsPool.prediction.breakdown.${item.reason}`,
                        )}: `}
                        <Typography variant="xxs" weight="semiBold">
                          {`${formatBreakdownPoints(
                            item.points,
                            item.reason,
                          )} ${t('sportsPool.prediction.breakdown.point', {
                            count: item.points,
                          })}`}
                        </Typography>
                      </Typography>
                    </View>
                  ))}
                </View>
              )}
              {!isBreakdownLoading && breakdownItems.length === 0 && (
                <View style={styles.bullet}>
                  <View
                    style={[
                      styles.bulletDot,
                      {backgroundColor: theme.text.neutral.default},
                    ]}
                  />
                  <Typography variant="xxs">
                    {t('sportsPool.prediction.incorrect')}
                  </Typography>
                </View>
              )}
            </View>
          )}
        </View>
      ) : null}
    </Dialog>
  );
}

export default MatchDetailModal;
