import { useState, useCallback, useEffect, type CSSProperties } from 'react';
import type { HeroQuest } from '../game/types';
import { useT } from '../i18n';

// ---- Types ----

interface QuestLogProps {
  quests: HeroQuest[];
  onClaim: (heroQuestId: number) => void;
  onAbandon: (heroQuestId: number) => void;
  onClose: () => void;
}

// ---- Quest Type Icons ----

function questTypeIcon(type: string): string {
  switch (type) {
    case 'kill_count':
      return '\u2694\uFE0F'; // swords
    case 'visit_town':
      return '\uD83E\uDDED'; // compass
    case 'collect_item':
      return '\uD83D\uDC8E'; // gem
    default:
      return '\uD83D\uDCDC'; // scroll
  }
}

// ---- Styles ----

const overlayStyle: CSSProperties = {
  position: 'absolute',
  inset: 0,
  zIndex: 600,
  pointerEvents: 'auto',
};

const backdropStyle: CSSProperties = {
  position: 'absolute',
  inset: 0,
  backgroundColor: 'rgba(0, 0, 0, 0.4)',
};

const panelStyle: CSSProperties = {
  position: 'absolute',
  bottom: 0,
  left: 0,
  right: 0,
  maxHeight: '40vh',
  backgroundColor: 'rgba(15, 15, 25, 0.95)',
  borderTop: '2px solid rgba(255, 215, 0, 0.3)',
  borderRadius: '16px 16px 0 0',
  display: 'flex',
  flexDirection: 'column',
  animation: 'quest-log-slide-up 0.3s ease-out',
  overflow: 'hidden',
};

const headerStyle: CSSProperties = {
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'space-between',
  padding: '12px 16px 8px',
  borderBottom: '1px solid rgba(255, 255, 255, 0.08)',
};

const titleStyle: CSSProperties = {
  fontSize: 15,
  fontWeight: 700,
  color: '#ffd700',
  textShadow: '0 0 8px rgba(255, 215, 0, 0.3)',
};

const closeBtnStyle: CSSProperties = {
  background: 'none',
  border: 'none',
  color: '#888',
  fontSize: 20,
  cursor: 'pointer',
  padding: '4px 8px',
  lineHeight: 1,
};

const listStyle: CSSProperties = {
  overflowY: 'auto',
  padding: '8px 12px 16px',
  flex: 1,
};

const questCardStyle: CSSProperties = {
  backgroundColor: 'rgba(255, 255, 255, 0.04)',
  border: '1px solid rgba(255, 255, 255, 0.08)',
  borderRadius: 10,
  padding: '10px 12px',
  marginBottom: 8,
  cursor: 'pointer',
  transition: 'background-color 150ms ease',
};

const questHeaderRow: CSSProperties = {
  display: 'flex',
  alignItems: 'center',
  gap: 8,
};

const questTitleStyle: CSSProperties = {
  fontSize: 13,
  fontWeight: 600,
  color: '#e8e8e8',
  flex: 1,
};

const progressTextStyle: CSSProperties = {
  fontSize: 11,
  fontWeight: 700,
  color: '#aaa',
  whiteSpace: 'nowrap',
};

const progressBarOuter: CSSProperties = {
  height: 6,
  borderRadius: 3,
  backgroundColor: 'rgba(255, 255, 255, 0.08)',
  marginTop: 6,
  overflow: 'hidden',
};

const descriptionStyle: CSSProperties = {
  fontSize: 11,
  color: '#999',
  marginTop: 8,
  lineHeight: 1.4,
};

const rewardsRow: CSSProperties = {
  display: 'flex',
  gap: 10,
  marginTop: 8,
  fontSize: 11,
  fontWeight: 600,
};

const rewardChip: CSSProperties = {
  display: 'inline-flex',
  alignItems: 'center',
  gap: 3,
};

const actionRow: CSSProperties = {
  display: 'flex',
  gap: 8,
  marginTop: 10,
};

const claimBtnStyle: CSSProperties = {
  flex: 1,
  padding: '8px 0',
  border: 'none',
  borderRadius: 8,
  backgroundColor: 'rgba(255, 215, 0, 0.25)',
  color: '#ffd700',
  fontSize: 13,
  fontWeight: 700,
  cursor: 'pointer',
  textShadow: '0 0 6px rgba(255, 215, 0, 0.4)',
  boxShadow: '0 0 12px rgba(255, 215, 0, 0.15)',
  animation: 'quest-claim-glow 1.5s ease-in-out infinite',
};

const abandonBtnStyle: CSSProperties = {
  padding: '8px 14px',
  border: '1px solid rgba(255, 80, 80, 0.3)',
  borderRadius: 8,
  backgroundColor: 'rgba(255, 50, 50, 0.1)',
  color: '#cc6666',
  fontSize: 11,
  fontWeight: 600,
  cursor: 'pointer',
};

const emptyStyle: CSSProperties = {
  textAlign: 'center',
  color: '#666',
  fontSize: 13,
  padding: '24px 0',
};

