"use client";

/**
 * فرم ایجاد/ویرایش محصول با جدول تنوع‌ها (رنگ/حجم، قیمت، موجودی).
 * اعتبارسنجی نهایی در سرور انجام می‌شود و خطاها کنار هر فیلد نمایش داده می‌شوند.
 */
import { useRouter } from "next/navigation";
import { useState, useTransition, type ReactNode } from "react";
import { ProductArt } from "@/components/product/ProductArt";
import { Icon } from "@/components/ui/Icon";
import { faNumber } from "@/lib/format";
import { saveProductAction, type ProductFormInput } from "@/server/admin/products";
import type { AdminImage } from "@/server/admin/images";
import { ProductImageManager } from "./ProductImageManager";
import type { ProductShape } from "@/types/catalog";

type Variant = ProductFormInput["variants"][number];

const SHAPES: { value: ProductShape; label: string }[] = [
  { value: "dropper", label: "قطره‌چکان" },
  { value: "bottle", label: "بطری" },
  { value: "pump", label: "پمپی" },
  { value: "tube", label: "تیوپ" },
  { value: "jar", label: "کاسه‌ای" },
  { value: "lipstick", label: "رژلب" },
  { value: "wand", label: "ریمل / برق لب" },
  { value: "compact", label: "پودری" },
  { value: "palette", label: "پالت" },
  { value: "perfume", label: "عطر" },
];
const TAGS = [
  { value: "new", label: "جدید" },
  { value: "limited", label: "نسخه محدود" },
  { value: "exclusive", label: "فقط در زهورا" },
  { value: "bestseller", label: "پرفروش" },
] as const;

interface Props {
  id: number | null;
  initial: ProductFormInput;
  brands: { id: string; name: string }[];
  categories: { id: string; name: string }[];
  skinTypes: { id: string; name: string }[];
  /** عکس‌های فعلی (فقط در ویرایش؛ محصول جدید اول باید ذخیره شود) */
  images?: AdminImage[];
  /** قیمت‌گذاری دلاری دسته «اورجینال»: نرخ مؤثر و گرد کردن برای پیش‌نمایش قیمت تومانی */
  currency: { originalCategoryIds: string[]; rate: number | null; roundTo: number; roundMode: "nearest" | "up" | "down" };
}

/** همان فرمول سرور (src/server/services/currency.ts) فقط برای پیش‌نمایش */
function previewToman(usd: unknown, c: Props["currency"]) {
  const n = Number(String(usd ?? "").replace(/[^\d.]/g, ""));
  if (!c.rate || !n) return null;
  const step = Math.max(1, c.roundTo);
  const fn = c.roundMode === "up" ? Math.ceil : c.roundMode === "down" ? Math.floor : Math.round;
  return Math.max(step, fn((Math.round(n * 100) / 100) * c.rate / step) * step);
}

const emptyVariant = (): Variant => ({ sku: "", colorName: "", colorHex: "", size: "", price: "" as unknown as number, compareAtPrice: "", stock: 0, isActive: true });

function Field({ label, error, children, className = "" }: { label: string; error?: string; children: ReactNode; className?: string }) {
  return (
    <label className={`block ${className}`}>
      <span className="label">{label}</span>
      {children}
      {error && <span className="mt-1 block text-xs font-medium">⚠ {error}</span>}
    </label>
  );
}

