import { Box, Typography, Button, Dialog, DialogContent } from '@mui/material';
import { useEffect, useState, useRef, useCallback } from 'react';
import { CaseItem } from '../api';

type Rarity = 'common' | 'rare' | 'epic' | 'legendary';

interface CaseRouletteProps {
  open: boolean;
  onClose: () => void;
  caseName?: string;
  items: CaseItem[];
  reward: CaseItem | null;
}

// --- настройки рулетки ---
const ITEM_WIDTH = 110;
const ITEM_GAP = 8;
const VISIBLE_ITEMS = 21;
const CONTAINER_WIDTH = 800;
const LINE_X = CONTAINER_WIDTH / 2;

const ANIMATION_DURATION = 10; // секунды
const ANIMATION_DURATION_MS = ANIMATION_DURATION * 1000;

// Удаляем майнкрафтовские цвет-коды (§a, §b, §l и т.д.)
function stripMinecraftColors(text?: string | null): string {
  if (!text) return '';
  return text.replace(/§[0-9A-FK-ORa-fk-or]/g, '');
}

function getRarityByWeight(weight?: number): Rarity {
  if (weight === undefined || weight === null) return 'common';
  if (weight <= 5) return 'legendary';
  if (weight <= 20) return 'epic';
  if (weight <= 50) return 'rare';
  return 'common';
}

function getRarityColor(weight?: number): string {
  const rarity = getRarityByWeight(weight);
  switch (rarity) {
    case 'legendary':
      return 'rgba(255, 215, 0, 1)';
    case 'epic':
      return 'rgba(186, 85, 211, 1)';
    case 'rare':
      return 'rgba(65, 105, 225, 1)';
    case 'common':
    default:
      return 'rgba(255, 255, 255, 0.6)';
  }
}

