import { CheckCircle2, XCircle } from "lucide-react";
import type { FengShuiResult, DirectionAnalysis } from "@/lib/feng-shui/bat-trach";
import { BaguaWheel } from "./bagua-wheel";
import { RoomPlacementTable } from "./room-placement-table";
import { FlyingStarPanel } from "./flying-star-panel";
import { ThanSatPanel } from "./than-sat-panel";
import { AiInsightPanel } from "@/components/ai/insight-panel";
import { cn } from "@/lib/utils";

type Props = { result: FengShuiResult; year: number };

export function PhongThuyResult({ result, year }: Props) {
  return (
    <div className="mx-auto max-w-5xl space-y-8">
      {/* Top summary card */}
      <div className="border-brand-gold/30 bg-bg-elevated/60 rounded-2xl border p-6 backdrop-blur-sm lg:p-8">
        <div className="grid gap-6 lg:grid-cols-3">
          <div>
            <div className="text-ink-muted mb-1 text-xs tracking-wider uppercase">Cung mệnh</div>
            <div className="font-display text-brand-gold text-4xl font-semibold lg:text-5xl">
              {result.cungMenh}
            </div>
            <div className="text-ink-secondary mt-1 text-sm">
              {result.group} · Hành {result.element}
            </div>
          </div>

          <div>
            <div className="text-ink-muted mb-1 text-xs tracking-wider uppercase">
              Hướng tốt nhất
            </div>
            <div className="font-display text-2xl font-semibold text-emerald-400 lg:text-3xl">
              {result.bestDirection.direction}
            </div>
            <div className="text-ink-secondary mt-1 text-sm">
              {result.bestDirection.fortune} — đặt cửa chính
            </div>
          </div>

          <div>
            <div className="text-ink-muted mb-1 text-xs tracking-wider uppercase">
              Hướng cần tránh
            </div>
            <div className="font-display text-2xl font-semibold text-rose-400 lg:text-3xl">
              {result.worstDirection.direction}
            </div>
            <div className="text-ink-secondary mt-1 text-sm">{result.worstDirection.fortune}</div>
          </div>
        </div>
      </div>

      {/* 8 directions split good/bad */}
      <div className="grid gap-6 lg:grid-cols-2">
        <DirectionList title="4 hướng cát" directions={result.goodDirections} isGood={true} />
        <DirectionList title="4 hướng hung" directions={result.badDirections} isGood={false} />
      </div>

      {/* Compass visualization */}
      <CompassDiagram allDirections={result.allDirections} />

      {/* Interactive bagua wheel — rotates to user's house heading */}
      <BaguaWheel result={result} />

      {/* Per-room placement guide — 8 rooms × directions */}
      <RoomPlacementTable result={result} />

      {/* Huyền Không phi tinh — annual flying stars */}
      <FlyingStarPanel />

      {/* Lộc · Mã · Quý Nhân — 3 thần sát theo trụ năm */}
      <ThanSatPanel year={year} />

      {/* Compatible bagua + colors */}
      <div className="grid gap-6 lg:grid-cols-2">
        <div className="border-stroke-default bg-bg-elevated/40 rounded-xl border p-6">
          <h3 className="font-display mb-3 text-lg font-semibold">Cung hợp (đối tác / cộng sự)</h3>
          <p className="text-ink-secondary mb-3 text-sm">
            Cùng nhóm <strong className="text-ink-primary">{result.group}</strong> sẽ tương hợp về
            mặt tính cách và năng lượng:
          </p>
          <div className="flex flex-wrap gap-2">
            {result.compatibleBagua.map((b) => (
              <span
                key={b}
                className="border-brand-gold/30 bg-brand-gold/10 text-brand-gold rounded-full border px-3 py-1 text-sm font-medium"
              >
                {b}
              </span>
            ))}
          </div>
        </div>

        <div className="border-stroke-default bg-bg-elevated/40 rounded-xl border p-6">
          <h3 className="font-display mb-3 text-lg font-semibold">
            Màu sắc theo hành <span className="text-brand-gold">{result.element}</span>
          </h3>
          <ColorGroup label="Màu chính" items={result.colors.primary} tone="primary" />
          <ColorGroup label="Màu hỗ trợ" items={result.colors.supporting} tone="supporting" />
          <ColorGroup label="Tránh" items={result.colors.avoid} tone="avoid" />
        </div>
      </div>

      {/* AI luận giải */}
      <AiInsightPanel
        topic="numerology"
        context={{
          tool: "feng-shui-house",
          year,
          cungMenh: result.cungMenh,
          group: result.group,
          element: result.element,
          good: result.goodDirections.map((d) => ({
            direction: d.direction,
            fortune: d.fortune,
            meaning: d.meaning,
          })),
          bad: result.badDirections.map((d) => ({
            direction: d.direction,
            fortune: d.fortune,
            meaning: d.meaning,
          })),
          colors: result.colors,
        }}
        cta={'Hỏi "Thầy" về phong thuỷ nhà'}
        title='"Thầy" luận sâu phong thuỷ nhà'
        hint={`"Thầy" sẽ phân tích sâu cho người mệnh ${result.cungMenh}: cách bố trí cửa chính, phòng ngủ, bếp - WC, vật phẩm phong thuỷ phù hợp, và cách hoá giải khi nhà hiện tại không tối ưu.`}
      />

      {/* Disclaimer */}
      <div className="border-brand-red/20 bg-brand-red/5 rounded-lg border p-4 text-xs">
        <p className="text-ink-secondary leading-relaxed">
          <span className="text-ink-primary font-medium">Disclaimer:</span> Kết quả phong thủy chỉ
          mang tính tham khảo theo Bát Trạch cổ truyền. Năm sinh dùng theo dương lịch — nếu bạn sinh
          trước Lập Xuân (~4/2 hằng năm), hãy nhập năm trước đó để chính xác hơn. Quyết định xây
          nhà, mua nhà cần kết hợp khảo sát thực địa của thầy phong thủy có chuyên môn.
        </p>
      </div>
    </div>
  );
}

