import type { Metadata } from "next";
import Link from "next/link";
import { ArrowLeft, Printer } from "lucide-react";
import { ChartGrid } from "@/components/tuvi/chart-grid";
import { ChartWithOverlay } from "@/components/tuvi/chart-with-overlay";
import { TuViForm } from "@/components/tuvi/tu-vi-form";
import { HoroscopePanel } from "@/components/tuvi/horoscope-panel";
import { HoroscopeDatePicker } from "@/components/tuvi/horoscope-date-picker";
import { SectionReading } from "@/components/ai/section-reading";
import { SaveChartButton } from "@/components/charts/save-chart-button";
import { buildChart, type ChartInput } from "@/lib/tuvi/engine";
import { buildHoroscope } from "@/lib/tuvi/horoscope";
import { currentUser } from "@/lib/charts";
import { prisma } from "@/lib/db";

export const metadata: Metadata = {
  title: "Tử Vi Trọn Đời",
  description:
    "Lập lá số tử vi đẩu số trọn đời từ ngày sinh — 12 cung, an chính tinh và phụ tinh, hóa Lộc Quyền Khoa Kỵ.",
};

type SearchParams = Record<string, string | string[] | undefined>;

function pickString(v: string | string[] | undefined): string | undefined {
  if (Array.isArray(v)) return v[0];
  return v;
}

function parseInput(sp: SearchParams): ChartInput | null {
  const date = pickString(sp.d);
  const t = pickString(sp.t);
  const g = pickString(sp.g);
  const c = pickString(sp.c);
  if (!date || !t || !g || !c) return null;

  const timeIndex = parseInt(t, 10);
  if (Number.isNaN(timeIndex) || timeIndex < 0 || timeIndex > 12) return null;

  const gender = g === "Nữ" ? "Nữ" : g === "Nam" ? "Nam" : null;
  if (!gender) return null;

  const calendar = c === "lunar" ? "lunar" : c === "solar" ? "solar" : null;
  if (!calendar) return null;

  return {
    date,
    timeIndex,
    gender,
    calendar,
    isLeapMonth: pickString(sp.leap) === "1",
    fullName: pickString(sp.n),
  };
}

