import type { ReactNode } from "react";
import { useId, useMemo } from "react";

import { getPalaceInterpretVisibleTabs } from "@/lib/tuvi-palace-section-priority";

import { TuViLuanCungPanel } from "./TuViLuanCungPanel";
import {
  TUVI_INTERPRET_FORTUNE_SECTION_KEYS,
  TUVI_INTERPRET_HEALTH_SECTION_KEYS,
  TUVI_INTERPRET_FAMILY_SECTION_KEYS,
} from "./tuvi-interpret-thematic-keys";
import { TUVI_INTERPRET_TABS, type TuViInterpretPanelTabId } from "./tuvi-interpret-tabs.config";

export type { TuViInterpretNormalized } from "@/lib/tuvi-interpret-types";
export type {
  PalaceInterpretAdviceGroups,
  PalaceInterpretationView,
  PalaceInterpretSection,
  PalaceInterpretTone,
  PalaceStarExplainItem,
} from "@/lib/tuvi-palace-interpret-view-model";
export type { TuViInterpretPanelTabId } from "./tuvi-interpret-tabs.config";
export { TUVI_INTERPRET_TABS } from "./tuvi-interpret-tabs.config";

import {
  palaceInterpretOverviewSections,
  palaceInterpretTabSection,
  type PalaceInterpretationView,
  type PalaceInterpretSection,
} from "@/lib/tuvi-palace-interpret-view-model";

export type TuViInterpretPanelLayout = "aside" | "workspace";

/** Cuộn tới phụ lục AI — chỉ gọi `onRequest` khi `available`. */
export type TuViInterpretAiDeepDive = {
  available: boolean;
  onRequest: () => void;
  /** Hiển thị khi `available === false`. */
  unavailableHint?: string;
};

type Props = {
  interpretation: PalaceInterpretationView | null;
  selectedPalace: TuViInterpretPanelSelectedPalace | null;
  activeTab: TuViInterpretPanelTabId;
  onTabChange: (id: TuViInterpretPanelTabId) => void;
  onNavigatePalace?: (palaceKey: string) => void;
  footer?: ReactNode;
  className?: string;
  /** `workspace` — khối luận rộng, vùng cuộn cao hơn (tab Luận cung). */
  layout?: TuViInterpretPanelLayout;
  /** Nút «Luận sâu cung này»; khi thiếu API: nút tắt + gợi ý, không lỗi UI. */
  aiDeepDive?: TuViInterpretAiDeepDive;
  /** Ẩn hàng tab — dùng khi tab strip nằm ngoài (trên trang / trong overlay). */
  hideTabBar?: boolean;
  /** `minimal` — bỏ tiêu đề khối «Dịch lý / Luận giải» (overlay đã có heading). */
  chrome?: "full" | "minimal";
};

export type TuViInterpretPanelSelectedPalace = {
  key: string;
  nameVi: string;
  indexOneBased: number;
};

