import { type FC, useEffect, useMemo } from 'react';
import { useQuery } from 'react-query';

import { parseAsStringLiteral, useQueryState } from 'nuqs';
import Box from '@material-hu/mui/Box';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import CardContainer from '@material-hu/components/design-system/CardContainer';
import Chip from '@material-hu/components/design-system/Chip';
import HuSpinner from '@material-hu/components/design-system/ProgressIndicators/Spinner';

import { getPrizes, getRules, prodeKeys } from 'src/services/prode';
import { useLokaliseTranslation } from 'src/utils/i18n';

import MarkdownContent from 'src/components/MarkdownContent';

import {
  getStaggerAnimationSx,
  loadingContainerSx,
  prizesSubTabsContainerSx,
  prizesTabContainerSx,
} from '../constants';

import FAQAccordion from './FAQAccordion';
import PrizeCard from './PrizeCard';
import RulesContent from './RulesContent';

type RulesTabProps = {
  competitionId: number;
};

const SUB_TABS = ['details', 'prizes', 'faqs'] as const;
type SubTab = (typeof SUB_TABS)[number];

const RulesTab: FC<RulesTabProps> = ({ competitionId }) => {
  const { t } = useLokaliseTranslation('sportsPool');

  // URL-synced sub-tab state
  const [subTabParam, setSubTabParam] = useQueryState(
    'section',
    parseAsStringLiteral(SUB_TABS),
  );
  const activeSubTab: SubTab = subTabParam ?? 'details';

  const { data: prizes, isLoading: isPrizesLoading } = useQuery(
    prodeKeys.prizes(competitionId),
    () => getPrizes(competitionId),
    {
      enabled: !!competitionId,
      select: res => res.data,
    },
  );

  const { data: rules, isLoading: isRulesLoading } = useQuery(
    prodeKeys.rules(competitionId),
    () => getRules(competitionId),
    {
      enabled: !!competitionId,
      select: res => res.data,
    },
  );

  const isLoading = isPrizesLoading || isRulesLoading;

  const allPrizes = useMemo(
    () => [...(prizes?.podiumPrizes || []), ...(prizes?.otherPrizes || [])],
    [prizes],
  );
  const hasPrizes = allPrizes.length > 0;
  const hasConsiderations = !!rules?.considerations;
  const hasFaqs = !!rules?.faq?.length;

  const subTabs = useMemo<{ id: SubTab; label: string }[]>(
    () => [
      { id: 'details', label: t('rules_tab.details') },
      ...(hasPrizes || hasConsiderations
        ? [{ id: 'prizes' as SubTab, label: t('rules_tab.prizes') }]
        : []),
      ...(hasFaqs
        ? [{ id: 'faqs' as SubTab, label: t('rules_tab.faqs') }]
        : []),
    ],
    [hasPrizes, hasConsiderations, hasFaqs, t],
  );

  const visibleTabIds = subTabs.map(tab => tab.id);
  const effectiveSubTab: SubTab = visibleTabIds.includes(activeSubTab)
    ? activeSubTab
    : 'details';

  useEffect(() => {
    if (!isLoading && activeSubTab !== effectiveSubTab) {
      setSubTabParam(effectiveSubTab);
    }
  }, [isLoading, activeSubTab, effectiveSubTab, setSubTabParam]);

  if (isLoading) {
    return (
      <Stack sx={loadingContainerSx}>
        <HuSpinner />
      </Stack>
    );
  }

  // Details sub-tab now shows rules content (was "Reglamento" content)
  const renderDetailsContent = () => {
    if (!rules) return null;
    return <RulesContent rulesContent={rules.rulesContent} />;
  };

  const renderPrizesContent = () => {
    if (!hasPrizes && !hasConsiderations) return null;

    return (
      <Stack sx={{ gap: 3 }}>
        {hasPrizes && (
          <Stack sx={{ gap: 1.5 }}>
            <Typography
              variant="globalS"
              fontWeight="fontWeightSemiBold"
              sx={{ lineHeight: 1 }}
            >
              {t('rules_tab.prize_details')}
            </Typography>
            <Stack sx={{ gap: 1 }}>
              {allPrizes.map((prize, index) => (
                <Box
                  key={prize.id}
                  sx={getStaggerAnimationSx(index)}
                >
                  <PrizeCard prize={prize} />
                </Box>
              ))}
            </Stack>
          </Stack>
        )}

        {hasConsiderations && (
          <Box sx={getStaggerAnimationSx(allPrizes.length)}>
            <Stack sx={{ gap: 1 }}>
              <Typography
                variant="globalS"
                fontWeight="fontWeightSemiBold"
              >
                {t('rules_tab.considerations')}
              </Typography>
              <CardContainer fullWidth>
                <MarkdownContent markdown={rules.considerations!} />
              </CardContainer>
            </Stack>
          </Box>
        )}
      </Stack>
    );
  };

  const renderFAQsContent = () => {
    if (!rules?.faq) return null;
    return <FAQAccordion faqItems={rules.faq} />;
  };

  return (
    <Stack sx={prizesTabContainerSx}>
      {/* Sub-tabs */}
      <Stack sx={prizesSubTabsContainerSx}>
        {subTabs.map(tab => (
          <Chip
            key={tab.id}
            size="medium"
            label={tab.label}
            isSelected={effectiveSubTab === tab.id}
            onClick={() => setSubTabParam(tab.id)}
          />
        ))}
      </Stack>
      {effectiveSubTab === 'details' && renderDetailsContent()}
      {effectiveSubTab === 'prizes' && renderPrizesContent()}
      {effectiveSubTab === 'faqs' && renderFAQsContent()}
    </Stack>
  );
};

export default RulesTab;