function DirectionList({
  title,
  directions,
  isGood,
}: {
  title: string;
  directions: DirectionAnalysis[];
  isGood: boolean;
}) {
  return (
    <div
      className={cn(
        "rounded-xl border p-6",
        isGood ? "border-emerald-500/20 bg-emerald-500/5" : "border-rose-500/20 bg-rose-500/5"
      )}
    >
      <h3 className="font-display mb-4 flex items-center gap-2 text-lg font-semibold">
        {isGood ? (
          <CheckCircle2 className="h-5 w-5 text-emerald-400" aria-hidden="true" />
        ) : (
          <XCircle className="h-5 w-5 text-rose-400" aria-hidden="true" />
        )}
        {title}
      </h3>
      <ul className="space-y-3">
        {directions.map((d) => (
          <li
            key={d.direction}
            className="border-stroke-default/50 border-b pb-3 last:border-0 last:pb-0"
          >
            <div className="flex items-baseline justify-between gap-3">
              <span className="text-ink-primary font-semibold">{d.direction}</span>
              <span
                className={cn("text-xs font-medium", isGood ? "text-emerald-300" : "text-rose-300")}
              >
                {d.fortune}
              </span>
            </div>
            <p className="text-ink-secondary mt-1 text-xs leading-relaxed">{d.meaning}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

function CompassDiagram({ allDirections }: { allDirections: DirectionAnalysis[] }) {
  // 3×3 grid: N at top, S at bottom, center is "you"
  const layout: (DirectionAnalysis | null)[] = [
    findDir(allDirections, "Tây Bắc"),
    findDir(allDirections, "Bắc"),
    findDir(allDirections, "Đông Bắc"),
    findDir(allDirections, "Tây"),
    null,
    findDir(allDirections, "Đông"),
    findDir(allDirections, "Tây Nam"),
    findDir(allDirections, "Nam"),
    findDir(allDirections, "Đông Nam"),
  ];

  return (
    <div className="border-stroke-default bg-bg-elevated/40 rounded-xl border p-6 lg:p-8">
      <h3 className="font-display mb-6 text-center text-lg font-semibold">La bàn Bát Trạch</h3>
      <div className="mx-auto grid max-w-md grid-cols-3 gap-2">
        {layout.map((d, i) => {
          if (d === null) {
            return (
              <div
                key="center"
                className="border-brand-gold/40 bg-brand-gold/10 flex aspect-square items-center justify-center rounded-lg border-2 border-dashed"
              >
                <span className="text-brand-gold-soft text-xs tracking-wider uppercase">Bạn</span>
              </div>
            );
          }
          return (
            <div
              key={i}
              className={cn(
                "flex aspect-square flex-col items-center justify-center rounded-lg border p-2 text-center",
                d.isAuspicious
                  ? "border-emerald-500/30 bg-emerald-500/5"
                  : "border-rose-500/30 bg-rose-500/5"
              )}
            >
              <div className="text-ink-primary text-xs font-semibold lg:text-sm">{d.direction}</div>
              <div
                className={cn(
                  "mt-1 text-[10px] lg:text-xs",
                  d.isAuspicious ? "text-emerald-300" : "text-rose-300"
                )}
              >
                {d.fortune}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function findDir(arr: DirectionAnalysis[], dir: string): DirectionAnalysis {
  const found = arr.find((d) => d.direction === dir);
  if (!found) throw new Error(`Missing direction ${dir}`);
  return found;
}

function ColorGroup({
  label,
  items,
  tone,
}: {
  label: string;
  items: string[];
  tone: "primary" | "supporting" | "avoid";
}) {
  return (
    <div className="mb-3 last:mb-0">
      <div className="text-ink-muted mb-1.5 text-xs tracking-wider uppercase">{label}</div>
      <div className="flex flex-wrap gap-1.5">
        {items.map((c) => (
          <span
            key={c}
            className={cn(
              "rounded-md border px-2.5 py-1 text-xs",
              tone === "primary" && "border-brand-gold/40 bg-brand-gold/10 text-brand-gold",
              tone === "supporting" && "border-stroke-default bg-bg-inset text-ink-secondary",
              tone === "avoid" && "border-rose-500/30 bg-rose-500/5 text-rose-300 line-through"
            )}
          >
            {c}
          </span>
        ))}
      </div>
    </div>
  );
}
