import type { Metadata } from "next";
import { Sparkles, MapPin } from "lucide-react";
import {
  colorAdvice,
  SWATCHES,
  APPLICATION_LABELS,
  type Application,
} from "@/lib/feng-shui/colors";
import { AiInsightPanel } from "@/components/ai/insight-panel";

export const metadata: Metadata = {
  title: "Màu sắc Phong Thủy — Tử Vi Số",
  description:
    "Tra cứu màu sắc hợp Mệnh theo năm sinh, gợi ý ứng dụng cho trang phục, nội thất, xe, kinh doanh, cưới hỏi.",
};

type Props = {
  searchParams: Promise<{
    year?: string;
    gender?: string;
    application?: string;
  }>;
};

const APPLICATIONS: Application[] = ["clothing", "interior", "vehicle", "business", "wedding"];

function isApplication(s: string | undefined): s is Application {
  return !!s && (APPLICATIONS as string[]).includes(s);
}

export default async function FengShuiColorsPage({ searchParams }: Props) {
  const sp = await searchParams;
  const yearNum = sp.year ? parseInt(sp.year, 10) : null;
  const valid = yearNum && yearNum >= 1900 && yearNum <= 2100;
  const gender = sp.gender === "Nam" || sp.gender === "Nữ" ? sp.gender : undefined;
  const application = isApplication(sp.application) ? sp.application : undefined;

  const result = valid ? colorAdvice(yearNum!, { gender, application }) : null;

  return (
    <div className="bg-bg-base min-h-screen">
      <div className="mx-auto max-w-4xl px-4 py-8 lg:py-12">
        <div className="mb-8 text-center">
          <h1 className="font-display text-ink-primary text-3xl font-semibold lg:text-4xl">
            Màu sắc Phong Thủy
          </h1>
          <p className="text-ink-secondary mt-2 text-sm">
            Màu hợp &amp; màu kỵ theo Mệnh năm sinh — gợi ý ứng dụng cho 5 tình huống thường gặp.
          </p>
        </div>

        <form
          method="GET"
          className="border-stroke-subtle bg-bg-elevated/40 mb-8 grid gap-3 rounded-xl border p-5 lg:grid-cols-3"
        >
          <div>
            <label className="text-ink-muted block text-xs">Năm sinh dương lịch</label>
            <input
              type="number"
              name="year"
              defaultValue={sp.year ?? ""}
              placeholder="vd: 1992"
              min={1900}
              max={2100}
              required
              className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold mt-1 w-full rounded-md border px-3 py-2 text-sm focus:outline-none"
            />
          </div>
          <div>
            <label className="text-ink-muted block text-xs">
              Giới tính <span className="text-ink-muted/60">(tuỳ chọn)</span>
            </label>
            <select
              name="gender"
              defaultValue={sp.gender ?? ""}
              className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold mt-1 w-full rounded-md border px-3 py-2 text-sm focus:outline-none"
            >
              <option value="">— Không chọn —</option>
              <option value="Nam">Nam</option>
              <option value="Nữ">Nữ</option>
            </select>
          </div>
          <div>
            <label className="text-ink-muted block text-xs">
              Ứng dụng <span className="text-ink-muted/60">(tuỳ chọn)</span>
            </label>
            <select
              name="application"
              defaultValue={sp.application ?? ""}
              className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold mt-1 w-full rounded-md border px-3 py-2 text-sm focus:outline-none"
            >
              <option value="">— Tổng quát —</option>
              {APPLICATIONS.map((app) => (
                <option key={app} value={app}>
                  {APPLICATION_LABELS[app]}
                </option>
              ))}
            </select>
          </div>
          <div className="lg:col-span-3">
            <button
              type="submit"
              className="bg-brand-gold text-bg-base w-full rounded-md px-4 py-2.5 text-sm font-semibold"
            >
              Phân tích
            </button>
          </div>
        </form>

        {result ? (
          <>
            <article className="border-stroke-subtle bg-bg-elevated/40 mb-6 rounded-2xl border p-6 lg:p-8">
              <div className="border-stroke-subtle border-b pb-4">
                <div className="text-brand-gold text-xs tracking-[0.2em] uppercase">
                  Năm {yearNum} · Mệnh
                </div>
                <h2 className="font-display text-ink-primary mt-1 text-3xl font-semibold lg:text-4xl">
                  {result.element}
                </h2>
                <p className="text-ink-secondary mt-3 text-sm leading-relaxed">
                  {result.description}
                </p>
              </div>

              <div className="mt-6 space-y-6">
                <Palette title="Màu hợp (Tốt)" colors={result.good} variant="good" />
                {result.neutral.length > 0 ? (
                  <Palette title="Màu trung tính" colors={result.neutral} variant="neutral" />
                ) : null}
                <Palette title="Màu kỵ (Tránh)" colors={result.bad} variant="bad" />
              </div>
            </article>

            {result.application ? (
              <article className="mb-6 rounded-2xl border border-amber-500/30 bg-amber-500/5 p-6 lg:p-8">
                <div className="flex items-center gap-2 text-xs tracking-[0.2em] text-amber-300 uppercase">
                  <Sparkles className="h-3.5 w-3.5" />
                  Gợi ý cho {result.application.label}
                </div>
                <ul className="mt-4 space-y-3">
                  {result.application.tips.map((tip, i) => (
                    <li key={i} className="text-ink-secondary flex gap-2 text-sm leading-relaxed">
                      <span className="shrink-0 text-amber-400">·</span>
                      {tip}
                    </li>
                  ))}
                </ul>
              </article>
            ) : (
              <article className="border-stroke-subtle bg-bg-inset/40 mb-6 rounded-xl border border-dashed p-5 text-center">
                <p className="text-ink-muted text-xs">
                  Chọn ứng dụng cụ thể (Trang phục / Nội thất / Xe / Kinh doanh / Cưới hỏi) trong
                  form để xem gợi ý chi tiết.
                </p>
              </article>
            )}

            {result.personalized ? (
              <article className="border-stroke-subtle bg-bg-elevated/40 mb-6 rounded-2xl border p-6 lg:p-8">
                <div className="text-brand-gold flex items-center gap-2 text-xs tracking-[0.2em] uppercase">
                  <MapPin className="h-3.5 w-3.5" />
                  Cá nhân hoá theo cung mệnh
                </div>
                <div className="mt-4 grid gap-4 lg:grid-cols-2">
                  <div className="border-stroke-subtle bg-bg-inset rounded-lg border p-4">
                    <div className="text-ink-muted text-[11px] tracking-wider uppercase">
                      Cung mệnh
                    </div>
                    <div className="font-display text-brand-gold mt-1 text-2xl font-semibold">
                      {result.personalized.cung}
                    </div>
                    <div className="text-ink-secondary mt-1 text-xs">
                      {result.personalized.group}
                    </div>
                  </div>
                  <div className="border-stroke-subtle bg-bg-inset rounded-lg border p-4">
                    <div className="text-ink-muted text-[11px] tracking-wider uppercase">
                      Hướng tốt để bố trí màu hợp mệnh
                    </div>
                    <div className="mt-2 flex flex-wrap gap-1.5">
                      {result.personalized.goodDirections.map((d) => (
                        <span
                          key={d}
                          className="border-brand-gold/40 bg-brand-gold/10 text-brand-gold rounded border px-2 py-0.5 text-xs"
                        >
                          {d}
                        </span>
                      ))}
                    </div>
                  </div>
                </div>
                <p className="text-ink-secondary mt-4 text-sm leading-relaxed">
                  {result.personalized.summary}
                </p>
              </article>
            ) : (
              <article className="border-stroke-subtle bg-bg-inset/40 mb-6 rounded-xl border border-dashed p-5 text-center">
                <p className="text-ink-muted text-xs">
                  Nhập giới tính để mở khoá gợi ý hướng bố trí màu theo cung mệnh Bát Trạch.
                </p>
              </article>
            )}

            <AiInsightPanel
              topic="numerology"
              context={{
                tool: "feng-shui-colors",
                year: yearNum,
                element: result.element,
                gender,
                application: result.application?.label,
                cung: result.personalized?.cung,
                group: result.personalized?.group,
                goodColors: result.good,
                badColors: result.bad,
              }}
              cta={'Hỏi "Thầy"'}
              title="Luận giải màu sắc theo từng tình huống"
              hint='"Thầy" sẽ kết hợp Mệnh ngũ hành + cung mệnh + ứng dụng cụ thể để đưa ra gợi ý màu sắc, chất liệu, cách phối phù hợp với hoàn cảnh của bạn.'
            />
          </>
        ) : (
          <p className="text-ink-muted text-center text-sm">Nhập năm sinh để xem màu hợp Mệnh.</p>
        )}
      </div>
    </div>
  );
}

function Palette({
  title,
  colors,
  variant,
}: {
  title: string;
  colors: string[];
  variant: "good" | "neutral" | "bad";
}) {
  const accentClass =
    variant === "good"
      ? "text-emerald-400"
      : variant === "bad"
        ? "text-brand-red"
        : "text-ink-secondary";
  return (
    <section>
      <h3
        className={`font-display ${accentClass} mb-3 text-sm font-semibold tracking-wider uppercase`}
      >
        {title}
      </h3>
      <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-5">
        {colors.map((c) => (
          <div
            key={c}
            className="border-stroke-subtle bg-bg-inset flex items-center gap-2 rounded-md border p-2"
          >
            <span
              className="border-stroke-default h-8 w-8 shrink-0 rounded border"
              style={{ background: SWATCHES[c] ?? "#888" }}
            />
            <span className="text-ink-secondary truncate text-xs">{c}</span>
          </div>
        ))}
      </div>
    </section>
  );
}
