import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { BackHeader, Btn, cn } from "@/pages/app/components/ui";
import { Field, Select, TextArea, TextInput, UploadBox } from "@/pages/app/components/bo/BoUI";
import { businessFields } from "@/mocks/dshnBusiness";

export default function BizProductForm() {
  const { goBack, params, jump, products, saveProduct } = useApp();
  const editing = products.find((p) => p.id === params.productId);

  const [images, setImages] = useState(Boolean(editing));
  const [name, setName] = useState(editing?.name ?? "");
  const [desc, setDesc] = useState(editing?.description ?? "");
  const [category, setCategory] = useState(editing?.category ?? "أغذية ومشروبات");
  const [method, setMethod] = useState<"fixed" | "negotiable">(
    editing?.negotiable ? "negotiable" : "fixed",
  );
  const [price, setPrice] = useState(editing?.price ? String(editing.price) : "");
  const [minOrder, setMinOrder] = useState(String(editing?.minOrder ?? 1));
  const [qty, setQty] = useState(String(editing?.stock ?? ""));

  const valid =
    images &&
    name.trim().length > 1 &&
    Boolean(category) &&
    qty.trim() !== "" &&
    (method === "negotiable" || price.trim() !== "");

  const handleSave = () => {
    if (!valid) return;
    saveProduct({
      id: editing?.id,
      name: name.trim(),
      description: desc.trim(),
      category,
      negotiable: method === "negotiable",
      price: method === "negotiable" ? null : Number(price) || 0,
      minOrder: Number(minOrder) || 1,
      stock: Number(qty) || 0,
    });
    jump("bizProducts");
  };

  return (
    <div className="min-h-full flex flex-col bg-background-50">
      <BackHeader title={editing ? "تعديل منتج" : "إضافة منتج"} onBack={goBack} />

      <div className="flex-1 px-4 py-5 space-y-4">
        <UploadBox label="رفع صور" hint="أضف صورة واحدة على الأقل (مربعة)" filled={images} onToggle={() => setImages((v) => !v)} />

        <Field label="اسم المنتج" required>
          <TextInput value={name} onChange={setName} placeholder="مثال: عسل سدر جبلي فاخر" />
        </Field>

        <Field label="الوصف">
          <TextArea value={desc} onChange={setDesc} placeholder="اكتب وصفًا تفصيليًا للمنتج..." rows={4} />
        </Field>

        <Field label="التصنيف" required>
          <Select value={category} onChange={setCategory} options={businessFields} />
        </Field>

        <Field label="طريقة البيع" required>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => setMethod("fixed")}
              className={cn(
                "flex-1 h-[52px] rounded-[13px] text-[13px] font-semibold flex items-center justify-center gap-1.5 cursor-pointer transition-colors",
                method === "fixed" ? "bg-primary-500 text-background-50" : "bg-background-100 border border-background-200 text-foreground-700",
              )}
            >
              <i className="ri-price-tag-3-line text-[16px] leading-none" />
              سعر محدد
            </button>
            <button
              type="button"
              onClick={() => setMethod("negotiable")}
              className={cn(
                "flex-1 h-[52px] rounded-[13px] text-[13px] font-semibold flex items-center justify-center gap-1.5 cursor-pointer transition-colors",
                method === "negotiable" ? "bg-primary-500 text-background-50" : "bg-background-100 border border-background-200 text-foreground-700",
              )}
            >
              <i className="ri-chat-3-line text-[16px] leading-none" />
              حسب التفاوض
            </button>
          </div>
        </Field>

        {method === "fixed" && (
          <Field label="السعر (ر.س)" required>
            <TextInput value={price} onChange={(v) => setPrice(v.replace(/[^\d.]/g, ""))} placeholder="0.00" dir="ltr" />
          </Field>
        )}

        <div className="grid grid-cols-2 gap-3">
          <Field label="الحد الأدنى للطلب" required>
            <TextInput value={minOrder} onChange={(v) => setMinOrder(v.replace(/\D/g, ""))} placeholder="1" dir="ltr" />
          </Field>
          <Field label="الكمية المتاحة" required>
            <TextInput value={qty} onChange={(v) => setQty(v.replace(/\D/g, ""))} placeholder="0" dir="ltr" />
          </Field>
        </div>
      </div>

      <div className="sticky bottom-0 z-30 px-4 py-4 bg-background-50 border-t border-background-200/70">
        <Btn full disabled={!valid} onClick={handleSave}>
          حفظ المنتج
        </Btn>
      </div>
    </div>
  );
}