export default function CaseRoulette({
  open,
  onClose,
  caseName,
  items,
  reward,
}: CaseRouletteProps) {
  const [sequence, setSequence] = useState<CaseItem[]>([]);
  const [offset, setOffset] = useState(0);
  const [animating, setAnimating] = useState(false);
  const [animationFinished, setAnimationFinished] = useState(false);
  const itemRefs = useRef<(HTMLDivElement | null)[]>([]);
  const animationTimeoutRef = useRef<NodeJS.Timeout>();
  const finishTimeoutRef = useRef<NodeJS.Timeout>();

  const winningNameRaw =
    reward?.meta?.display_name || reward?.name || reward?.material || '';
  const winningName = stripMinecraftColors(winningNameRaw);

  // Измеряем реальные ширины элементов
  const measureItemWidths = useCallback((): number[] => {
    return itemRefs.current.map((ref) =>
      ref ? ref.getBoundingClientRect().width : ITEM_WIDTH,
    );
  }, []);

  // Основной эффект для инициализации
  useEffect(() => {
    if (!open || !reward || !items || items.length === 0) return;

    if (animationTimeoutRef.current) clearTimeout(animationTimeoutRef.current);
    if (finishTimeoutRef.current) clearTimeout(finishTimeoutRef.current);

    setAnimating(false);
    setAnimationFinished(false);
    setOffset(0);
    itemRefs.current = [];

    const totalItems = VISIBLE_ITEMS * 3;
    const seq: CaseItem[] = [];

    for (let i = 0; i < totalItems; i++) {
      const randomItem = items[Math.floor(Math.random() * items.length)];
      seq.push(randomItem);
    }

    const winPosition = Math.floor(totalItems / 2);
    const fromCase =
      items.find((i) => i.material === reward.material) || reward;
    seq[winPosition] = fromCase;

    setSequence(seq);
  }, [open, reward, items]);

  // Эффект запуска анимации
  useEffect(() => {
    if (sequence.length === 0 || !open) return;

    const startAnimation = () => {
      const widths = measureItemWidths();
      const winPosition = Math.floor(sequence.length / 2);

      const EXTRA_SPINS = 3;
      const averageItemWidth = ITEM_WIDTH + ITEM_GAP;
      const extraDistance = EXTRA_SPINS * VISIBLE_ITEMS * averageItemWidth;

      if (widths.length === 0 || widths.length !== sequence.length) {
        const centerItemCenter =
          winPosition * (ITEM_WIDTH + ITEM_GAP) + ITEM_WIDTH / 2;

        const finalOffset = centerItemCenter - LINE_X;
        const initialOffset = Math.max(finalOffset - extraDistance, 0);

        setOffset(initialOffset);

        animationTimeoutRef.current = setTimeout(() => {
          setAnimating(true);
          setOffset(finalOffset);
        }, 50);

        finishTimeoutRef.current = setTimeout(() => {
          setAnimationFinished(true);
        }, ANIMATION_DURATION_MS + 200);

        return;
      }

      let cumulativeOffset = 0;
      for (let i = 0; i < winPosition; i++) {
        cumulativeOffset += widths[i] + ITEM_GAP;
      }
      const centerItemCenter = cumulativeOffset + widths[winPosition] / 2;

      const finalOffset = centerItemCenter - LINE_X;
      const initialOffset = Math.max(finalOffset - extraDistance, 0);

      setOffset(initialOffset);

      animationTimeoutRef.current = setTimeout(() => {
        setAnimating(true);
        setOffset(finalOffset);
      }, 50);

      finishTimeoutRef.current = setTimeout(() => {
        setAnimationFinished(true);
      }, ANIMATION_DURATION_MS + 200);
    };

    const renderTimeout = setTimeout(startAnimation, 100);

    return () => {
      clearTimeout(renderTimeout);
      if (animationTimeoutRef.current)
        clearTimeout(animationTimeoutRef.current);
      if (finishTimeoutRef.current) clearTimeout(finishTimeoutRef.current);
    };
  }, [sequence, open, measureItemWidths]);

  // Очистка при закрытии
  useEffect(() => {
    if (!open) {
      if (animationTimeoutRef.current)
        clearTimeout(animationTimeoutRef.current);
      if (finishTimeoutRef.current) clearTimeout(finishTimeoutRef.current);
      setSequence([]);
      setAnimating(false);
      setAnimationFinished(false);
      setOffset(0);
    }
  }, [open]);

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="md"
      fullWidth
      PaperProps={{
        sx: {
          bgcolor: 'transparent',
          borderRadius: '2.5vw',
          overflow: 'hidden',
          boxShadow: '0 30px 80px rgba(0,0,0,0.9)',
        },
      }}
    >
      <DialogContent
        sx={{
          position: 'relative',
          px: 3,
          py: 3.5,
          background:
            'radial-gradient(circle at top, #101018 0%, #050509 40%, #000 100%)',
        }}
      >
        {/* лёгкий "бордер" по контуру */}
        <Box
          sx={{
            position: 'absolute',
            inset: 0,
            pointerEvents: 'none',
            borderRadius: '2.5vw',
            border: '1px solid rgba(255,255,255,0.08)',
          }}
        />

        {/* заголовок с градиентом как в Registration */}
        <Typography
          variant="h6"
          sx={{
            textAlign: 'center',
            mb: 2.5,
            fontFamily: 'Benzin-Bold',
            letterSpacing: 0.6,
            backgroundImage:
              'linear-gradient(136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
          }}
        >
          Открытие кейса {caseName}
        </Typography>

        {/* контейнер рулетки */}
        <Box
          sx={{
            position: 'relative',
            overflow: 'hidden',
            borderRadius: '2vw',
            px: 2,
            py: 3,
            width: `${CONTAINER_WIDTH}px`,
            maxWidth: '100%',
            mx: 'auto',
            background:
              'linear-gradient(135deg, rgba(15,15,20,0.96), rgba(30,20,35,0.96))',
            boxShadow: '0 0 40px rgba(0,0,0,0.8)',
          }}
        >
          {/* затемнённые края */}
          <Box
            sx={{
              position: 'absolute',
              inset: 0,
              pointerEvents: 'none',
              background:
                'linear-gradient(90deg, rgba(0,0,0,0.85) 0%, transparent 20%, transparent 80%, rgba(0,0,0,0.85) 100%)',
              zIndex: 1,
            }}
          />

          {/* центральная линия (прицел) */}
          <Box
            sx={{
              position: 'absolute',
              top: 0,
              bottom: 0,
              left: `${LINE_X}px`,
              transform: 'translateX(-1px)',
              width: '2px',
              background:
                'linear-gradient(180deg, rgb(242,113,33), rgb(233,64,87))',
              boxShadow: '0 0 16px rgba(233,64,87,0.9)',
              zIndex: 2,
            }}
          />

          {/* Лента предметов */}
          <Box
            sx={{
              display: 'flex',
              flexDirection: 'row',
              gap: `${ITEM_GAP}px`,
              transform: `translateX(-${offset}px)`,
              willChange: 'transform',
              transition: animating
                ? `transform ${ANIMATION_DURATION}s cubic-bezier(0.15, 0.85, 0.25, 1)`
                : 'none',
              position: 'relative',
              zIndex: 0,
            }}
          >
            {sequence.map((item, index) => {
              const color = getRarityColor(item.weight);
              const isWinningItem =
                animationFinished && index === Math.floor(sequence.length / 2);

              const rawName =
                item.meta?.display_name ||
                item.name ||
                item.material
                  .replace(/_/g, ' ')
                  .toLowerCase()
                  .replace(/\b\w/g, (l) => l.toUpperCase());
              const displayName = stripMinecraftColors(rawName);

              return (
                <Box
                  key={index}
                  ref={(el) => (itemRefs.current[index] = el)}
                  sx={{
                    minWidth: `${ITEM_WIDTH}px`,
                    height: 130,
                    borderRadius: '1.4vw',
                    background: 'rgba(255,255,255,0.03)',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                    border: isWinningItem
                      ? `2px solid ${color}`
                      : `1px solid ${color}`,
                    boxShadow: isWinningItem
                      ? `0 0 24px ${color}`
                      : '0 0 10px rgba(0,0,0,0.6)',
                    transition: 'all 0.3s ease',
                    px: 1,
                    transform: isWinningItem ? 'scale(1.08)' : 'scale(1)',
                  }}
                >
                  <Box
                    component="img"
                    src={`https://cdn.minecraft.popa-popa.ru/textures/${item.material.toLowerCase()}.png`}
                    alt={item.material}
                    sx={{
                      width: 52,
                      height: 52,
                      objectFit: 'contain',
                      imageRendering: 'pixelated',
                      mb: 1,
                    }}
                  />
                  <Typography
                    variant="body2"
                    sx={{
                      color: 'white',
                      textAlign: 'center',
                      fontSize: '0.72rem',
                      maxWidth: 100,
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                    }}
                  >
                    {displayName}
                  </Typography>
                </Box>
              );
            })}
          </Box>
        </Box>

        {animationFinished && winningName && (
          <Typography
            variant="body1"
            sx={{
              textAlign: 'center',
              mt: 2.5,
              color: 'rgba(255,255,255,0.9)',
            }}
          >
            Вам выпало:{' '}
            <Box
              component="span"
              sx={{
                fontFamily: 'Benzin-Bold',
                backgroundImage:
                  'linear-gradient(136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
                WebkitBackgroundClip: 'text',
                WebkitTextFillColor: 'transparent',
              }}
            >
              {winningName}
            </Box>
          </Typography>
        )}

        {/* кнопка как в Registration */}
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 3 }}>
          <Button
            variant="contained"
            onClick={onClose}
            sx={{
              transition: 'transform 0.3s ease',
              borderRadius: '2.5vw',
              px: '3vw',
              py: '0.7vw',
              background:
                'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)',
              fontFamily: 'Benzin-Bold',
              fontSize: '0.9rem',
              textTransform: 'uppercase',
              letterSpacing: 1,
              color: '#fff',
              opacity: animationFinished ? 1 : 0.4,
              pointerEvents: animationFinished ? 'auto' : 'none',
              '&:hover': {
                transform: 'scale(1.02)',
              },
            }}
          >
            Закрыть
          </Button>
        </Box>
      </DialogContent>
    </Dialog>
  );
}