export function TuViInterpretPanel({
  interpretation,
  selectedPalace,
  activeTab,
  onTabChange,
  onNavigatePalace,
  footer,
  className = "",
  layout = "aside",
  aiDeepDive,
  hideTabBar = false,
  chrome = "full",
}: Props) {
  const palaceKey = selectedPalace?.key ?? "";
  const visibleTabs = useMemo(() => new Set(getPalaceInterpretVisibleTabs(palaceKey)), [palaceKey]);
  const effectiveTab = visibleTabs.has(activeTab) ? activeTab : (getPalaceInterpretVisibleTabs(palaceKey)[0] ?? "overview");
  const isWorkspace = layout === "workspace";
  const aiDeepHintId = useId();
  const minimal = chrome === "minimal";

  const scrollBodyClass =
    hideTabBar ?
      "mt-0 min-h-0 flex-1 overflow-visible pr-0.5 font-sans text-sm leading-[1.85]"
    : `ctkp-tuvi-text-body mt-5 overflow-y-auto pr-1 font-sans text-sm leading-[1.85] ${
        isWorkspace ?
          "max-h-[min(72vh,34rem)] min-h-[min(40vh,18rem)] sm:max-h-[min(78vh,40rem)] lg:max-h-[min(84vh,48rem)]"
        : "max-h-[min(64vh,26rem)] sm:max-h-[min(70vh,30rem)]"
      }`;

  return (
    <section
      className={`rounded-xl border border-[#d4af37]/16 bg-[linear-gradient(175deg,rgba(14,20,36,0.88),rgba(4,6,12,0.92))] p-5 shadow-[inset_0_1px_0_rgba(212,175,55,0.1),0_20px_48px_rgba(0,0,0,0.35)] sm:p-6 ${minimal ? "border-0 bg-transparent p-0 shadow-none sm:p-0" : ""} ${className}`}
      aria-labelledby={minimal ? undefined : "tuvi-interpret-heading"}
    >
      {!minimal ?
        <>
          <div className="flex flex-col gap-1 border-b border-[#d4af37]/12 pb-4 sm:flex-row sm:items-end sm:justify-between">
            <div>
              <p className="font-ctkp-serif text-[10px] uppercase tracking-[0.32em] text-[#d4af37]/68">
                Dịch lý
              </p>
              <h2
                id="tuvi-interpret-heading"
                className="ctkp-tuvi-text-title-soft mt-1 font-ctkp-serif text-lg font-normal tracking-[0.1em] sm:text-xl"
              >
                Luận giải
              </h2>
            </div>
            <p className="ctkp-tuvi-text-muted max-w-md font-sans text-[11px] leading-relaxed">
              {isWorkspace ?
                "Luận chia mục — tránh dàn trải như bài dài. Đổi cung ở bộ chọn bên trái hoặc phía trên."
              : "Khung có cấu từ engine và tra cứu — không phải văn bản thô một khối. Chọn ô trên lưới để đổi cung."}
            </p>
          </div>

          {selectedPalace ?
            <p
              className="mt-4 rounded-md border border-[#d4af37]/18 bg-black/25 px-3 py-2.5 font-sans text-[11px] leading-snug text-[#e8d9a8]/92"
              aria-live="polite"
            >
              <span className="text-slate-500">Đang xem</span>
              <span className="mx-1.5 text-[#d4af37]/55" aria-hidden>
                ·
              </span>
              <span className="font-ctkp-serif tracking-[0.04em]">{selectedPalace.nameVi}</span>
              <span className="ml-2 tabular-nums text-slate-500">{selectedPalace.indexOneBased}/12</span>
            </p>
          : null}
        </>
      : selectedPalace ?
        <p
          className="mb-4 rounded-md border border-[#d4af37]/18 bg-black/25 px-3 py-2.5 font-sans text-[11px] leading-snug text-[#e8d9a8]/92"
          aria-live="polite"
        >
          <span className="text-slate-500">Đang xem</span>
          <span className="mx-1.5 text-[#d4af37]/55" aria-hidden>
            ·
          </span>
          <span className="font-ctkp-serif tracking-[0.04em]">{selectedPalace.nameVi}</span>
          <span className="ml-2 tabular-nums text-slate-500">{selectedPalace.indexOneBased}/12</span>
        </p>
      : null}

      {!hideTabBar ?
        <div className="mt-5 flex flex-wrap gap-1.5 border-b border-[#d4af37]/10 pb-4" role="tablist" aria-label="Mục luận giải">
          {TUVI_INTERPRET_TABS.filter(({ id }) => visibleTabs.has(id)).map(({ id, label }) => (
            <button
              key={id}
              type="button"
              role="tab"
              aria-selected={effectiveTab === id}
              onClick={() => onTabChange(id)}
              className={`rounded-md px-3 py-2 font-ctkp-serif text-[11px] tracking-[0.06em] transition-[background-color,border-color,color] duration-200 ${
                effectiveTab === id
                  ? "border border-[#d4af37]/38 bg-[#d4af37]/14 text-[#f5d878]"
                  : "border border-transparent text-slate-400 hover:border-[#d4af37]/18 hover:bg-[#0a1020]/65 hover:text-slate-200"
              }`}
            >
              {label}
            </button>
          ))}
        </div>
      : null}

      <div
        key={palaceKey || "none"}
        className={scrollBodyClass}
        role="tabpanel"
        aria-label={
          selectedPalace ? `Nội dung luận cho ${selectedPalace.nameVi}` : "Nội dung luận giải tử vi"
        }
      >
        {effectiveTab === "overview" ?
          <TuViLuanCungPanel
            embedded
            interpretation={interpretation}
            selectedPalace={selectedPalace}
            onNavigatePalace={onNavigatePalace}
          />
        : effectiveTab === "career" ?
          <DomainPanel section={interpretation ? palaceInterpretTabSection(interpretation, "career") : undefined} />
        : effectiveTab === "wealth" ?
          <DomainPanel section={interpretation ? palaceInterpretTabSection(interpretation, "wealth") : undefined} />
        : effectiveTab === "love" ?
          <DomainPanel section={interpretation ? palaceInterpretTabSection(interpretation, "love") : undefined} />
        : effectiveTab === "family" ?
          <ThematicSectionsPanel
            interpretation={interpretation}
            keys={TUVI_INTERPRET_FAMILY_SECTION_KEYS}
            emptyHint="Chưa có đoạn «gia đạo» tách riêng cho ô đang chọn. Thử ô Phụ Mẫu, Phúc Đức, Tử Tức hoặc Huynh Đệ — hoặc về tab Tổng quan."
          />
        : effectiveTab === "health" ?
          <ThematicSectionsPanel
            interpretation={interpretation}
            keys={TUVI_INTERPRET_HEALTH_SECTION_KEYS}
            emptyHint="Chưa có đoạn «sức khỏe» tách riêng cho ô đang chọn. Thử ô Tật Ách — hoặc xem Tổng quan; luận không thay tư vấn y tế."
          />
        : (
          <ThematicSectionsPanel
            interpretation={interpretation}
            keys={TUVI_INTERPRET_FORTUNE_SECTION_KEYS}
            emptyHint="Chưa có đoạn «vận hạn» tách riêng cho ô đang chọn. Thử ô Thiên Di, Điền Trạch, Nô Bộc, Quan Lộc — hoặc mở các tab Đại vận / Tiểu vận phía trên."
          />
        )}
      </div>

      {aiDeepDive ?
        <div className={`mt-5 border-t border-[#d4af37]/10 pt-4 ${minimal ? "mt-6" : ""}`}>
          <p className="font-ctkp-serif text-[10px] uppercase tracking-[0.22em] text-[#d4af37]/52">
            Luận thêm (tùy chọn)
          </p>
          <div className="mt-2.5 flex flex-col gap-2.5 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
            <button
              type="button"
              onClick={() => {
                if (aiDeepDive.available) aiDeepDive.onRequest();
              }}
              disabled={!aiDeepDive.available}
              aria-disabled={!aiDeepDive.available}
              aria-describedby={!aiDeepDive.available ? aiDeepHintId : undefined}
              className={`inline-flex w-fit shrink-0 items-center justify-center rounded-lg border px-3.5 py-2 font-ctkp-serif text-[12px] tracking-[0.04em] transition-[background-color,border-color,color,opacity] duration-200 ${
                aiDeepDive.available ?
                  "border-[#d4af37]/32 bg-[#d4af37]/08 text-[#f0e6c8] hover:border-[#d4af37]/48 hover:bg-[#d4af37]/12 hover:text-[#fff8e8] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#d4af37]/35"
                : "cursor-not-allowed border-white/[0.08] bg-[#060912]/40 text-slate-500 opacity-80"
              }`}
            >
              Luận sâu cung này
            </button>
            {aiDeepDive.available ?
              <p className="max-w-md font-sans text-[10px] leading-relaxed text-slate-500 sm:pt-0.5 sm:text-[11px]">
                Cuộn tới phụ lục cuối trang. Ở đó bạn mới bấm gọi AI — lớp đó không thay luận engine/tra cứu phía trên.
              </p>
            : null}
          </div>
          {!aiDeepDive.available ?
            <p id={aiDeepHintId} className="mt-2 font-sans text-[11px] leading-relaxed text-slate-500">
              {aiDeepDive.unavailableHint ??
                "Luận sâu (AI) chưa bật trên môi trường này. Nội dung trong panel vẫn đủ dùng."}
            </p>
          : null}
        </div>
      : null}

      {footer}
    </section>
  );
}