export function ProductForm({ id, initial, brands, categories, skinTypes, images, currency }: Props) {
  const router = useRouter();
  const [form, setForm] = useState<ProductFormInput>(initial);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [pending, start] = useTransition();
  const [imageCount, setImageCount] = useState(images?.length ?? 0);

  const set = <K extends keyof ProductFormInput>(key: K, value: ProductFormInput[K]) => setForm((f) => ({ ...f, [key]: value }));
  const setVariant = (i: number, patch: Partial<Variant>) => setForm((f) => ({ ...f, variants: f.variants.map((v, j) => (j === i ? { ...v, ...patch } : v)) }));
  const toggleIn = <T extends string>(list: T[], value: T) => (list.includes(value) ? list.filter((x) => x !== value) : [...list, value]);
  const input = (key: keyof ProductFormInput) => ({
    value: String(form[key] ?? ""),
    onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => set(key, e.target.value as never),
  });

  function submit(e: React.FormEvent) {
    e.preventDefault();
    start(async () => {
      const res = await saveProductAction(id, form);
      if (!res.ok) {
        setErrors(res.errors);
        window.scrollTo({ top: 0, behavior: "smooth" });
        return;
      }
      setErrors({});
      router.push(`/admin/products/${res.id}?saved=1`);
      router.refresh();
    });
  }

  const isOriginal = currency.originalCategoryIds.includes(form.categoryId);
  const previewTone = form.variants.find((v) => v.colorHex)?.colorHex || form.tone;

  return (
    <form onSubmit={submit} noValidate className="grid gap-4 lg:grid-cols-[1fr_320px]">
      <div className="space-y-4">
        {Object.keys(errors).length > 0 && (
          <p className="rounded-xl bg-paper px-4 py-3 text-sm ring-1 ring-ink" role="alert">⚠ لطفاً خطاهای مشخص‌شده را اصلاح کنید. {errors.variants}</p>
        )}

        <section className="space-y-4 rounded-2xl bg-paper p-5">
          <h2 className="text-sm font-bold">اطلاعات اصلی</h2>
          <div className="grid gap-4 sm:grid-cols-2">
            <Field label="نام محصول" error={errors.name} className="sm:col-span-2"><input className="field" maxLength={120} {...input("name")} /></Field>
            <Field label="اسلاگ آدرس (خالی = از روی نام)" error={errors.slug} className="sm:col-span-2"><input className="field" maxLength={140} {...input("slug")} /></Field>
            <Field label="برند" error={errors.brandId}>
              <select className="field" {...input("brandId")}>
                <option value="">انتخاب کنید</option>
                {brands.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
              </select>
            </Field>
            <Field label="دسته" error={errors.categoryId}>
              <select className="field" {...input("categoryId")}>
                <option value="">انتخاب کنید</option>
                {categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </Field>
            <Field label="شماره مجوز بهداشتی (IRC) — اختیاری" error={errors.ircCode}><input className="field" inputMode="numeric" maxLength={24} {...input("ircCode")} /></Field>
            <Field label="کشور سازنده" error={errors.madeIn}><input className="field" maxLength={40} {...input("madeIn")} /></Field>
            <Field label="خلاصه (یک خط)" error={errors.summary} className="sm:col-span-2"><input className="field" maxLength={200} {...input("summary")} /></Field>
            <Field label="توضیحات" error={errors.description} className="sm:col-span-2"><textarea className="field h-28 py-3" maxLength={4000} {...input("description")} /></Field>
            <Field label="روش مصرف" error={errors.howToUse}><textarea className="field h-24 py-3" maxLength={2000} {...input("howToUse")} /></Field>
            <Field label="ترکیبات" error={errors.ingredients}><textarea className="field h-24 py-3" maxLength={2000} {...input("ingredients")} /></Field>
          </div>
          <fieldset>
            <legend className="label">مناسب برای نوع پوست</legend>
            <div className="flex flex-wrap gap-2">
              {skinTypes.map((s) => (
                <button key={s.id} type="button" onClick={() => set("skinTypeIds", toggleIn(form.skinTypeIds, s.id))} className={`chip ${form.skinTypeIds.includes(s.id) ? "chip-active" : ""}`}>{s.name}</button>
              ))}
            </div>
          </fieldset>
          <fieldset>
            <legend className="label">برچسب‌ها</legend>
            <div className="flex flex-wrap gap-2">
              {TAGS.map((t) => (
                <button key={t.value} type="button" onClick={() => set("tags", toggleIn(form.tags, t.value))} className={`chip ${form.tags.includes(t.value) ? "chip-active" : ""}`}>{t.label}</button>
              ))}
            </div>
          </fieldset>
        </section>

        <section className="rounded-2xl bg-paper p-5">
          <div className="mb-4 flex items-center justify-between">
            <div>
              <h2 className="text-sm font-bold">تنوع‌ها (رنگ / حجم، قیمت، موجودی)</h2>
              {isOriginal && (
                <p className="mt-1 text-[11px] leading-5 text-muted">
                  دسته «اورجینال»: فقط قیمت دلاری وارد کنید؛ قیمت تومانی خودکار با نرخ روز {currency.rate ? `(${faNumber(Math.round(currency.rate))} تومان)` : "(هنوز دریافت نشده)"} محاسبه و با هر تغییر نرخ به‌روز می‌شود. مشتری فقط تومان می‌بیند.
                </p>
              )}
            </div>
            <button type="button" className="chip" onClick={() => set("variants", [...form.variants, emptyVariant()])}><Icon name="plus" size={14} /> تنوع جدید</button>
          </div>
          <div className="space-y-3">
            {form.variants.map((v, i) => {
              const err = (f: string) => errors[`variants.${i}.${f}`];
              return (
                <div key={v.id ?? `new-${i}`} className={`grid grid-cols-2 gap-3 rounded-xl border p-3 sm:grid-cols-4 ${v.isActive ? "border-line" : "border-dashed border-line opacity-60"}`}>
                  <Field label="SKU" error={err("sku")}><input className="field h-10" dir="ltr" value={v.sku} onChange={(e) => setVariant(i, { sku: e.target.value })} /></Field>
                  <Field label="نام رنگ" error={err("colorName")}><input className="field h-10" value={v.colorName ?? ""} onChange={(e) => setVariant(i, { colorName: e.target.value })} /></Field>
                  <Field label="کد رنگ" error={err("colorHex")}>
                    <span className="flex gap-2">
                      <input type="color" className="h-10 w-10 shrink-0 cursor-pointer rounded-lg border border-line" value={v.colorHex || "#cccccc"} onChange={(e) => setVariant(i, { colorHex: e.target.value })} aria-label="انتخاب رنگ" />
                      <input className="field h-10" dir="ltr" placeholder="#RRGGBB" value={v.colorHex ?? ""} onChange={(e) => setVariant(i, { colorHex: e.target.value })} />
                    </span>
                  </Field>
                  <Field label="حجم / وزن" error={err("size")}><input className="field h-10" value={v.size ?? ""} onChange={(e) => setVariant(i, { size: e.target.value })} /></Field>
                  {isOriginal ? (
                    <>
                      <Field label="قیمت (دلار USD)" error={err("priceUsd")}>
                        <input className="field h-10" inputMode="decimal" dir="ltr" placeholder="49.90" value={String(v.priceUsd ?? "")} onChange={(e) => setVariant(i, { priceUsd: e.target.value as unknown as number })} />
                        <span className="mt-1 block text-[11px] text-muted">= {(() => { const t = previewToman(v.priceUsd, currency); return t ? `${faNumber(t)} تومان` : "—"; })()}</span>
                      </Field>
                      <Field label="قبل از تخفیف (دلار، اختیاری)" error={err("compareAtUsd")}>
                        <input className="field h-10" inputMode="decimal" dir="ltr" placeholder="59.90" value={String(v.compareAtUsd ?? "")} onChange={(e) => setVariant(i, { compareAtUsd: e.target.value as unknown as number })} />
                        <span className="mt-1 block text-[11px] text-muted">{(() => { const t = previewToman(v.compareAtUsd, currency); return t ? `= ${faNumber(t)} تومان` : "حراج ندارد"; })()}</span>
                      </Field>
                    </>
                  ) : (
                    <>
                      <Field label="قیمت (تومان)" error={err("price")}><input className="field h-10" inputMode="numeric" value={String(v.price ?? "")} onChange={(e) => setVariant(i, { price: e.target.value as unknown as number })} /></Field>
                      <Field label="قیمت قبل از تخفیف" error={err("compareAtPrice")}><input className="field h-10" inputMode="numeric" value={String(v.compareAtPrice ?? "")} onChange={(e) => setVariant(i, { compareAtPrice: e.target.value as unknown as number })} /></Field>
                    </>
                  )}
                  <Field label="موجودی" error={err("stock")}><input className="field h-10" inputMode="numeric" value={String(v.stock)} onChange={(e) => setVariant(i, { stock: e.target.value as unknown as number })} /></Field>
                  <div className="flex items-end justify-between gap-2">
                    <label className="flex h-10 items-center gap-2 text-xs"><input type="checkbox" className="accent-ink" checked={v.isActive} onChange={(e) => setVariant(i, { isActive: e.target.checked })} /> فعال</label>
                    {form.variants.length > 1 && (
                      <button type="button" className="grid size-10 place-items-center rounded-full hover:bg-mist" aria-label="حذف تنوع" onClick={() => set("variants", form.variants.filter((_, j) => j !== i))}><Icon name="trash" size={16} /></button>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
          <p className="mt-3 text-[11px] leading-5 text-muted">تنوعی که در سفارشی استفاده شده باشد با حذف، فقط غیرفعال می‌شود تا سابقه سفارش‌ها حفظ شود.</p>
        </section>
      </div>

      <aside className="space-y-4">
        <section className="space-y-4 rounded-2xl bg-paper p-5">
          <h2 className="text-sm font-bold">عکس‌های محصول</h2>
          {id ? (
            <ProductImageManager
              productId={id}
              initial={images ?? []}
              variants={form.variants.filter((v) => v.id).map((v) => ({ id: v.id!, label: [v.colorName, v.size].filter(Boolean).join(" · ") || v.sku }))}
              onChange={(list) => setImageCount(list.length)}
            />
          ) : (
            <p className="rounded-xl bg-mist px-3 py-2 text-xs leading-5">برای آپلود عکس، اول محصول را ایجاد کنید.</p>
          )}
        </section>
        <section className="space-y-4 rounded-2xl bg-paper p-5">
          <h2 className="text-sm font-bold">{imageCount ? "تصویر جایگزین (بدون عکس)" : "تصویر موقت و نمایش"}</h2>
          <div className={`aspect-square rounded-xl bg-mist ${imageCount ? "mx-auto w-24" : ""}`}>
            <ProductArt shape={form.shape as ProductShape} tone={/^#[0-9a-f]{6}$/i.test(previewTone ?? "") ? previewTone! : "#dddddd"} label="ZAHORA" className="size-full" />
          </div>
          <Field label="شکل ظرف (تصویر موقت)">
            <select className="field h-10" {...input("shape")}>
              {SHAPES.map((s) => <option key={s.value} value={s.value}>{s.label}</option>)}
            </select>
          </Field>
          <Field label="رنگ پایه ظرف" error={errors.tone}>
            <span className="flex gap-2">
              <input type="color" className="h-10 w-10 shrink-0 cursor-pointer rounded-lg border border-line" value={form.tone} onChange={(e) => set("tone", e.target.value)} aria-label="رنگ پایه" />
              <input className="field h-10" dir="ltr" {...input("tone")} />
            </span>
          </Field>
          <p className="text-[11px] leading-5 text-muted">{imageCount ? "این طرح فقط وقتی نمایش داده می‌شود که همه عکس‌ها حذف شوند." : "تا زمان آپلود عکس واقعی، تصویر برداری از روی شکل و رنگ ساخته می‌شود."}</p>
          <label className="flex items-center gap-2 text-sm"><input type="checkbox" className="size-4 accent-ink" checked={form.isActive} onChange={(e) => set("isActive", e.target.checked)} /> نمایش در فروشگاه</label>
          <button className="btn-primary w-full" disabled={pending}>{pending ? "در حال ذخیره…" : id ? "ذخیره تغییرات" : "ایجاد محصول"}</button>
        </section>
      </aside>
    </form>
  );
}
