import { useState } from "react";
import { ChevronDown, ChevronRight } from "lucide-react";
import { useNavigate } from "react-router-dom";
import type { QuestNode, QuestArc } from "../types/quest";
import { CREW_RANKS } from "../types/quest";
import {
  useQuestStore,
  getQuestSummary,
  getCrewRank,
} from "../stores/useQuestStore";
import { ChestOpenModal } from "./ChestOpenModal";

// ─── Styles ───────────────────────────────────────────────────────────────────
const STYLES = `
  @import url('https://fonts.googleapis.com/css2?family=Cinzel:wght@600;700;900&family=Sorts+Mill+Goudy:ital@0;1&family=Nunito:wght@700;800;900&family=Nunito+Sans:wght@400;600;700&display=swap');

  /* ══ CARD SHELL ══ */
  .qpc2-card {
    position: relative; overflow: hidden;
    border-radius: 24px;
    background: linear-gradient(160deg, #0b1a35 0%, #060e1f 55%, #0d1530 100%);
    border: 1.5px solid rgba(251,191,36,0.2);
    box-shadow:
      0 8px 32px rgba(0,0,0,0.35),
      0 0 0 1px rgba(255,255,255,0.04) inset,
      0 1px 0 rgba(255,255,255,0.08) inset;
  }

  /* Animated sea shimmer behind everything */
  .qpc2-sea {
    position: absolute; inset: 0; pointer-events: none; z-index: 0;
    background:
      repeating-linear-gradient(105deg, transparent 0%, transparent 55%,
        rgba(56,189,248,0.022) 56%, transparent 57%),
      repeating-linear-gradient(75deg, transparent 0%, transparent 70%,
        rgba(56,189,248,0.014) 71%, transparent 72%);
    background-size: 300% 300%, 250% 250%;
    animation: qpc2Sea 12s ease-in-out infinite alternate;
  }
  @keyframes qpc2Sea {
    0%   { background-position: 0% 0%, 100% 0%; }
    100% { background-position: 100% 100%, 0% 100%; }
  }

  /* Faint gold orb top-right */
  .qpc2-orb {
    position: absolute; top: -40px; right: -30px;
    width: 160px; height: 160px; border-radius: 50%;
    background: radial-gradient(circle, rgba(251,191,36,0.14) 0%, transparent 70%);
    pointer-events: none; z-index: 0;
  }

  /* ══ RANK HERO (always visible) ══ */
  .qpc2-hero {
    position: relative; z-index: 2;
    padding: 1rem 1.1rem 0.9rem;
    cursor: pointer;
    transition: background 0.18s ease;
  }
  .qpc2-hero:hover { background: rgba(255,255,255,0.025); }

  .qpc2-hero-row {
    display: flex; align-items: center; justify-content: space-between; gap: 0.75rem;
  }
  .qpc2-hero-left  { display: flex; align-items: center; gap: 0.75rem; flex: 1; min-width: 0; }
  .qpc2-hero-right { display: flex; align-items: center; gap: 0.5rem; flex-shrink: 0; }

  /* Rank badge icon */
  .qpc2-rank-icon {
    width: 44px; height: 44px; border-radius: 14px; flex-shrink: 0;
    background: linear-gradient(135deg, #1e0e4a, #3730a3);
    border: 1.5px solid rgba(251,191,36,0.35);
    display: flex; align-items: center; justify-content: center;
    font-size: 1.35rem;
    box-shadow: 0 4px 0 rgba(30,14,74,0.7), 0 0 16px rgba(251,191,36,0.1);
  }

  .qpc2-rank-label {
    font-family: 'Cinzel', serif;
    font-size: 0.78rem; font-weight: 700;
    color: rgba(255,255,255,0.45); letter-spacing: 0.12em;
    text-transform: uppercase; margin-bottom: 0.1rem;
  }
  .qpc2-rank-name {
    font-family: 'Sorts Mill Goudy', serif;
    font-size: 1.05rem; font-weight: 700;
    color: #fbbf24;
    text-shadow: 0 0 18px rgba(251,191,36,0.45);
    line-height: 1.1;
  }

  /* Rank progress bar */
  .qpc2-rank-bar-wrap {
    margin-top: 0.55rem;
    display: flex; align-items: center; gap: 0.6rem;
  }
  .qpc2-rank-bar-track {
    flex: 1; height: 5px; border-radius: 100px;
    background: rgba(255,255,255,0.1); overflow: hidden;
  }
  .qpc2-rank-bar-fill {
    height: 100%; border-radius: 100px;
    background: linear-gradient(90deg, #fbbf24, #f59e0b);
    box-shadow: 0 0 8px rgba(251,191,36,0.5);
    transition: width 0.7s cubic-bezier(0.34,1.56,0.64,1);
  }
  .qpc2-rank-bar-label {
    font-family: 'Nunito Sans', sans-serif;
    font-size: 0.6rem; font-weight: 700;
    color: rgba(255,255,255,0.35); white-space: nowrap;
  }

  /* Stats row */
  .qpc2-stats {
    display: flex; gap: 0.5rem; margin-top: 0.75rem;
    padding-top: 0.7rem;
    border-top: 1px solid rgba(255,255,255,0.07);
  }
  .qpc2-stat {
    flex: 1; display: flex; flex-direction: column; align-items: center; gap: 0.1rem;
  }
  .qpc2-stat-val {
    font-family: 'Nunito', sans-serif;
    font-size: 0.95rem; font-weight: 900; color: #fbbf24;
  }
  .qpc2-stat-lbl {
    font-family: 'Nunito Sans', sans-serif;
    font-size: 0.56rem; font-weight: 700;
    color: rgba(255,255,255,0.35); text-align: center;
    letter-spacing: 0.06em; text-transform: uppercase;
  }
  .qpc2-stat-div {
    width: 1px; background: rgba(255,255,255,0.08); margin: 0.1rem 0;
  }

  /* Chest badge */
  .qpc2-chest-badge {
    display: flex; align-items: center; gap: 0.22rem;
    padding: 0.22rem 0.6rem;
    background: linear-gradient(135deg, #fbbf24, #f59e0b);
    border-radius: 100px;
    font-family: 'Nunito', sans-serif;
    font-size: 0.65rem; font-weight: 900; color: #1a0800;
    box-shadow: 0 2px 0 #d97706, 0 0 10px rgba(251,191,36,0.35);
    animation: qpc2ChestPop 1.8s ease-in-out infinite;
  }
  @keyframes qpc2ChestPop {
    0%,100%{ transform: scale(1); }
    50%    { transform: scale(1.07); }
  }

  /* Expand chevron */
  .qpc2-chevron {
    color: rgba(255,255,255,0.35);
    transition: transform 0.3s cubic-bezier(0.34,1.56,0.64,1), color 0.2s;
  }
  .qpc2-chevron.open { transform: rotate(180deg); color: #fbbf24; }

  /* ══ COLLAPSIBLE BODY ══ */
  .qpc2-body {
    position: relative; z-index: 2;
    overflow: hidden;
    max-height: 0;
    transition: max-height 0.4s cubic-bezier(0.4,0,0.2,1);
  }
  .qpc2-body.open { max-height: 600px; }

  .qpc2-divider {
    height: 1px; background: rgba(255,255,255,0.07); margin: 0 1.1rem;
  }

  /* ══ QUEST ROWS ══ */
  .qpc2-quest-list { display: flex; flex-direction: column; padding: 0.5rem 0; }

  .qpc2-quest-row {
    display: flex; align-items: center; gap: 0.7rem;
    padding: 0.75rem 1.1rem;
    cursor: pointer;
    transition: background 0.15s ease;
    position: relative;
  }
  .qpc2-quest-row:hover { background: rgba(255,255,255,0.03); }

  /* Left accent line = arc colour */
  .qpc2-quest-row::before {
    content: ''; position: absolute; left: 0; top: 16%; bottom: 16%;
    width: 3px; border-radius: 0 3px 3px 0;
    background: var(--ac);
    opacity: 0.7;
  }

  .qpc2-quest-icon {
    width: 38px; height: 38px; border-radius: 12px; flex-shrink: 0;
    display: flex; align-items: center; justify-content: center;
    font-size: 1.2rem;
    background: rgba(255,255,255,0.05);
    border: 1.5px solid rgba(255,255,255,0.08);
    transition: transform 0.2s ease;
  }
  .qpc2-quest-row:hover .qpc2-quest-icon { transform: scale(1.1) rotate(-5deg); }
  .qpc2-quest-icon.claimable {
    background: rgba(251,191,36,0.12);
    border-color: rgba(251,191,36,0.4);
    animation: qpc2Wiggle 2s ease-in-out infinite;
  }
  @keyframes qpc2Wiggle {
    0%,100%{ transform: rotate(0deg); }
    25%    { transform: rotate(-8deg) scale(1.06); }
    75%    { transform: rotate(8deg) scale(1.06); }
  }

  .qpc2-quest-body { flex: 1; min-width: 0; }
  .qpc2-quest-arc {
    font-size: 0.57rem; font-weight: 800; letter-spacing: 0.12em;
    text-transform: uppercase; color: var(--ac);
    margin-bottom: 0.08rem;
  }
  .qpc2-quest-title {
    font-family: 'Sorts Mill Goudy', serif;
    font-size: 0.82rem; font-weight: 700; color: rgba(255,255,255,0.9);
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    margin-bottom: 0.28rem;
  }
  .qpc2-mini-track {
    height: 4px; background: rgba(255,255,255,0.08);
    border-radius: 100px; overflow: hidden; margin-bottom: 0.18rem;
  }
  .qpc2-mini-fill {
    height: 100%; border-radius: 100px;
    background: var(--ac);
    box-shadow: 0 0 5px color-mix(in srgb, var(--ac) 55%, transparent);
    transition: width 0.5s cubic-bezier(0.34,1.56,0.64,1);
  }
  .qpc2-mini-label {
    font-family: 'Nunito Sans', sans-serif;
    font-size: 0.58rem; font-weight: 700; color: rgba(255,255,255,0.3);
  }
  .qpc2-claimable-label {
    font-family: 'Nunito Sans', sans-serif;
    font-size: 0.62rem; font-weight: 700; color: #fbbf24;
  }

  /* Claim button */
  .qpc2-claim-btn {
    padding: 0.32rem 0.7rem; border: none; border-radius: 100px; cursor: pointer;
    background: linear-gradient(135deg, #fbbf24, #f59e0b);
    font-family: 'Nunito', sans-serif;
    font-size: 0.65rem; font-weight: 900; color: #1a0800;
    box-shadow: 0 2px 0 #d97706, 0 3px 8px rgba(251,191,36,0.25);
    flex-shrink: 0; white-space: nowrap;
    transition: all 0.12s ease;
  }
  .qpc2-claim-btn:hover  { transform: translateY(-1px); box-shadow: 0 3px 0 #d97706; }
  .qpc2-claim-btn:active { transform: translateY(1px); }

  /* ══ FOOTER LINK ══ */
  .qpc2-footer {
    position: relative; z-index: 2;
    display: flex; align-items: center; justify-content: center; gap: 0.3rem;
    padding: 0.65rem 1.1rem;
    border-top: 1px solid rgba(255,255,255,0.07);
    cursor: pointer;
    transition: background 0.15s ease;
  }
  .qpc2-footer:hover { background: rgba(255,255,255,0.03); }
  .qpc2-footer-label {
    font-family: 'Nunito', sans-serif;
    font-size: 0.72rem; font-weight: 800;
    color: rgba(251,191,36,0.7);
    letter-spacing: 0.04em;
  }
  .qpc2-footer:hover .qpc2-footer-label { color: #fbbf24; }

  /* ══ EMPTY STATE ══ */
  .qpc2-empty {
    padding: 1.25rem 1.1rem; text-align: center;
    display: flex; flex-direction: column; align-items: center; gap: 0.35rem;
  }
  .qpc2-empty-title {
    font-family: 'Sorts Mill Goudy', serif;
    font-size: 0.88rem; font-weight: 700; color: rgba(255,255,255,0.55);
  }
  .qpc2-empty-sub {
    font-family: 'Nunito Sans', sans-serif;
    font-size: 0.68rem; font-weight: 600; color: rgba(255,255,255,0.25);
  }
`;