function DomainPanel({ section }: { section: PalaceInterpretSection | undefined }) {
  const title = section?.title ?? "—";
  const content = section?.content?.trim() ?? "";
  return (
    <div className="space-y-3">
      <p className="font-ctkp-serif text-[10px] uppercase tracking-[0.2em] text-[#d4af37]/75">{title}</p>
      <p className="whitespace-pre-wrap text-pretty font-ctkp-serif text-[13px] leading-[1.9] text-slate-200/95">
        {content.length > 0 ? content : "Chọn cung để xem luận theo ô — hoặc mở tab Tổng quan."}
      </p>
    </div>
  );
}

function ThematicSectionsPanel({
  interpretation,
  keys,
  emptyHint,
}: {
  interpretation: PalaceInterpretationView | null;
  keys: ReadonlySet<string>;
  emptyHint: string;
}) {
  const overview = interpretation ? palaceInterpretOverviewSections(interpretation) : [];
  const picked = overview.filter((s) => keys.has(s.key));

  if (picked.length === 0) {
    return (
      <div className="space-y-3">
        <p className="font-ctkp-serif text-[10px] uppercase tracking-[0.2em] text-[#d4af37]/75">Gợi đọc</p>
        <p className="whitespace-pre-wrap text-pretty font-sans text-[13px] leading-[1.85] text-slate-400">{emptyHint}</p>
      </div>
    );
  }

  return (
    <div className="space-y-10">
      {picked.map((s) => (
        <div key={s.key} className="border-b border-[#d4af37]/10 pb-8 last:border-0 last:pb-0">
          <DomainPanel section={s} />
        </div>
      ))}
    </div>
  );
}
