import { useEffect, useRef, useState } from "react";
import { AppIcon } from "./PixelIcons";
import SkillCoachChat from "./SkillCoachChat";
import SkillDrillHistory from "./SkillDrillHistory";
import SkillDrillPanel from "./SkillDrillPanel";
import SkillNotesPanel from "./SkillNotesPanel";
import { hasCardNotesInIndex, type SkillNotesIndex } from "../lib/skillCardNotes";
import { Tag } from "./ui";
import {
  masteryLabel,
  parsePrincipleCard,
  RARITY_LABEL,
  type DrillMistakeBook,
  type SkillProgressMap,
  type SkillTreeNode,
} from "../lib/skillTree";
import type { AIFocus } from "../lib/ai";

type SkillTab = "detail" | "drill" | "records" | "coach" | "notes";

export default function SkillCardPanel({
  node,
  progress,
  onClose,
  onProgressChange,
  onMistakeBookChange,
  onNotesChange,
  onAttemptRecorded,
  historyRevision = 0,
  hasOpenMistake = false,
  notesIndex = {},
  onNotesIndexChange,
  initialTab = "detail",
}: {
  node: SkillTreeNode | null;
  progress: SkillProgressMap;
  onClose: () => void;
  onProgressChange: (map: SkillProgressMap) => void;
  onMistakeBookChange?: (book: DrillMistakeBook) => void;
  onNotesChange?: () => void;
  onAttemptRecorded?: () => void;
  historyRevision?: number;
  hasOpenMistake?: boolean;
  notesIndex?: SkillNotesIndex;
  onNotesIndexChange?: (index: SkillNotesIndex) => void;
  initialTab?: SkillTab;
}) {
  const open = !!node;
  const card = node ? parsePrincipleCard(node) : null;
  const entry = node ? progress[node.principle.id] : undefined;
  const [tab, setTab] = useState<SkillTab>("detail");
  const [coachAutoSendToken, setCoachAutoSendToken] = useState(0);
  const [notesTick, setNotesTick] = useState(0);
  const onCloseRef = useRef(onClose);

  useEffect(() => {
    onCloseRef.current = onClose;
  }, [onClose]);

  useEffect(() => {
    if (!open) return;
    setTab(initialTab);
    setCoachAutoSendToken(0);
  }, [open, node?.principle.id, initialTab]);

  useEffect(() => {
    if (!open) return;
    document.body.classList.add("skill-modal-open");
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onCloseRef.current();
    };
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.classList.remove("skill-modal-open");
    };
  }, [open]);

  if (!open || !node || !card) return null;

  void notesTick;
  const hasNotes = hasCardNotesInIndex(notesIndex, node.principle.id);

  const aiPrompt = `請用白話解釋這條投資心法，並舉一個我能記得的判斷情境（教學用，非投資建議）：\n「${node.principle.title}」\n\n機制摘要：${card.mechanism || "（見正文）"}`;
  const coachContextHint = [
    node.principle.title,
    card.mechanism,
    card.triggers.length ? `觸發：${card.triggers.slice(0, 4).join("；")}` : "",
    card.quote ? `引述：${card.quote}` : "",
  ]
    .filter(Boolean)
    .join("\n");

  const aiFocus: AIFocus = {
    cardTitle: card.cleanTitle,
    label: card.label,
    tab: "skills",
    principleId: node.principle.id,
  };

  const openCoach = (autoSend = false) => {
    setTab("coach");
    if (autoSend) setCoachAutoSendToken((t) => t + 1);
  };

  return (
    <div className="skill-modal" role="dialog" aria-modal="true" aria-labelledby="skill-card-title">
      <button type="button" className="skill-modal-backdrop" aria-label="關閉心法卡" onClick={onClose} />
      <div
        className={[
          "skill-modal-panel",
          "skill-modal-panel--tabbed",
          tab === "coach" ? "skill-modal-panel--coach" : "",
          `rar-${card.rarity}`,
        ]
          .filter(Boolean)
          .join(" ")}
      >
        <div className="skill-modal-banner" aria-hidden>
          <AppIcon name={node.artIcon} size={32} framed glow variant="hero" />
        </div>
        <div className="skill-modal-head">
          <AppIcon name={node.artIcon} size={26} framed variant="hero" />
          <strong>心法卡</strong>
          <div className="skill-modal-tabs" role="tablist" aria-label="心法卡分頁">
            <button
              type="button"
              role="tab"
              aria-selected={tab === "detail"}
              className={"skill-modal-tab" + (tab === "detail" ? " active" : "")}
              onClick={() => setTab("detail")}
            >
              心法詳情
            </button>
            <button
              type="button"
              role="tab"
              aria-selected={tab === "drill"}
              className={"skill-modal-tab" + (tab === "drill" ? " active" : "")}
              onClick={() => setTab("drill")}
            >
              <AppIcon name="sword" size={14} framed={false} />
              修煉試煉
            </button>
            <button
              type="button"
              role="tab"
              aria-selected={tab === "records"}
              className={
                "skill-modal-tab" +
                (tab === "records" ? " active" : "") +
                (hasOpenMistake ? " has-open-mistake" : "")
              }
              onClick={() => setTab("records")}
            >
              <AppIcon name="scroll" size={14} framed={false} />
              錯題紀錄
            </button>
            <button
              type="button"
              role="tab"
              aria-selected={tab === "coach"}
              className={"skill-modal-tab" + (tab === "coach" ? " active" : "")}
              onClick={() => openCoach(false)}
            >
              <AppIcon name="wizard" size={14} framed={false} />
              教練
            </button>
            <button
              type="button"
              role="tab"
              aria-selected={tab === "notes"}
              className={"skill-modal-tab" + (tab === "notes" ? " active" : "") + (hasNotes ? " has-notes" : "")}
              onClick={() => setTab("notes")}
            >
              <AppIcon name="folder" size={14} framed={false} />
              筆記
            </button>
          </div>
          <button type="button" className="skill-modal-close" aria-label="關閉" onClick={onClose}>
            ×
          </button>
        </div>

        <div
          className={"skill-modal-pane skill-modal-body" + (tab === "detail" ? " active" : "")}
          role="tabpanel"
          hidden={tab !== "detail"}
        >
            <div className="skill-card-badges">
              <span className={`pill-rar rar-${card.rarity}`}>{RARITY_LABEL[card.rarity] || "普通"}</span>
              {node.core ? (
                <Tag tone="gold">
                  <span className="tag-icon-inline">
                    <AppIcon name="key" size={14} framed={false} />
                  </span>
                  核心
                </Tag>
              ) : null}
              <Tag tone={entry?.mastered ? "gold" : undefined}>{masteryLabel(entry)}</Tag>
            </div>

            <h2 id="skill-card-title" className="skill-card-title pixel">
              {card.cleanTitle}
            </h2>
            <div className="skill-card-meta">
              {card.label} · {card.groupName}
            </div>
            <p className="skill-card-rarity-reason small muted">評分依據：{node.rarityReason}</p>

            <div className="skill-card-actions">
              <button type="button" className="btn-primary sm" onClick={() => setTab("drill")}>
                開始修煉試煉
              </button>
              <button type="button" className="btn-ghost sm" onClick={() => openCoach(true)}>
                問貓頭鷹教練
              </button>
              <button type="button" className="btn-ghost sm" onClick={() => setTab("notes")}>
                寫修煉筆記
              </button>
              <button type="button" className="btn-ghost sm" onClick={() => setTab("records")}>
                錯題紀錄
              </button>
            </div>

            <section className="skill-card-section">
              <div className="skill-card-section-head">
                <AppIcon name="hammer" size={20} framed variant="hero" />
                <h3>通用機制</h3>
              </div>
              <p className="skill-card-text">{card.mechanism || "（見下方完整說明）"}</p>
            </section>

            {card.triggers.length > 0 && (
              <section className="skill-card-section">
                <div className="skill-card-section-head">
                  <AppIcon name="compass" size={20} framed variant="hero" />
                  <h3>觸發訊號</h3>
                </div>
                <ul className="skill-card-list">
                  {card.triggers.map((t, i) => (
                    <li key={i}>{t}</li>
                  ))}
                </ul>
              </section>
            )}

            {card.quote ? (
              <blockquote className="editorial skill-card-quote">
                「{card.quote}」
                <span className="by">— 關鍵引述（跨情境適用）</span>
              </blockquote>
            ) : null}

            {card.instances.length > 0 && (
              <section className="skill-card-section">
                <div className="skill-card-section-head">
                  <AppIcon name="folder" size={20} framed variant="hero" />
                  <h3>歷史實例 · {card.instances.length}</h3>
                </div>
                <div className="skill-instance-list">
                  {card.instances.map((inst, i) => (
                    <div className="skill-instance card" key={i}>
                      {inst.ep ? <div className="skill-instance-ep">{inst.ep}</div> : null}
                      <div className="skill-instance-text">{inst.text}</div>
                    </div>
                  ))}
                </div>
              </section>
            )}

            <section className="skill-card-section">
              <div className="skill-card-section-head">
                <AppIcon name="scroll" size={20} framed variant="hero" />
                <h3>完整條文</h3>
              </div>
              <div className="skill-card-raw">{card.body.replace(/^#\s+.+\n?/m, "").trim()}</div>
            </section>

            <p className="skill-card-foot">
              ＊精通需通過修煉試煉（含 K 線圖判），教練評分 95 分以上。僅供學習，不構成投資建議。
            </p>
        </div>

        <div
          className={
            "skill-modal-pane skill-modal-body skill-modal-body--drill" + (tab === "drill" ? " active" : "")
          }
          role="tabpanel"
          hidden={tab !== "drill"}
        >
          <SkillDrillPanel
            key={node.principle.id}
            node={node}
            progressEntry={entry}
            onProgressChange={onProgressChange}
            onMistakeBookChange={onMistakeBookChange}
            onAttemptRecorded={onAttemptRecorded}
          />
        </div>

        <div
          className={
            "skill-modal-pane skill-modal-body skill-modal-body--records" +
            (tab === "records" ? " active" : "")
          }
          role="tabpanel"
          hidden={tab !== "records"}
        >
          <SkillDrillHistory
            principleId={node.principle.id}
            refreshKey={historyRevision}
            onMistakeBookChange={onMistakeBookChange}
            onRetryDrill={() => setTab("drill")}
          />
        </div>

        <div
          className={
            "skill-modal-pane skill-modal-body skill-modal-body--coach" + (tab === "coach" ? " active" : "")
          }
          role="tabpanel"
          hidden={tab !== "coach"}
        >
          <SkillCoachChat
            key={node.principle.id}
            principleId={node.principle.id}
            focus={aiFocus}
            cardTitle={card.cleanTitle}
            contextHint={coachContextHint}
            initialQuestion={aiPrompt}
            autoSendToken={coachAutoSendToken}
            onNotesIndexChange={onNotesIndexChange}
          />
        </div>

        <div
          className={
            "skill-modal-pane skill-modal-body skill-modal-body--notes" + (tab === "notes" ? " active" : "")
          }
          role="tabpanel"
          hidden={tab !== "notes"}
        >
          <SkillNotesPanel
            key={node.principle.id}
            principleId={node.principle.id}
            cardTitle={card.cleanTitle}
            onNotesChange={(index) => {
              onNotesIndexChange?.(index);
              setNotesTick((n) => n + 1);
              onNotesChange?.();
            }}
          />
        </div>
      </div>
    </div>
  );
}
