import { css, keyframes } from '@emotion/react';
import { useState } from 'react';
import { adaptive } from '../../styles/adaptive';
import { useGameStore } from '../../store/useGameStore';
import achievementsData from '../../data/achievements.json';
import elementsData from '../../data/elements.json';
import { PrestigeModal } from '../PrestigeModal';

// ────────────────────────────────────────────────────────────
// Types
// ────────────────────────────────────────────────────────────

interface AchievementCondition {
  type: string;
  value: number;
  target?: string;
  tier?: number;
}

interface AchievementReward {
  gold?: number;
  boostType?: string;
  boostDurationMin?: number;
  bonusScrolls?: number;
  permanentGoldMultiplier?: number;
  permanentSpawnMultiplier?: number;
  title?: string;
  specialBackground?: string;
}

interface Achievement {
  id: string;
  name: string;
  description: string;
  category: string;
  condition: AchievementCondition;
  reward: AchievementReward;
  isHidden: boolean;
}

const ACHIEVEMENTS = achievementsData as Achievement[];

type CategoryKey = 'beginner' | 'intermediate' | 'advanced' | 'prestige';

const CATEGORY_TABS: { key: CategoryKey; label: string; icon: string }[] = [
  { key: 'beginner', label: '입문', icon: '🌱' },
  { key: 'intermediate', label: '중급', icon: '⚡' },
  { key: 'advanced', label: '고급', icon: '🔥' },
  { key: 'prestige', label: '프레스티지', icon: '✨' },
];

// ────────────────────────────────────────────────────────────
// Progress calculation
// ────────────────────────────────────────────────────────────

function calcProgress(
  condition: AchievementCondition,
  state: {
    elements: Record<string, number>;
    gold: number;
    elementLevels: Record<string, number>;
    achievementStats: {
      fuseCount: number;
      enhanceCount: number;
      offlineClaimCount: number;
      prestigeCount: number;
      tiersUnlocked: number[];
    };
  }
): { current: number; max: number } {
  const { elements, gold, elementLevels, achievementStats } = state;
  const ENHANCE_MAX_LEVEL = 5;

  switch (condition.type) {
    case 'fuse_count':
      return { current: achievementStats.fuseCount, max: condition.value };
    case 'enhance_count':
      return { current: achievementStats.enhanceCount, max: condition.value };
    case 'offline_claim':
      return { current: achievementStats.offlineClaimCount, max: condition.value };
    case 'prestige_count':
      return { current: achievementStats.prestigeCount, max: condition.value };
    case 'element_count':
      return { current: elements[condition.target ?? ''] ?? 0, max: condition.value };
    case 'element_variety':
      return {
        current: Object.values(elements).filter((c) => c > 0).length,
        max: condition.value,
      };
    case 'gold_amount':
      return { current: gold, max: condition.value };
    case 'max_enhance_count': {
      const maxCount = Object.values(elementLevels).filter(
        (lv) => lv >= ENHANCE_MAX_LEVEL
      ).length;
      return { current: maxCount, max: condition.value };
    }
    case 'total_elements': {
      const total = Object.values(elements).reduce((s, c) => s + c, 0);
      return { current: total, max: condition.value };
    }
    case 'single_element_count': {
      const maxCount = Math.max(0, ...Object.values(elements));
      return { current: maxCount, max: condition.value };
    }
    case 'tier_variety': {
      const targetTier = condition.tier ?? 0;
      const tierIds = (elementsData as Array<{ id: string; tier: number }>)
        .filter((e) => e.tier === targetTier)
        .map((e) => e.id);
      const discovered = tierIds.filter((id) => (elements[id] ?? 0) > 0).length;
      return { current: discovered, max: condition.value };
    }
    case 'all_enhance_min_level': {
      const discoveredIds = Object.entries(elements)
        .filter(([, count]) => count > 0)
        .map(([id]) => id);
      if (discoveredIds.length === 0) return { current: 0, max: 1 };
      const meetCount = discoveredIds.filter(
        (id) => (elementLevels[id] ?? 0) >= condition.value
      ).length;
      return { current: meetCount, max: discoveredIds.length };
    }
    case 'tier_unlock':
      return {
        current: achievementStats.tiersUnlocked.includes(condition.value) ? 1 : 0,
        max: 1,
      };
    case 'element_unlock':
      return {
        current: (elements[condition.target ?? ''] ?? 0) > 0 ? 1 : 0,
        max: 1,
      };
    default:
      return { current: 0, max: 1 };
  }
}

