import { useState, useEffect, useCallback, type CSSProperties } from 'react';
import type { NPC, Quest, HeroQuest } from '../game/types';
import { getNPCQuests, acceptQuest, claimQuest, buyPotion, healAtNPC } from '../network/api';
import type { HeroResponse } from '../network/api';
import { getTelegramUserId } from '../shared/telegram';
import { hapticImpact } from '../shared/telegram';
import { useT, t } from '../i18n';

// ---- Types ----

interface NPCDialogProps {
  npc: NPC;
  heroQuests: HeroQuest[];
  heroGold: number;
  onClose: () => void;
  onQuestsChanged: () => void;
  onHeroUpdated: (hero: HeroResponse) => void;
  onToast: (message: string, color: string) => void;
}

// ---- Styles ----

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

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

const dialogStyle: CSSProperties = {
  position: 'absolute',
  bottom: 0,
  left: 0,
  right: 0,
  maxHeight: '55vh',
  backgroundColor: 'rgba(15, 15, 25, 0.96)',
  borderTop: '2px solid rgba(255, 215, 0, 0.35)',
  borderRadius: '16px 16px 0 0',
  display: 'flex',
  flexDirection: 'column',
  animation: 'npc-dialog-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 npcNameStyle: CSSProperties = {
  fontSize: 15,
  fontWeight: 700,
  color: '#e8e8e8',
};

const npcTypeTag: CSSProperties = {
  fontSize: 10,
  fontWeight: 600,
  color: '#999',
  textTransform: 'uppercase',
  letterSpacing: 0.5,
  marginLeft: 8,
};

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

const bodyStyle: CSSProperties = {
  overflowY: 'auto',
  padding: '10px 14px 18px',
  flex: 1,
};

const sectionTitleStyle: CSSProperties = {
  fontSize: 11,
  fontWeight: 700,
  color: '#888',
  textTransform: 'uppercase',
  letterSpacing: 0.5,
  marginTop: 10,
  marginBottom: 6,
};

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,
};

const questTitleRow: CSSProperties = {
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'space-between',
  gap: 8,
};

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

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

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

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

const acceptBtnStyle: CSSProperties = {
  marginTop: 8,
  width: '100%',
  padding: '8px 0',
  border: 'none',
  borderRadius: 8,
  backgroundColor: 'rgba(68, 170, 255, 0.25)',
  color: '#66bbff',
  fontSize: 12,
  fontWeight: 700,
  cursor: 'pointer',
  transition: 'background-color 150ms ease',
};

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

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

const serviceBtnStyle: CSSProperties = {
  width: '100%',
  padding: '12px 0',
  border: 'none',
  borderRadius: 10,
  fontSize: 14,
  fontWeight: 700,
  cursor: 'pointer',
  marginBottom: 8,
  transition: 'background-color 150ms ease',
};

const disabledBtnStyle: CSSProperties = {
  ...serviceBtnStyle,
  opacity: 0.4,
  cursor: 'default',
};

// ---- NPC Type Info ----

function npcTypeIcon(type: string): string {
  switch (type) {
    case 'quest_giver':
      return '\u2753'; // question mark
    case 'merchant':
      return '\uD83D\uDCB0'; // money bag
    case 'healer':
      return '\u2764\uFE0F'; // heart
    default:
      return '\uD83D\uDDE3\uFE0F'; // speaking
  }
}

function npcTypeLabel(type: string, tr: ReturnType<typeof useT>): string {
  switch (type) {
    case 'quest_giver': return tr.questGiver;
    case 'merchant': return tr.merchant;
    case 'healer': return tr.healer;
    default: return tr.npc;
  }
}

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

// ---- Constants ----

const POTION_COST = 50;
const HEAL_COST = 30;

// ---- Component ----

