"use client";

import { useEffect, useState } from "react";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";
import {
  MAJOR_STARS,
  PALACE_ORDER,
  type MajorStarKey,
  type MajorStarInfo,
} from "@/lib/tuvi/major-stars-catalog";

type Props = {
  starName: string;
  onClose: () => void;
};

export function MajorStarModal({ starName, onClose }: Props) {
  const info: MajorStarInfo | undefined = MAJOR_STARS[starName as MajorStarKey];
  const [tab, setTab] = useState<"general" | "palaces">("general");

  // ESC to close
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", handler);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", handler);
      document.body.style.overflow = "";
    };
  }, [onClose]);

  if (!info) {
    return (
      <ModalShell onClose={onClose}>
        <div className="p-6">
          <h3 className="font-display text-lg font-semibold">Không có dữ liệu</h3>
          <p className="text-ink-secondary mt-2 text-sm">
            Sao &ldquo;{starName}&rdquo; chưa có trong catalog 14 chính tinh. Có thể là phụ tinh,
            sát tinh hoặc sao đặc biệt — sẽ bổ sung trong các bản cập nhật sau.
          </p>
        </div>
      </ModalShell>
    );
  }

  const natureColor =
    info.nature === "cát"
      ? "text-emerald-300"
      : info.nature === "hung"
        ? "text-rose-300"
        : "text-amber-300";

  return (
    <ModalShell onClose={onClose}>
      {/* Header */}
      <div className="border-stroke-subtle border-b p-5 lg:p-6">
        <div className="flex items-start justify-between gap-3">
          <div>
            <div className="text-ink-muted mb-1 text-xs tracking-wider uppercase">
              14 Chính Tinh
            </div>
            <h2 className="font-display text-brand-gold text-2xl font-semibold lg:text-3xl">
              {info.name}
            </h2>
            <div className="text-ink-secondary mt-1 flex flex-wrap items-center gap-2 text-xs lg:text-sm">
              <span>{info.category}</span>
              <span className="text-ink-muted">·</span>
              <span>Hành {info.element}</span>
              <span className="text-ink-muted">·</span>
              <span className={cn("font-medium capitalize", natureColor)}>{info.nature}</span>
            </div>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="text-ink-muted hover:text-ink-primary -m-2 p-2"
            aria-label="Đóng"
          >
            <X className="h-5 w-5" aria-hidden="true" />
          </button>
        </div>

        {/* Tabs */}
        <div className="mt-4 flex gap-1">
          <TabButton active={tab === "general"} onClick={() => setTab("general")}>
            Tổng quan
          </TabButton>
          <TabButton active={tab === "palaces"} onClick={() => setTab("palaces")}>
            12 Cung
          </TabButton>
        </div>
      </div>

      {/* Body */}
      <div className="max-h-[60vh] overflow-y-auto p-5 lg:p-6">
        {tab === "general" ? (
          <div className="prose prose-sm prose-invert max-w-none">
            <p className="text-ink-secondary text-sm leading-relaxed lg:text-base">
              {info.general}
            </p>
            <div className="text-ink-muted mt-6 text-xs leading-relaxed">
              <strong className="text-ink-secondary">Lưu ý luận giải:</strong> Ý nghĩa của một chính
              tinh phụ thuộc vào (1) miếu vượng đắc hãm theo địa chi, (2) sao phù trợ trong tam
              phương tứ chính (Tả Phù, Hữu Bật, Văn Xương, Văn Khúc, Thiên Khôi, Thiên Việt), (3)
              sát tinh tọa thủ (Kình, Đà, Hỏa, Linh, Không, Kiếp), và (4) Hóa Lộc, Hóa Quyền, Hóa
              Khoa, Hóa Kỵ. Cần xem tổng hợp để có luận giải chính xác.
            </div>
          </div>
        ) : (
          <div className="space-y-3">
            {PALACE_ORDER.map((palace) => (
              <div
                key={palace}
                className="border-stroke-subtle bg-bg-elevated/40 rounded-lg border p-3 lg:p-4"
              >
                <div className="text-brand-gold-soft font-display mb-1 text-sm font-medium tracking-wide lg:text-base">
                  {palace}
                </div>
                <p className="text-ink-secondary text-xs leading-relaxed lg:text-sm">
                  {info.inPalace[palace]}
                </p>
              </div>
            ))}
          </div>
        )}
      </div>
    </ModalShell>
  );
}

function TabButton({
  active,
  onClick,
  children,
}: {
  active: boolean;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        "rounded-md px-3 py-1.5 text-sm font-medium transition-colors",
        active
          ? "bg-brand-gold/15 text-brand-gold border-brand-gold/40 border"
          : "text-ink-secondary hover:bg-bg-inset border border-transparent"
      )}
    >
      {children}
    </button>
  );
}

function ModalShell({ children, onClose }: { children: React.ReactNode; onClose: () => void }) {
  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 backdrop-blur-sm"
      onClick={onClose}
      role="dialog"
      aria-modal="true"
    >
      <div
        className="border-brand-gold/30 bg-bg-elevated relative w-full max-w-2xl rounded-xl border shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        {children}
      </div>
    </div>
  );
}