function formatReward(reward: AchievementReward): string {
  const parts: string[] = [];
  if (reward.gold) parts.push(`💰 ${reward.gold.toLocaleString()}G`);
  if (reward.permanentGoldMultiplier)
    parts.push(`🏅 골드 +${(reward.permanentGoldMultiplier * 100).toFixed(0)}%`);
  if (reward.permanentSpawnMultiplier)
    parts.push(`🏅 스폰 +${(reward.permanentSpawnMultiplier * 100).toFixed(0)}%`);
  if (reward.title) parts.push(`👑 칭호: ${reward.title}`);
  if (reward.boostType) parts.push('⚡ 버프');
  return parts.join(' · ') || '보상 없음';
}

// ────────────────────────────────────────────────────────────
// Styles
// ────────────────────────────────────────────────────────────

const containerStyle = css`
  padding: 20px 20px 24px;
  background: ${adaptive.background};
  min-height: 100%;
`;

const headerStyle = css`
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
`;

const titleStyle = css`
  font-size: 20px;
  font-weight: 700;
  color: ${adaptive.grey900};
  margin: 0;
`;

const progressSummaryStyle = css`
  font-size: 13px;
  font-weight: 600;
  color: ${adaptive.blue500};
`;

const tabRowStyle = css`
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  overflow-x: auto;
  padding-bottom: 2px;
  -webkit-overflow-scrolling: touch;
  &::-webkit-scrollbar { display: none; }
`;

const tabButtonStyle = (active: boolean) => css`
  flex-shrink: 0;
  padding: 7px 14px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: ${active ? 700 : 500};
  border: none;
  background: ${active ? adaptive.blue500 : adaptive.greyBackground};
  color: ${active ? '#ffffff' : adaptive.grey600};
  cursor: pointer;
  transition: background 0.15s, color 0.15s;
`;

const achievementListStyle = css`
  display: flex;
  flex-direction: column;
  gap: 10px;
`;

const achievementCardBaseStyle = `
  border-radius: 14px;
  padding: 14px 16px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
`;

const achievementCardUnlockedStyle = css`
  ${achievementCardBaseStyle}
  background: ${adaptive.background};
  border: 1.5px solid ${adaptive.grey200};
`;

const achievementCardLockedStyle = css`
  ${achievementCardBaseStyle}
  background: ${adaptive.greyBackground};
  border: 1px solid ${adaptive.grey100};
  opacity: 0.7;
`;

const achievementCardHiddenStyle = css`
  ${achievementCardBaseStyle}
  background: ${adaptive.greyBackground};
  border: 1px dashed ${adaptive.grey200};
  opacity: 0.5;
`;

const iconBoxStyle = (unlocked: boolean) => css`
  width: 44px;
  height: 44px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  flex-shrink: 0;
  background: ${unlocked
    ? 'linear-gradient(135deg, #fff8e1, #ffe082)'
    : adaptive.grey200};
  border: 1.5px solid ${unlocked ? '#ffc107' : adaptive.grey300};
`;

const achievementInfoStyle = css`
  flex: 1;
  min-width: 0;
`;

const achievementNameStyle = (unlocked: boolean) => css`
  font-size: 14px;
  font-weight: 700;
  color: ${unlocked ? adaptive.grey900 : adaptive.grey600};
  margin: 0 0 3px;
`;

const achievementDescStyle = css`
  font-size: 12px;
  color: ${adaptive.grey500};
  margin: 0 0 6px;
  line-height: 1.4;
`;

const rewardRowStyle = css`
  font-size: 11px;
  color: #b8860b;
  font-weight: 600;
`;

const progressBarWrapStyle = css`
  margin-top: 6px;
`;

const progressRowStyle = css`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
`;

const progressLabelStyle = css`
  font-size: 11px;
  color: ${adaptive.grey500};
`;

const progressCountStyle = css`
  font-size: 11px;
  font-weight: 700;
  color: ${adaptive.blue500};
`;

const progressTrackStyle = css`
  height: 4px;
  background: ${adaptive.grey200};
  border-radius: 2px;
  overflow: hidden;
`;

const progressFillStyle = (ratio: number) => css`
  height: 100%;
  width: ${Math.min(ratio * 100, 100).toFixed(1)}%;
  background: linear-gradient(90deg, #3182f6, #7c4dff);
  border-radius: 2px;
  transition: width 0.3s ease;
`;

