"use client";

import { useState } from "react";
import { cn } from "@/lib/utils";
import {
  buildFlyingStarChart,
  type FlyingStarChart,
  type StarTone,
  type FlyingStarCell,
} from "@/lib/feng-shui/flying-stars";

const CURRENT_YEAR = 2026;
const YEARS_AVAILABLE = [2024, 2025, 2026, 2027, 2028];

const TONE_STYLES: Record<StarTone, { bg: string; border: string; text: string; label: string }> = {
  great: {
    bg: "bg-amber-500/10",
    border: "border-amber-400/40",
    text: "text-amber-300",
    label: "Đại cát",
  },
  good: {
    bg: "bg-emerald-500/10",
    border: "border-emerald-400/40",
    text: "text-emerald-300",
    label: "Cát",
  },
  neutral: {
    bg: "bg-bg-inset",
    border: "border-stroke-default",
    text: "text-ink-secondary",
    label: "Bình",
  },
  bad: {
    bg: "bg-orange-500/10",
    border: "border-orange-400/40",
    text: "text-orange-300",
    label: "Hung",
  },
  "very-bad": {
    bg: "bg-rose-500/10",
    border: "border-rose-400/40",
    text: "text-rose-300",
    label: "Đại hung",
  },
};

export function FlyingStarPanel() {
  const [year, setYear] = useState(CURRENT_YEAR);
  const [selected, setSelected] = useState<FlyingStarCell | null>(null);
  const chart: FlyingStarChart = buildFlyingStarChart(year);

  // Render order in 3x3 grid (gridIndex matches the layout)
  // 0=ĐN  1=Nam  2=TN
  // 3=Đ   4=TC   5=T
  // 6=ĐB  7=Bắc  8=TB
  const cells = chart.cells;

  return (
    <div className="border-stroke-default bg-bg-elevated/40 rounded-xl border p-6 lg:p-8">
      <div className="mb-5 flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
        <div>
          <h3 className="font-display text-lg font-semibold lg:text-xl">
            Huyền Không phi tinh — phong thủy theo năm
          </h3>
          <p className="text-ink-secondary mt-0.5 text-xs lg:text-sm">
            Cửu tinh bay vào 9 cung — xác định hướng cát/hung và cách hóa giải mỗi năm
          </p>
        </div>
        <div className="flex flex-wrap gap-1.5">
          {YEARS_AVAILABLE.map((y) => (
            <button
              key={y}
              type="button"
              onClick={() => {
                setYear(y);
                setSelected(null);
              }}
              className={cn(
                "rounded-md border px-3 py-1.5 text-xs font-medium transition-colors",
                y === year
                  ? "border-brand-gold/50 bg-brand-gold/15 text-brand-gold"
                  : "border-stroke-default text-ink-secondary hover:bg-bg-inset"
              )}
            >
              {y}
            </button>
          ))}
        </div>
      </div>

      <div className="text-ink-muted mb-3 text-xs">
        <span className="text-ink-primary font-medium">Sao nhập trung cung {year}:</span>{" "}
        <strong className={TONE_STYLES[cells[4].star.tone].text}>
          {cells[4].star.name} ({chart.centerStar})
        </strong>
        <span> · Click vào ô bất kỳ để xem ý nghĩa & cách hóa giải</span>
      </div>

      {/* 3x3 grid - Nam ở trên */}
      <div className="mx-auto grid max-w-2xl grid-cols-3 gap-2">
        {cells.map((cell) => {
          const tone = TONE_STYLES[cell.star.tone];
          const isCenter = cell.direction === "Trung cung";
          const isSelected = selected?.gridIndex === cell.gridIndex;
          return (
            <button
              key={cell.gridIndex}
              type="button"
              onClick={() => setSelected(cell)}
              className={cn(
                "flex aspect-square flex-col items-center justify-center rounded-lg border-2 p-2 text-center transition-all",
                tone.bg,
                tone.border,
                isCenter && "border-dashed",
                isSelected && "ring-brand-gold ring-2 ring-offset-2 ring-offset-transparent",
                "hover:scale-105 active:scale-95"
              )}
            >
              <div className={cn("font-display text-xl font-bold lg:text-2xl", tone.text)}>
                {cell.star.number}
              </div>
              <div className="text-ink-primary mt-0.5 text-[10px] font-medium lg:text-xs">
                {cell.star.name}
              </div>
              <div className="text-ink-muted mt-0.5 text-[9px] lg:text-[10px]">
                {cell.direction}
              </div>
            </button>
          );
        })}
      </div>

      {/* Legend */}
      <div className="mt-4 flex flex-wrap items-center justify-center gap-2 text-[10px] lg:text-xs">
        {(Object.entries(TONE_STYLES) as [StarTone, (typeof TONE_STYLES)[StarTone]][]).map(
          ([tone, style]) => (
            <span
              key={tone}
              className={cn(
                "rounded-full border px-2 py-0.5 font-medium",
                style.bg,
                style.border,
                style.text
              )}
            >
              {style.label}
            </span>
          )
        )}
      </div>

      {/* Detail panel */}
      {selected ? (
        <div
          className={cn(
            "mt-5 rounded-lg border-2 p-4 lg:p-5",
            TONE_STYLES[selected.star.tone].bg,
            TONE_STYLES[selected.star.tone].border
          )}
        >
          <div className="flex items-baseline justify-between gap-3">
            <div>
              <div
                className={cn(
                  "font-display text-xl font-bold",
                  TONE_STYLES[selected.star.tone].text
                )}
              >
                {selected.star.fullName}
              </div>
              <div className="text-ink-muted mt-0.5 text-xs">
                Hướng <strong className="text-ink-primary">{selected.direction}</strong> · Hành{" "}
                <strong className="text-ink-primary">{selected.star.element}</strong> ·{" "}
                <span className={TONE_STYLES[selected.star.tone].text}>
                  {TONE_STYLES[selected.star.tone].label}
                </span>
              </div>
            </div>
            <button
              type="button"
              onClick={() => setSelected(null)}
              className="text-ink-muted hover:text-ink-primary text-xs"
            >
              Đóng
            </button>
          </div>
          <p className="text-ink-secondary mt-3 text-sm leading-relaxed">{selected.star.meaning}</p>
          <div className="border-stroke-default/50 mt-3 border-t pt-3">
            <div className="text-ink-muted mb-1 text-xs tracking-wider uppercase">
              {selected.star.tone === "great" || selected.star.tone === "good"
                ? "Kích hoạt"
                : "Hóa giải"}
            </div>
            <p className="text-ink-secondary text-sm leading-relaxed">{selected.star.cure}</p>
          </div>
        </div>
      ) : null}

      {/* Disclaimer */}
      <div className="text-ink-muted mt-4 text-[10px] leading-relaxed lg:text-xs">
        <strong className="text-ink-secondary">Lưu ý:</strong> Phi tinh năm áp dụng từ Lập Xuân
        (~4/2). Kết hợp với phi tinh tháng và phi tinh trạch (theo hướng nhà) để có đánh giá đầy đủ.
        Hướng có sao 5 và sao 2 trong năm cần đặc biệt tránh động thổ, sửa chữa.
      </div>
    </div>
  );
}