// ─── Helpers ──────────────────────────────────────────────────────────────────
function getActiveQuests(arcs: QuestArc[]) {
  const results: { node: QuestNode; arc: QuestArc }[] = [];
  for (const arc of arcs) {
    for (const node of arc.nodes) {
      if (node.status === "claimable" || node.status === "active") {
        results.push({ node, arc });
      }
    }
  }
  // Claimable first, then active; max 2 shown
  results.sort((a, b) => {
    if (a.node.status === "claimable" && b.node.status !== "claimable")
      return -1;
    if (b.node.status === "claimable" && a.node.status !== "claimable")
      return 1;
    return 0;
  });
  return results.slice(0, 2);
}

// ─── Component ────────────────────────────────────────────────────────────────
interface Props {
  onViewAll?: () => void;
}

export const QuestProgressCard = ({ onViewAll }: Props) => {
  const navigate = useNavigate();
  const arcs = useQuestStore((s) => s.arcs);
  const claimNode = useQuestStore((s) => s.claimNode);

  const summary = getQuestSummary(arcs);
  const rank = getCrewRank(arcs);
  const activeQuests = getActiveQuests(arcs);

  const [open, setOpen] = useState(false);
  const [claimingNode, setClaimingNode] = useState<{
    node: QuestNode;
    arcId: string;
  } | null>(null);

  const handleViewAll = () => {
    if (onViewAll) onViewAll();
    else navigate("/student/quests");
  };

  const handleClaim = (node: QuestNode, arcId: string) => {
    setClaimingNode({ node, arcId });
  };

  const handleChestClose = () => {
    if (!claimingNode) return;
    claimNode(claimingNode.arcId, claimingNode.node.id);
    setClaimingNode(null);
  };

  // Next rank label
  const nextRankLabel = rank.next
    ? `${Math.round(rank.progressToNext * 100)}% to ${rank.next.label}`
    : "Max rank reached";

  return (
    <>
      <style>{STYLES}</style>

      <div className="qpc2-card">
        {/* Atmosphere layers */}
        <div className="qpc2-sea" />
        <div className="qpc2-orb" />

        {/* ── Rank hero (always visible, tap to expand) ── */}
        <div className="qpc2-hero" onClick={() => setOpen((o) => !o)}>
          <div className="qpc2-hero-row">
            <div className="qpc2-hero-left">
              <div className="qpc2-rank-icon">{rank.emoji}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <p className="qpc2-rank-label">Crew Rank</p>
                <p className="qpc2-rank-name">{rank.label}</p>
              </div>
            </div>
            <div className="qpc2-hero-right">
              {summary.claimableNodes > 0 && (
                <div className="qpc2-chest-badge">
                  📦 {summary.claimableNodes}
                </div>
              )}
              <ChevronDown
                size={18}
                className={`qpc2-chevron${open ? " open" : ""}`}
              />
            </div>
          </div>

          {/* Rank progress bar */}
          <div className="qpc2-rank-bar-wrap">
            <div className="qpc2-rank-bar-track">
              <div
                className="qpc2-rank-bar-fill"
                style={{ width: `${Math.round(rank.progressToNext * 100)}%` }}
              />
            </div>
            <span className="qpc2-rank-bar-label">{nextRankLabel}</span>
          </div>

          {/* Stats strip */}
          <div className="qpc2-stats">
            {[
              { val: `${summary.earnedXP}`, lbl: "XP Earned" },
              null,
              {
                val: `${summary.completedNodes}/${summary.totalNodes}`,
                lbl: "Quests Done",
              },
              null,
              {
                val: `${summary.arcsCompleted}/${summary.totalArcs}`,
                lbl: "Arcs",
              },
            ].map((item, i) =>
              item === null ? (
                <div key={i} className="qpc2-stat-div" />
              ) : (
                <div key={i} className="qpc2-stat">
                  <span className="qpc2-stat-val">{item.val}</span>
                  <span className="qpc2-stat-lbl">{item.lbl}</span>
                </div>
              ),
            )}
          </div>
        </div>

        {/* ── Collapsible quest list ── */}
        <div className={`qpc2-body${open ? " open" : ""}`}>
          <div className="qpc2-divider" />
          <div className="qpc2-quest-list">
            {activeQuests.length === 0 ? (
              <div className="qpc2-empty">
                <span style={{ fontSize: "1.75rem" }}>⚓</span>
                <p className="qpc2-empty-title">All caught up, Captain!</p>
                <p className="qpc2-empty-sub">
                  No active quests — keep sailing
                </p>
              </div>
            ) : (
              activeQuests.map(({ node, arc }) => {
                const pct = Math.min(
                  100,
                  Math.round((node.progress / node.requirement.target) * 100),
                );
                const isClaimable = node.status === "claimable";
                return (
                  <div
                    key={node.id}
                    className="qpc2-quest-row"
                    style={{ "--ac": arc.accentColor } as React.CSSProperties}
                    onClick={() => !isClaimable && handleViewAll()}
                  >
                    <div
                      className={`qpc2-quest-icon${isClaimable ? " claimable" : ""}`}
                    >
                      {isClaimable ? "📦" : node.emoji}
                    </div>
                    <div className="qpc2-quest-body">
                      <p className="qpc2-quest-arc">
                        {arc.emoji} {arc.name}
                      </p>
                      <p className="qpc2-quest-title">{node.title}</p>
                      {isClaimable ? (
                        <p className="qpc2-claimable-label">
                          ✨ Chest ready to open!
                        </p>
                      ) : (
                        <>
                          <div className="qpc2-mini-track">
                            <div
                              className="qpc2-mini-fill"
                              style={{ width: `${pct}%` }}
                            />
                          </div>
                          <p className="qpc2-mini-label">
                            {node.progress} / {node.requirement.target}{" "}
                            {node.requirement.label}
                          </p>
                        </>
                      )}
                    </div>
                    {isClaimable ? (
                      <button
                        className="qpc2-claim-btn"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleClaim(node, arc.id);
                        }}
                      >
                        Open 📦
                      </button>
                    ) : (
                      <ChevronRight size={14} color="rgba(255,255,255,0.2)" />
                    )}
                  </div>
                );
              })
            )}
          </div>

          {/* Footer — navigate to full map */}
          <div className="qpc2-footer" onClick={handleViewAll}>
            <span className="qpc2-footer-label">View full quest map</span>
            <ChevronRight size={14} color="rgba(251,191,36,0.7)" />
          </div>
        </div>
      </div>

      {claimingNode && (
        <ChestOpenModal node={claimingNode.node} onClose={handleChestClose} />
      )}
    </>
  );
};
