"use client";

/** نرخ دلار: بروزرسانی دستی، نرخ دستی (override)، فاصله بروزرسانی، حاشیه سود و گرد کردن */
import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { faNumber, formatToman } from "@/lib/format";
import { refreshRateAction, saveCurrencySettingsAction } from "@/server/admin/currency";

interface Props {
  initial: { useManual: boolean; manualRate: number | null; intervalMinutes: number; marginPercent: number; roundTo: number; roundMode: "nearest" | "up" | "down" };
  baseRate: number | null;
  jumpBlocked: boolean;
}

const ROUND_OPTIONS = [
  { v: 1, label: "بدون گرد کردن" },
  { v: 100, label: "۱۰۰ تومان" },
  { v: 1000, label: "۱٬۰۰۰ تومان" },
  { v: 10000, label: "۱۰٬۰۰۰ تومان" },
];

/** پیش‌نمایش قیمت ۱۰۰ دلاری با تنظیمات فعلی فرم (همان فرمول سرور) */
function preview(rate: number | null, f: Props["initial"]) {
  const base = f.useManual && f.manualRate ? f.manualRate : rate;
  if (!base) return null;
  const raw = 100 * base * (1 + f.marginPercent / 100);
  const step = Math.max(1, f.roundTo);
  const fn = f.roundMode === "up" ? Math.ceil : f.roundMode === "down" ? Math.floor : Math.round;
  return fn(raw / step) * step;
}

export function CurrencySettingsForm({ initial, baseRate, jumpBlocked }: Props) {
  const router = useRouter();
  const [f, setF] = useState(initial);
  const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
  const [pending, start] = useTransition();
  const set = <K extends keyof typeof f>(k: K, v: (typeof f)[K]) => setF((p) => ({ ...p, [k]: v }));
  const example = preview(baseRate, f);

  function refresh(allowJump = false) {
    setMsg(null);
    start(async () => {
      const r = await refreshRateAction(allowJump);
      setMsg(r.ok ? { ok: true, text: `نرخ به‌روز شد: ${formatToman(r.rateToman)}` } : { ok: false, text: r.error });
      router.refresh();
    });
  }

  function save() {
    setMsg(null);
    start(async () => {
      const r = await saveCurrencySettingsAction({ ...f, manualRate: f.manualRate ?? "" });
      setMsg(r.ok ? { ok: true, text: `تنظیمات ذخیره شد؛ قیمت ${faNumber(r.repriced)} تنوع به‌روز شد` } : { ok: false, text: r.error });
      if (r.ok) router.refresh();
    });
  }

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap gap-3">
        <button type="button" className="btn-primary h-11 px-6" disabled={pending} onClick={() => refresh()}>{pending ? "…" : "بروزرسانی دستی نرخ"}</button>
        {jumpBlocked && (
          <button type="button" className="btn-outline h-11 px-6" disabled={pending} onClick={() => confirm("نرخ جدید بیش از ۲۰٪ با نرخ قبلی فرق دارد. مطمئنید نرخ درست است و قیمت‌ها با آن محاسبه شوند؟") && refresh(true)}>
            پذیرش نرخ جدید (تغییر بیش از ۲۰٪)
          </button>
        )}
      </div>
      {msg && <p role="status" className={`rounded-xl px-4 py-3 text-sm ${msg.ok ? "bg-paper" : "bg-paper ring-1 ring-ink"}`}>{msg.ok ? "✓" : "⚠"} {msg.text}</p>}

      <section className="grid gap-4 rounded-2xl bg-paper p-5 md:grid-cols-2">
        <div className="space-y-3">
          <h2 className="text-sm font-bold">نرخ دستی (برای وقتی منبع در دسترس نیست)</h2>
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" className="size-4 accent-ink" checked={f.useManual} onChange={(e) => set("useManual", e.target.checked)} />
            قیمت‌ها با نرخ دستی محاسبه شوند
          </label>
          <label className="block">
            <span className="label">نرخ دستی دلار (تومان)</span>
            <input className="field h-10" inputMode="numeric" dir="ltr" placeholder="مثلاً 105000" value={f.manualRate ?? ""} onChange={(e) => set("manualRate", e.target.value ? Number(e.target.value.replace(/[^\d]/g, "")) || null : null)} />
          </label>
          <label className="block">
            <span className="label">فاصله بروزرسانی خودکار (دقیقه)</span>
            <input className="field h-10 max-w-32" type="number" min={10} max={60} value={f.intervalMinutes} onChange={(e) => set("intervalMinutes", Number(e.target.value))} />
          </label>
        </div>
        <div className="space-y-3">
          <h2 className="text-sm font-bold">محاسبه قیمت تومانی</h2>
          <label className="block">
            <span className="label">حاشیه سود روی نرخ دلار (٪)</span>
            <input className="field h-10 max-w-32" type="number" min={0} max={100} step={0.5} value={f.marginPercent} onChange={(e) => set("marginPercent", Number(e.target.value))} />
          </label>
          <label className="block">
            <span className="label">گرد کردن به مضرب</span>
            <select className="field h-10" value={f.roundTo} onChange={(e) => set("roundTo", Number(e.target.value))}>
              {ROUND_OPTIONS.map((o) => <option key={o.v} value={o.v}>{o.label}</option>)}
            </select>
          </label>
          <label className="block">
            <span className="label">جهت گرد کردن</span>
            <select className="field h-10" value={f.roundMode} onChange={(e) => set("roundMode", e.target.value as typeof f.roundMode)}>
              <option value="nearest">نزدیک‌ترین</option>
              <option value="up">رو به بالا</option>
              <option value="down">رو به پایین</option>
            </select>
          </label>
          <p className="rounded-xl bg-mist px-3 py-2 text-xs">پیش‌نمایش: محصول ۱۰۰ دلاری = <b>{example ? formatToman(example) : "—"}</b></p>
        </div>
        <div className="md:col-span-2">
          <button type="button" className="btn-primary h-11 px-6" disabled={pending} onClick={save}>{pending ? "در حال ذخیره…" : "ذخیره و محاسبه دوباره قیمت‌ها"}</button>
        </div>
      </section>
    </div>
  );
}