export default async function TuViTronDoiPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>;
}) {
  const sp = await searchParams;
  const input = parseInput(sp);

  if (!input) {
    return <PhaseAForm />;
  }

  let chart;
  try {
    chart = buildChart(input);
  } catch (e) {
    return (
      <PhaseAForm
        error={e instanceof Error ? e.message : "Không thể lập lá số. Vui lòng thử lại."}
      />
    );
  }

  const user = await currentUser();
  const defaultLabel = chart.fullName || "Lá số mới";

  // Resolve the user's plan so the AI section panel can show/hide PDF export.
  let userPlan: "FREE" | "PREMIUM" | "ANONYMOUS" = "ANONYMOUS";
  if (user) {
    const u = await prisma.user.findUnique({
      where: { id: user.id },
      select: { plan: true },
    });
    userPlan = u?.plan === "PREMIUM" ? "PREMIUM" : "FREE";
  }

  // Horoscope for the selected date (defaults to today)
  const forDate = pickString(sp.h);
  const isoDateRe = /^\d{4}-\d{2}-\d{2}$/;
  const safeForDate = forDate && isoDateRe.test(forDate) ? forDate : undefined;
  let horoscope = null;
  try {
    horoscope = buildHoroscope(input, safeForDate);
  } catch {
    horoscope = null;
  }

  return (
    <div className="bg-bg-base relative">
      <div className="bagua-decor absolute inset-0 opacity-40" aria-hidden="true" />
      <div className="max-w-container relative mx-auto px-4 py-10 lg:px-6 lg:py-16">
        {/* Header bar */}
        <div className="mb-8 flex flex-wrap items-center justify-between gap-3">
          <Link
            href="/tu-vi-tron-doi"
            className="text-ink-secondary hover:text-brand-gold inline-flex items-center gap-1.5 text-sm"
          >
            <ArrowLeft className="h-4 w-4" aria-hidden="true" />
            Lập lá số khác
          </Link>
          <div className="flex flex-wrap items-center gap-2">
            <SaveChartButton input={input} defaultLabel={defaultLabel} isLoggedIn={!!user} />
            <button
              type="button"
              className="border-stroke-default text-ink-secondary hover:border-brand-gold/50 hover:text-brand-gold inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-sm"
              // Print is a client-only action — keep it as no-op for now (Phase 1.4 polish)
            >
              <Printer className="h-4 w-4" aria-hidden="true" />
              In lá số
            </button>
          </div>
        </div>

        {/* Title strip */}
        <div className="mb-6 text-center">
          <div className="ornament-line text-brand-gold-soft mb-2 text-xs tracking-[0.22em] uppercase">
            Tử Vi Đẩu Số
          </div>
          <h1 className="font-display text-2xl font-semibold lg:text-4xl">
            Lá số trọn đời{chart.fullName ? ` của ${chart.fullName}` : ""}
          </h1>
          <p className="text-ink-secondary mt-2 text-sm">
            {chart.gender} · {chart.solarDate} ({chart.lunarDate}) · {chart.timeRange}
          </p>
        </div>

        <div className="mx-auto max-w-5xl">
          {horoscope ? (
            <ChartWithOverlay chart={chart} horo={horoscope} />
          ) : (
            <ChartGrid chart={chart} />
          )}
        </div>

        {horoscope ? (
          <>
            <HoroscopeDatePicker currentInput={input} currentForDate={horoscope.forDate} />
            <HoroscopePanel horo={horoscope} />
          </>
        ) : null}

        <SectionReading input={input} forDate={horoscope?.forDate} plan={userPlan} />

        {/* Reading note */}
        <div className="border-brand-red/20 bg-brand-red/5 mx-auto mt-8 max-w-3xl rounded-lg border p-4 text-xs">
          <p className="text-ink-secondary leading-relaxed">
            <span className="text-ink-primary font-medium">Cách đọc lá số:</span> Cung Mệnh là điểm
            khởi (đánh dấu khung vàng nếu trùng Thân). Đọc theo chiều ngược kim đồng hồ qua 12 cung.
            Sao có hóa <span className="text-emerald-300">Lộc</span>,{" "}
            <span className="text-sky-300">Quyền</span>,{" "}
            <span className="text-amber-300">Khoa</span>, <span className="text-rose-300">Kỵ</span>{" "}
            tô màu khác.
          </p>
        </div>
      </div>
    </div>
  );
}

function PhaseAForm({ error }: { error?: string }) {
  return (
    <div className="bg-bg-base bagua-decor relative">
      <div className="max-w-container relative mx-auto px-4 py-12 lg:px-6 lg:py-20">
        <div className="mb-8 text-center lg:mb-12">
          <div className="ornament-line text-brand-gold-soft mb-3 text-xs tracking-[0.22em] uppercase">
            Tử Vi Đẩu Số
          </div>
          <h1 className="font-display text-3xl font-semibold lg:text-5xl">
            Lá số <span className="italic">tử vi trọn đời</span>
          </h1>
          <p className="text-ink-secondary mx-auto mt-3 max-w-[58ch] text-sm lg:text-base">
            Nhập ngày sinh để xem 12 cung, chính tinh, phụ tinh và hóa khí — dựa trên Tử vi Đẩu số
            cổ học (engine: iztro · v2.5).
          </p>
        </div>

        {error ? (
          <div className="border-brand-red/40 bg-brand-red/10 text-brand-red-light mx-auto mb-6 max-w-2xl rounded-md border px-4 py-3 text-sm">
            {error}
          </div>
        ) : null}

        <TuViForm />
      </div>
    </div>
  );
}