const unlockedBadgePulse = keyframes`
  0%   { transform: scale(1); }
  50%  { transform: scale(1.15); }
  100% { transform: scale(1); }
`;

const checkBadgeStyle = css`
  font-size: 18px;
  flex-shrink: 0;
  animation: ${unlockedBadgePulse} 1.5s ease-in-out infinite;
`;

// ── 프레스티지 버튼 섹션 ──────────────────────────────────

const prestigeSectionStyle = css`
  margin-bottom: 20px;
  border-radius: 16px;
  overflow: hidden;
  background: linear-gradient(135deg, #1a0a00, #3d1a00);
  border: 1.5px solid #ff9800;
  padding: 18px 16px;
`;

const prestigeTitleStyle = css`
  font-size: 16px;
  font-weight: 700;
  color: #ffd700;
  margin: 0 0 6px;
`;

const prestigeDescStyle = css`
  font-size: 12px;
  color: #ffcc80;
  margin: 0 0 14px;
  line-height: 1.5;
`;

const prestigeButtonStyle = css`
  width: 100%;
  padding: 14px;
  border-radius: 12px;
  background: linear-gradient(135deg, #ff6f00, #ffd700);
  color: #3d1a00;
  font-size: 15px;
  font-weight: 700;
  border: none;
  cursor: pointer;
  letter-spacing: 0.3px;
  box-shadow: 0 4px 16px rgba(255, 180, 0, 0.4);
  transition: transform 0.15s, box-shadow 0.15s;
  &:active { transform: scale(0.97); box-shadow: 0 2px 8px rgba(255, 180, 0, 0.3); }
`;

const prestigeLockedStyle = css`
  background: ${adaptive.greyBackground};
  border: 1px dashed ${adaptive.grey300};
  border-radius: 14px;
  padding: 14px 16px;
  margin-bottom: 16px;
  text-align: center;
  font-size: 13px;
  color: ${adaptive.grey500};
`;

const prestigeCountBadgeStyle = css`
  display: inline-flex;
  align-items: center;
  gap: 4px;
  background: rgba(255, 215, 0, 0.15);
  border: 1px solid rgba(255, 215, 0, 0.4);
  border-radius: 8px;
  padding: 3px 8px;
  font-size: 11px;
  font-weight: 700;
  color: #ffd700;
  margin-bottom: 10px;
`;

// ────────────────────────────────────────────────────────────
// AchievementCard
// ────────────────────────────────────────────────────────────

interface AchievementCardProps {
  ach: Achievement;
  unlocked: boolean;
  progressState: {
    elements: Record<string, number>;
    gold: number;
    elementLevels: Record<string, number>;
    achievementStats: {
      fuseCount: number;
      enhanceCount: number;
      offlineClaimCount: number;
      prestigeCount: number;
      tiersUnlocked: number[];
    };
  };
}

const CATEGORY_ICONS: Record<string, string> = {
  beginner: '🌱',
  intermediate: '⚡',
  advanced: '🔥',
  prestige: '✨',
};