interface QuestLogListProps {
  quests: HeroQuest[];
  onClaim: (heroQuestId: number) => void;
  onAbandon: (heroQuestId: number) => void;
}

/** Quest list body (embedded in Hero sheet or standalone panel). */
export function QuestLogList({ quests, onClaim, onAbandon }: QuestLogListProps) {
  const tr = useT();
  const [expandedId, setExpandedId] = useState<number | null>(null);

  const activeQuests = quests.filter((q) => q.status !== 'claimed');

  const handleCardClick = useCallback((id: number) => {
    setExpandedId((prev) => (prev === id ? null : id));
  }, []);

  return (
    <>
      <style>{`
        @keyframes quest-claim-glow {
          0%, 100% { box-shadow: 0 0 8px rgba(255, 215, 0, 0.15); }
          50%      { box-shadow: 0 0 18px rgba(255, 215, 0, 0.4); }
        }
      `}</style>
      <div
        style={{
          ...listStyle,
          padding: '0 0 8px',
          maxHeight: 'min(52vh, 400px)',
        }}
      >
            {activeQuests.length === 0 ? (
              <div style={emptyStyle}>{tr.noActiveQuests}</div>
            ) : (
              activeQuests.map((q) => {
                const isExpanded = expandedId === q.id;
                const isCompleted = q.status === 'completed';
                const pct = q.targetCount > 0 ? Math.min(100, (q.progress / q.targetCount) * 100) : 0;

                return (
                  <div
                    key={q.id}
                    style={{
                      ...questCardStyle,
                      borderColor: isCompleted
                        ? 'rgba(255, 215, 0, 0.3)'
                        : 'rgba(255, 255, 255, 0.08)',
                    }}
                    onClick={() => handleCardClick(q.id)}
                  >
                    <div style={questHeaderRow}>
                      <span style={{ fontSize: 16 }}>{questTypeIcon(q.type)}</span>
                      <span style={questTitleStyle}>{q.title}</span>
                      <span
                        style={{
                          ...progressTextStyle,
                          color: isCompleted ? '#ffd700' : '#aaa',
                        }}
                      >
                        {q.progress}/{q.targetCount}
                      </span>
                    </div>

                    {/* Progress bar */}
                    <div style={progressBarOuter}>
                      <div
                        style={{
                          height: '100%',
                          width: `${pct}%`,
                          borderRadius: 3,
                          backgroundColor: isCompleted ? '#ffd700' : '#4a90d9',
                          transition: 'width 300ms ease',
                        }}
                      />
                    </div>

                    {/* Expanded details */}
                    {isExpanded && (
                      <>
                        <div style={descriptionStyle}>{q.description}</div>
                        <div style={{ ...descriptionStyle, color: '#777', fontSize: 10 }}>
                          {q.npcName} &middot; {q.townName}
                        </div>
                        <div style={rewardsRow}>
                          {q.rewardXp > 0 && (
                            <span style={{ ...rewardChip, color: '#44aaff' }}>
                              {'\u2728'} {q.rewardXp} XP
                            </span>
                          )}
                          {q.rewardGold > 0 && (
                            <span style={{ ...rewardChip, color: '#ffd700' }}>
                              {'\uD83D\uDCB0'} {q.rewardGold}
                            </span>
                          )}
                          {q.rewardPotions > 0 && (
                            <span style={{ ...rewardChip, color: '#88dd88' }}>
                              {'\uD83E\uDDEA'} {q.rewardPotions}
                            </span>
                          )}
                        </div>
                        <div style={actionRow}>
                          {isCompleted ? (
                            <button
                              style={claimBtnStyle}
                              onClick={(e) => {
                                e.stopPropagation();
                                onClaim(q.id);
                              }}
                            >
                              {tr.claimRewards}
                            </button>
                          ) : (
                            <button
                              style={abandonBtnStyle}
                              onClick={(e) => {
                                e.stopPropagation();
                                onAbandon(q.id);
                              }}
                            >
                              {tr.abandon}
                            </button>
                          )}
                        </div>
                      </>
                    )}
                  </div>
                );
              })
            )}
      </div>
    </>
  );
}

export function QuestLog({ quests, onClaim, onAbandon, onClose }: QuestLogProps) {
  const tr = useT();
  useEffect(() => {
    const handleKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', handleKey);
    return () => window.removeEventListener('keydown', handleKey);
  }, [onClose]);

  return (
    <>
      <style>{`
        @keyframes quest-log-slide-up {
          0%   { transform: translateY(100%); }
          100% { transform: translateY(0); }
        }
      `}</style>
      <div style={overlayStyle}>
        <div style={backdropStyle} onClick={onClose} />
        <div style={panelStyle}>
          <div style={headerStyle}>
            <span style={titleStyle}>{'\uD83D\uDCDC'} {tr.questLog}</span>
            <button style={closeBtnStyle} onClick={onClose}>{'\u2715'}</button>
          </div>
          <QuestLogList quests={quests} onClaim={onClaim} onAbandon={onAbandon} />
        </div>
      </div>
    </>
  );
}