export function NPCDialog({
  npc,
  heroQuests,
  heroGold,
  onClose,
  onQuestsChanged,
  onHeroUpdated,
  onToast,
}: NPCDialogProps) {
  const tr = useT();
  const [availableQuests, setAvailableQuests] = useState<Quest[]>([]);
  const [loading, setLoading] = useState(false);

  const telegramId = getTelegramUserId() ?? 1;

  // Fetch available quests for quest giver NPCs
  useEffect(() => {
    if (npc.type !== 'quest_giver') return;
    setLoading(true);
    getNPCQuests(npc.id, telegramId)
      .then((qs) => setAvailableQuests(qs))
      .catch((err) => {
        console.warn('[NPCDialog] Failed to fetch quests:', err);
        setAvailableQuests([]);
      })
      .finally(() => setLoading(false));
  }, [npc.id, npc.type, telegramId]);

  // Close on Escape
  useEffect(() => {
    const handleKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', handleKey);
    return () => window.removeEventListener('keydown', handleKey);
  }, [onClose]);

  const handleAcceptQuest = useCallback(
    (questId: number) => {
      acceptQuest(questId, telegramId)
        .then(() => {
          hapticImpact('medium');
          onToast(tr.questAccepted, '#44aaff');
          onQuestsChanged();
          // Remove from available list
          setAvailableQuests((prev) => prev.filter((q) => q.id !== questId));
        })
        .catch((err) => {
          console.warn('[NPCDialog] Failed to accept quest:', err);
          onToast(tr.failedToAcceptQuest, '#ff4444');
        });
    },
    [telegramId, onQuestsChanged, onToast],
  );

  const handleClaimQuest = useCallback(
    (heroQuestId: number) => {
      claimQuest(heroQuestId, telegramId)
        .then((hero) => {
          hapticImpact('heavy');
          onToast(tr.questRewardsClaimed, '#ffd700');
          onHeroUpdated(hero);
          onQuestsChanged();
        })
        .catch((err) => {
          console.warn('[NPCDialog] Failed to claim quest:', err);
          onToast(tr.failedToClaimRewards, '#ff4444');
        });
    },
    [telegramId, onQuestsChanged, onHeroUpdated, onToast],
  );

  const handleBuyPotion = useCallback(() => {
    if (heroGold < POTION_COST) {
      onToast(tr.notEnoughGold, '#ff4444');
      return;
    }
    buyPotion(telegramId)
      .then((hero) => {
        hapticImpact('medium');
        onToast(t(tr.boughtPotion, { cost: POTION_COST }), '#88dd88');
        onHeroUpdated(hero);
      })
      .catch((err) => {
        console.warn('[NPCDialog] Failed to buy potion:', err);
        onToast(tr.failedToBuyPotion, '#ff4444');
      });
  }, [telegramId, heroGold, onHeroUpdated, onToast]);

  const handleHeal = useCallback(() => {
    if (heroGold < HEAL_COST) {
      onToast(tr.notEnoughGold, '#ff4444');
      return;
    }
    healAtNPC(telegramId)
      .then((hero) => {
        hapticImpact('medium');
        onToast(tr.healedToFull, '#44cc44');
        onHeroUpdated(hero);
      })
      .catch((err) => {
        console.warn('[NPCDialog] Failed to heal:', err);
        onToast(tr.failedToHeal, '#ff4444');
      });
  }, [telegramId, heroGold, onHeroUpdated, onToast]);

  // Quests relevant to this NPC
  const npcHeroQuests = heroQuests.filter(
    (hq) => hq.status !== 'claimed',
  );
  // Filter to quests from this NPC based on npcName matching
  const npcInProgressQuests = npcHeroQuests.filter(
    (hq) => hq.npcName === npc.name && hq.status === 'accepted',
  );
  const npcCompletedQuests = npcHeroQuests.filter(
    (hq) => hq.npcName === npc.name && hq.status === 'completed',
  );

  return (
    <>
      <style>{`
        @keyframes npc-dialog-slide-up {
          0%   { transform: translateY(100%); }
          100% { transform: translateY(0); }
        }
        @keyframes npc-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={overlayStyle}>
        <div style={backdropStyle} onClick={onClose} />
        <div style={dialogStyle}>
          {/* Header */}
          <div style={headerStyle}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <span style={{ fontSize: 18, marginRight: 8 }}>{npcTypeIcon(npc.type)}</span>
              <span style={npcNameStyle}>{npc.name}</span>
              <span style={npcTypeTag}>{npcTypeLabel(npc.type, tr)}</span>
            </div>
            <button style={closeBtnStyle} onClick={onClose}>{'\u2715'}</button>
          </div>

          {/* Body */}
          <div style={bodyStyle}>
            {/* ---- Quest Giver ---- */}
            {npc.type === 'quest_giver' && (
              <>
                {/* Completed quests — claim first */}
                {npcCompletedQuests.length > 0 && (
                  <>
                    <div style={sectionTitleStyle}>{tr.completed}</div>
                    {npcCompletedQuests.map((hq) => (
                      <div
                        key={hq.id}
                        style={{
                          ...questCardStyle,
                          borderColor: 'rgba(255, 215, 0, 0.3)',
                        }}
                      >
                        <div style={questTitleRow}>
                          <span style={{ fontSize: 14 }}>{questTypeIcon(hq.type)}</span>
                          <span style={questTitleText}>{hq.title}</span>
                          <span style={{ fontSize: 11, fontWeight: 700, color: '#ffd700' }}>
                            {hq.progress}/{hq.targetCount}
                          </span>
                        </div>
                        <div style={rewardsRow}>
                          {hq.rewardXp > 0 && (
                            <span style={{ ...rewardChip, color: '#44aaff' }}>
                              {'\u2728'} {hq.rewardXp} XP
                            </span>
                          )}
                          {hq.rewardGold > 0 && (
                            <span style={{ ...rewardChip, color: '#ffd700' }}>
                              {'\uD83D\uDCB0'} {hq.rewardGold}
                            </span>
                          )}
                          {hq.rewardPotions > 0 && (
                            <span style={{ ...rewardChip, color: '#88dd88' }}>
                              {'\uD83E\uDDEA'} {hq.rewardPotions}
                            </span>
                          )}
                        </div>
                        <button
                          style={claimBtnStyle}
                          onClick={() => handleClaimQuest(hq.id)}
                        >
                          {tr.claimRewards}
                        </button>
                      </div>
                    ))}
                  </>
                )}

                {/* In-progress quests */}
                {npcInProgressQuests.length > 0 && (
                  <>
                    <div style={sectionTitleStyle}>In Progress</div>
                    {npcInProgressQuests.map((hq) => {
                      const pct = hq.targetCount > 0
                        ? Math.min(100, (hq.progress / hq.targetCount) * 100)
                        : 0;
                      return (
                        <div key={hq.id} style={questCardStyle}>
                          <div style={questTitleRow}>
                            <span style={{ fontSize: 14 }}>{questTypeIcon(hq.type)}</span>
                            <span style={questTitleText}>{hq.title}</span>
                            <span style={{ fontSize: 11, fontWeight: 700, color: '#aaa' }}>
                              {hq.progress}/{hq.targetCount}
                            </span>
                          </div>
                          <div style={progressBarOuter}>
                            <div
                              style={{
                                height: '100%',
                                width: `${pct}%`,
                                borderRadius: 3,
                                backgroundColor: '#4a90d9',
                                transition: 'width 300ms ease',
                              }}
                            />
                          </div>
                        </div>
                      );
                    })}
                  </>
                )}

                {/* Available quests */}
                {loading ? (
                  <div style={{ color: '#666', fontSize: 12, textAlign: 'center', padding: 16 }}>
                    Loading quests...
                  </div>
                ) : availableQuests.length > 0 ? (
                  <>
                    <div style={sectionTitleStyle}>Available Quests</div>
                    {availableQuests.map((q) => (
                      <div key={q.id} style={questCardStyle}>
                        <div style={questTitleRow}>
                          <span style={{ fontSize: 14 }}>{questTypeIcon(q.type)}</span>
                          <span style={questTitleText}>{q.title}</span>
                        </div>
                        <div style={questDescStyle}>{q.description}</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>
                        <button
                          style={acceptBtnStyle}
                          onClick={() => handleAcceptQuest(q.id)}
                        >
                          {tr.acceptQuest}
                        </button>
                      </div>
                    ))}
                  </>
                ) : (
                  npcInProgressQuests.length === 0 &&
                  npcCompletedQuests.length === 0 && (
                    <div style={{ color: '#666', fontSize: 12, textAlign: 'center', padding: 16 }}>
                      No quests available right now.
                    </div>
                  )
                )}
              </>
            )}

            {/* ---- Merchant ---- */}
            {npc.type === 'merchant' && (
              <>
                <div style={sectionTitleStyle}>Shop</div>
                <button
                  style={
                    heroGold >= POTION_COST
                      ? { ...serviceBtnStyle, backgroundColor: 'rgba(68, 200, 68, 0.2)', color: '#88dd88' }
                      : { ...disabledBtnStyle, backgroundColor: 'rgba(68, 200, 68, 0.1)', color: '#88dd88' }
                  }
                  onClick={handleBuyPotion}
                  disabled={heroGold < POTION_COST}
                >
                  {'\uD83E\uDDEA'} {tr.buyPotion} &mdash; {POTION_COST} {tr.gold}
                </button>
                <div style={{ fontSize: 11, color: '#666', textAlign: 'center' }}>
                  Your gold: {heroGold}
                </div>
              </>
            )}

            {/* ---- Healer ---- */}
            {npc.type === 'healer' && (
              <>
                <div style={sectionTitleStyle}>Services</div>
                <button
                  style={
                    heroGold >= HEAL_COST
                      ? { ...serviceBtnStyle, backgroundColor: 'rgba(200, 68, 68, 0.2)', color: '#ff8888' }
                      : { ...disabledBtnStyle, backgroundColor: 'rgba(200, 68, 68, 0.1)', color: '#ff8888' }
                  }
                  onClick={handleHeal}
                  disabled={heroGold < HEAL_COST}
                >
                  {'\u2764\uFE0F'} {tr.healToFull} &mdash; {HEAL_COST} {tr.gold}
                </button>
                <div style={{ fontSize: 11, color: '#666', textAlign: 'center' }}>
                  Your gold: {heroGold}
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </>
  );
}
