"use client";

import { useRouter, useSearchParams, usePathname } from "next/navigation";
import { useTransition } from "react";
import { DateInput } from "@/components/ui/date-input";
import { ChartInput } from "@/lib/tuvi/engine";

/**
 * Date picker that re-renders the horoscope panel for a different `forDate`
 * while keeping the existing chart inputs intact via the URL search params.
 *
 * Submitting the form pushes a new URL with `?h=YYYY-MM-DD`. The server
 * page reads `h` and recomputes via `buildHoroscope(input, h)`.
 */
export function HoroscopeDatePicker({
  currentInput: _currentInput,
  currentForDate,
}: {
  /** Reserved — currently unused but kept for future "preset" links. */
  currentInput: ChartInput;
  currentForDate: string;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [isPending, startTransition] = useTransition();

  function pushFor(iso: string) {
    const next = new URLSearchParams(searchParams?.toString() ?? "");
    if (iso) {
      next.set("h", iso);
    } else {
      next.delete("h");
    }
    startTransition(() => {
      router.push(`${pathname}?${next.toString()}`, { scroll: false });
    });
  }

  return (
    <div className="border-stroke-subtle bg-bg-elevated/40 mx-auto mt-10 max-w-5xl rounded-2xl border p-4 lg:p-5">
      <div className="flex flex-wrap items-center gap-3">
        <span className="text-ink-muted text-xs font-semibold tracking-wide uppercase">
          Xem hạn cho ngày
        </span>
        <div className="min-w-[180px] flex-1">
          <DateInput
            name="for-date-noop"
            defaultValue={currentForDate}
            onChangeISO={(iso) => {
              if (iso && iso !== currentForDate) pushFor(iso);
            }}
            min="1900-01-01"
            max="2100-12-31"
          />
        </div>
        <button
          type="button"
          onClick={() => pushFor("")}
          className="text-ink-secondary hover:text-brand-gold border-stroke-default hover:border-brand-gold/50 rounded-md border px-3 py-1.5 text-xs"
          disabled={isPending}
        >
          Hôm nay
        </button>
        {isPending ? <span className="text-ink-muted text-xs">Đang tính lại…</span> : null}
      </div>
      <p className="text-ink-muted mt-2 text-[11px]">
        Đại vận / lưu niên sẽ tái tính cho ngày đã chọn. Hạn truyền thống lấy theo năm dương lịch.
      </p>
    </div>
  );
}