function AchievementCard({ ach, unlocked, progressState }: AchievementCardProps) {
  const isHiddenLocked = ach.isHidden && !unlocked;

  if (isHiddenLocked) {
    return (
      <div css={achievementCardHiddenStyle}>
        <div css={iconBoxStyle(false)}>❓</div>
        <div css={achievementInfoStyle}>
          <p css={achievementNameStyle(false)}>???</p>
          <p css={achievementDescStyle}>숨겨진 업적입니다</p>
        </div>
      </div>
    );
  }

  const { current, max } = calcProgress(ach.condition, progressState);
  const ratio = max > 0 ? current / max : 0;
  const icon = CATEGORY_ICONS[ach.category] ?? '🏅';

  if (unlocked) {
    return (
      <div css={achievementCardUnlockedStyle}>
        <div css={iconBoxStyle(true)}>{icon}</div>
        <div css={achievementInfoStyle}>
          <p css={achievementNameStyle(true)}>{ach.name}</p>
          <p css={achievementDescStyle}>{ach.description}</p>
          <p css={rewardRowStyle}>{formatReward(ach.reward)}</p>
        </div>
        <span css={checkBadgeStyle}>✅</span>
      </div>
    );
  }

  const showCount = max > 1;
  const displayCurrent = Math.min(current, max);

  return (
    <div css={achievementCardLockedStyle}>
      <div css={iconBoxStyle(false)}>{icon}</div>
      <div css={achievementInfoStyle}>
        <p css={achievementNameStyle(false)}>{ach.name}</p>
        <p css={achievementDescStyle}>{ach.description}</p>
        <p css={rewardRowStyle}>{formatReward(ach.reward)}</p>
        {showCount && (
          <div css={progressBarWrapStyle}>
            <div css={progressRowStyle}>
              <span css={progressLabelStyle}>진행도</span>
              <span css={progressCountStyle}>
                {displayCurrent.toLocaleString()} / {max.toLocaleString()}
              </span>
            </div>
            <div css={progressTrackStyle}>
              <div css={progressFillStyle(ratio)} />
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// AchievementsScreen
// ────────────────────────────────────────────────────────────

export function AchievementsScreen() {
  const [activeCategory, setActiveCategory] = useState<CategoryKey>('beginner');
  const [showPrestigeModal, setShowPrestigeModal] = useState(false);

  const elements = useGameStore((s) => s.elements);
  const gold = useGameStore((s) => s.gold);
  const elementLevels = useGameStore((s) => s.elementLevels);
  const unlockedAchievements = useGameStore((s) => s.unlockedAchievements);
  const achievementStats = useGameStore((s) => s.achievementStats);
  const prestigeCount = useGameStore((s) => s.prestigeCount);
  const prestigeTitle = useGameStore((s) => s.prestigeTitle);

  const canPrestige =
    (elements['creation'] ?? 0) >= 1 && (elements['spirit'] ?? 0) >= 1;

  const progressState = { elements, gold, elementLevels, achievementStats };

  const filteredAchievements = ACHIEVEMENTS.filter(
    (ach) => ach.category === activeCategory
  );

  const totalUnlocked = unlockedAchievements.length;
  const totalCount = ACHIEVEMENTS.length;

  return (
    <div css={containerStyle}>
      <div css={headerStyle}>
        <h1 css={titleStyle}>업적</h1>
        <span css={progressSummaryStyle}>
          {totalUnlocked} / {totalCount}
        </span>
      </div>

      {/* 프레스티지 버튼 */}
      {activeCategory === 'prestige' && (
        canPrestige ? (
          <div css={prestigeSectionStyle}>
            {prestigeCount > 0 && (
              <div css={prestigeCountBadgeStyle}>
                ✨ {prestigeCount}회 환생 달성 {prestigeTitle && `· ${prestigeTitle}`}
              </div>
            )}
            <p css={prestigeTitleStyle}>환생 준비 완료</p>
            <p css={prestigeDescStyle}>
              Creation과 Spirit 원소를 모두 보유하고 있습니다.
              환생하면 진행이 초기화되지만 영구 보너스를 획득합니다.
            </p>
            <button css={prestigeButtonStyle} onClick={() => setShowPrestigeModal(true)}>
              ✨ 환생하기 (프레스티지)
            </button>
          </div>
        ) : (
          <div css={prestigeLockedStyle}>
            🔒 Creation + Spirit 원소를 모두 보유하면 프레스티지가 가능합니다
          </div>
        )
      )}

      {/* 카테고리 탭 */}
      <div css={tabRowStyle}>
        {CATEGORY_TABS.map((tab) => {
          const catAchs = ACHIEVEMENTS.filter((a) => a.category === tab.key);
          const catUnlocked = catAchs.filter((a) =>
            unlockedAchievements.includes(a.id)
          ).length;
          return (
            <button
              key={tab.key}
              css={tabButtonStyle(activeCategory === tab.key)}
              onClick={() => setActiveCategory(tab.key)}
            >
              {tab.icon} {tab.label} ({catUnlocked}/{catAchs.length})
            </button>
          );
        })}
      </div>

      {/* 업적 목록 */}
      <div css={achievementListStyle}>
        {filteredAchievements.map((ach) => (
          <AchievementCard
            key={ach.id}
            ach={ach}
            unlocked={unlockedAchievements.includes(ach.id)}
            progressState={progressState}
          />
        ))}
      </div>

      {/* 프레스티지 모달 */}
      {showPrestigeModal && (
        <PrestigeModal onClose={() => setShowPrestigeModal(false)} />
      )}
    </div>
  );
}
