"use client";

/**
 * Save-chart button for /tu-vi-tron-doi result page. Hidden when not
 * logged in; shows "Lưu lá số" + label input when logged in.
 *
 * Calls saveChartAction with the current ChartInput and a label.
 */
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Save, Check, AlertCircle, Loader2 } from "lucide-react";
import { saveChartAction } from "@/app/la-so/_actions";
import type { ChartInput } from "@/lib/tuvi/engine";

type Props = {
  input: ChartInput;
  defaultLabel: string;
  isLoggedIn: boolean;
};

export function SaveChartButton({ input, defaultLabel, isLoggedIn }: Props) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [label, setLabel] = useState(defaultLabel);
  const [pending, startTransition] = useTransition();
  const [done, setDone] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  if (!isLoggedIn) {
    // Anonymous → CTA to login (carry current chart as redirect target).
    const href = `/login?from=${encodeURIComponent(typeof window !== "undefined" ? window.location.pathname + window.location.search : "/tu-vi-tron-doi")}`;
    return (
      <a
        href={href}
        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"
      >
        <Save className="h-4 w-4" />
        Đăng nhập để lưu
      </a>
    );
  }

  if (done) {
    return (
      <a
        href={`/la-so#chart-${done}`}
        className="inline-flex items-center gap-1.5 rounded-md border border-emerald-500/40 bg-emerald-500/10 px-3 py-1.5 text-sm text-emerald-300"
      >
        <Check className="h-4 w-4" />
        Đã lưu — Xem trong &quot;Lá số của tôi&quot;
      </a>
    );
  }

  if (!open) {
    return (
      <button
        type="button"
        onClick={() => setOpen(true)}
        className="bg-brand-gold text-bg-base inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-semibold hover:brightness-105"
      >
        <Save className="h-4 w-4" />
        Lưu lá số
      </button>
    );
  }

  function submit() {
    setError(null);
    startTransition(async () => {
      const r = await saveChartAction(input, label);
      if (!r.ok) {
        setError(r.error);
      } else {
        setDone(r.id);
        router.refresh();
      }
    });
  }

  return (
    <div className="border-brand-gold/30 bg-bg-elevated/80 inline-flex items-center gap-2 rounded-md border px-2 py-1.5 backdrop-blur-md">
      <input
        autoFocus
        value={label}
        onChange={(e) => setLabel(e.target.value)}
        onKeyDown={(e) => e.key === "Enter" && submit()}
        placeholder="Nhãn (vd: Mẹ, Vợ, Tôi)"
        className="bg-bg-inset border-stroke-default text-ink-primary w-44 rounded border px-2 py-1 text-xs focus:outline-none"
        maxLength={80}
      />
      <button
        type="button"
        onClick={submit}
        disabled={pending || !label.trim()}
        className="bg-brand-gold text-bg-base inline-flex items-center gap-1 rounded-md px-2.5 py-1 text-xs font-semibold disabled:opacity-50"
      >
        {pending ? <Loader2 className="h-3 w-3 animate-spin" /> : <Save className="h-3 w-3" />}
        Lưu
      </button>
      <button
        type="button"
        onClick={() => setOpen(false)}
        className="text-ink-muted hover:text-brand-red text-xs"
      >
        Hủy
      </button>
      {error ? (
        <span className="text-brand-red-light inline-flex items-center gap-1 text-[11px]">
          <AlertCircle className="h-3 w-3" />
          {error}
        </span>
      ) : null}
    </div>
  );
}
