import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { useState, useEffect, useRef } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Flame, Swords, Gamepad2, Mailbox, Handshake, Megaphone, X, ImagePlus, Images, UploadCloud, Plus, ChevronDown } from "lucide-react";
import { s as supabase } from "./client-Dz5aErML.js";
const CATEGORIES = [
  { v: "Free Fire", label: "Free Fire", icon: Flame },
  { v: "Mobile Legends", label: "Mobile Legends", icon: Swords },
  { v: "Rental", label: "Rental", icon: Gamepad2 },
  { v: "JasaPost", label: "JasaPost", icon: Mailbox },
  { v: "Partner Resmi Bang Pergam", label: "Partner Resmi", icon: Handshake },
  { v: "Paid Promote Bang Pergam", label: "Paid Promote", icon: Megaphone }
];
function CustomSelect({ options, value, onChange, placeholder }) {
  const [isOpen, setIsOpen] = useState(false);
  const selectRef = useRef(null);
  const selectedOption = options.find((option) => option.value === value);
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (selectRef.current && !selectRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);
  const handleOptionClick = (optionValue) => {
    onChange(optionValue);
    setIsOpen(false);
  };
  return /* @__PURE__ */ jsxs("div", { className: "relative", ref: selectRef, children: [
    /* @__PURE__ */ jsxs(
      "button",
      {
        type: "button",
        className: "input flex w-full items-center justify-between gap-2 cursor-pointer transition-all hover:border-primary/50",
        onClick: () => setIsOpen(!isOpen),
        "aria-haspopup": "listbox",
        "aria-expanded": isOpen,
        children: [
          selectedOption ? /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-2", children: [
            selectedOption.icon && /* @__PURE__ */ jsx(selectedOption.icon, { className: "h-4 w-4" }),
            selectedOption.label
          ] }) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: placeholder }),
          /* @__PURE__ */ jsx(ChevronDown, { className: `h-4 w-4 transition-transform ${isOpen ? "rotate-180" : ""}` })
        ]
      }
    ),
    isOpen && /* @__PURE__ */ jsx(
      "ul",
      {
        role: "listbox",
        className: "absolute z-20 mt-2 max-h-60 w-full overflow-auto rounded-2xl border border-border bg-card/95 p-1.5 shadow-xl backdrop-blur-xl animate-fade-up",
        children: options.map((option) => /* @__PURE__ */ jsxs(
          "li",
          {
            role: "option",
            "aria-selected": option.value === value,
            onClick: () => handleOptionClick(option.value),
            className: `flex cursor-pointer items-center gap-2.5 px-3 py-2.5 text-sm rounded-xl transition-all ${option.value === value ? "bg-primary text-primary-foreground font-bold" : "text-foreground hover:bg-primary/10 hover:text-primary"}`,
            children: [
              option.icon && /* @__PURE__ */ jsx(option.icon, { className: `h-4 w-4 ${option.value === value ? "" : "opacity-70"}` }),
              option.label
            ]
          },
          option.value
        ))
      }
    )
  ] });
}
function ProductForm({ productId }) {
  const navigate = useNavigate();
  const isEdit = !!productId;
  const [loading, setLoading] = useState(isEdit);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const getDraftValue = (key, defaultValue) => {
    if (isEdit) return defaultValue;
    if (typeof window === "undefined") return defaultValue;
    try {
      const saved = localStorage.getItem("pergam_new_product_draft");
      if (saved) {
        const draft = JSON.parse(saved);
        if (draft[key] !== void 0) return draft[key];
      }
    } catch (e) {
      console.error("Error reading draft key:", key, e);
    }
    return defaultValue;
  };
  const [name, setName] = useState(() => getDraftValue("name", ""));
  const [game, setGame] = useState(() => getDraftValue("game", "Free Fire"));
  const [price, setPrice] = useState(() => getDraftValue("price", 0));
  const [status, setStatus] = useState(() => getDraftValue("status", "Ready"));
  const [description, setDescription] = useState(() => getDraftValue("description", ""));
  const [mainImage, setMainImage] = useState(() => getDraftValue("mainImage", ""));
  const [gallery, setGallery] = useState(() => getDraftValue("gallery", []));
  const [packages, setPackages] = useState(() => getDraftValue("packages", []));
  const [uploading, setUploading] = useState(false);
  const [readyEstimate, setReadyEstimate] = useState(() => getDraftValue("readyEstimate", ""));
  const [whatsappNumber, setWhatsappNumber] = useState(() => getDraftValue("whatsappNumber", ""));
  const [whatsappChannelUrl, setWhatsappChannelUrl] = useState(() => getDraftValue("whatsappChannelUrl", ""));
  useEffect(() => {
    if (!isEdit) return;
    (async () => {
      const [{ data: prod }, { data: imgs }, { data: pkgs }] = await Promise.all([
        supabase.from("products").select("*").eq("id", productId).single(),
        supabase.from("product_images").select("*").eq("product_id", productId).order("sort_order"),
        supabase.from("rental_packages").select("*").eq("product_id", productId).order("sort_order")
      ]);
      if (prod) {
        setName(prod.name);
        setGame(prod.game);
        setPrice(prod.price);
        setStatus(prod.status);
        setDescription(prod.description);
        setMainImage(prod.image_url ?? "");
        setWhatsappNumber(prod.whatsapp_number ?? "");
        setWhatsappChannelUrl(
          prod.whatsapp_channel_url ?? ""
        );
        if (prod.ready_estimate_at) {
          const d = new Date(prod.ready_estimate_at);
          const pad = (n) => String(n).padStart(2, "0");
          setReadyEstimate(
            `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`
          );
        }
      }
      setGallery((imgs ?? []).map((i) => ({ id: i.id, url: i.image_url })));
      setPackages((pkgs ?? []).map((p) => ({ id: p.id, duration: p.duration, price: p.price })));
      setLoading(false);
    })();
  }, [productId, isEdit]);
  useEffect(() => {
    if (isEdit || saving) return;
    const draft = {
      name,
      game,
      price,
      status,
      description,
      mainImage,
      gallery,
      packages,
      readyEstimate,
      whatsappNumber,
      whatsappChannelUrl
    };
    try {
      localStorage.setItem("pergam_new_product_draft", JSON.stringify(draft));
    } catch (e) {
      console.error("Failed to save product draft to localStorage", e);
    }
  }, [
    isEdit,
    saving,
    name,
    game,
    price,
    status,
    description,
    mainImage,
    gallery,
    packages,
    readyEstimate,
    whatsappNumber,
    whatsappChannelUrl
  ]);
  const clearDraft = () => {
    if (!isEdit) {
      try {
        localStorage.removeItem("pergam_new_product_draft");
      } catch (e) {
        console.error("Failed to clear product draft from localStorage", e);
      }
    }
  };
  const uploadFile = async (file) => {
    setUploading(true);
    const ext = file.name.split(".").pop() ?? "jpg";
    const path = `uploads/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
    const { error: upErr } = await supabase.storage.from("product-images").upload(path, file, { contentType: file.type });
    setUploading(false);
    if (upErr) {
      setError("Upload gagal: " + upErr.message);
      return null;
    }
    const { data } = supabase.storage.from("product-images").getPublicUrl(path);
    return data.publicUrl;
  };
  const handleMainImageUpload = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const url = await uploadFile(file);
    if (url) setMainImage(url);
    e.target.value = "";
  };
  const handleGalleryUpload = async (e) => {
    const files = Array.from(e.target.files ?? []);
    for (const file of files) {
      const url = await uploadFile(file);
      if (url) setGallery((g) => [...g, { url, isNew: true }]);
    }
    e.target.value = "";
  };
  const handleSave = async (e) => {
    e.preventDefault();
    setError("");
    setSaving(true);
    let pid = productId;
    const readyEstIso = game === "Rental" && status === "Not Available" && readyEstimate ? new Date(readyEstimate).toISOString() : null;
    const isPartnerLike = game === "Partner Resmi Bang Pergam" || game === "Paid Promote Bang Pergam";
    const waNumberClean = isPartnerLike ? whatsappNumber.replace(/[^0-9]/g, "") || null : null;
    const waChannelClean = isPartnerLike ? whatsappChannelUrl.trim() || null : null;
    if (isEdit) {
      const { error: upErr } = await supabase.from("products").update({
        name,
        game,
        price,
        status,
        description,
        image_url: mainImage || null,
        ready_estimate_at: readyEstIso,
        whatsapp_number: waNumberClean,
        whatsapp_channel_url: waChannelClean
      }).eq("id", productId);
      if (upErr) {
        setError(upErr.message);
        setSaving(false);
        return;
      }
    } else {
      const { data, error: insErr } = await supabase.from("products").insert({
        name,
        game,
        price,
        status,
        description,
        image_url: mainImage || null,
        ready_estimate_at: readyEstIso,
        whatsapp_number: waNumberClean,
        whatsapp_channel_url: waChannelClean
      }).select("id").single();
      if (insErr || !data) {
        setError(insErr?.message ?? "Gagal membuat produk");
        setSaving(false);
        return;
      }
      pid = data.id;
    }
    if (!pid) {
      setSaving(false);
      return;
    }
    await supabase.from("product_images").delete().eq("product_id", pid);
    if (gallery.length > 0) {
      await supabase.from("product_images").insert(
        gallery.map((g, i) => ({
          product_id: pid,
          image_url: g.url,
          sort_order: i
        }))
      );
    }
    await supabase.from("rental_packages").delete().eq("product_id", pid);
    if (game === "Rental" && packages.length > 0) {
      await supabase.from("rental_packages").insert(
        packages.map((p, i) => ({
          product_id: pid,
          duration: p.duration,
          price: p.price,
          sort_order: i
        }))
      );
    }
    setSaving(false);
    clearDraft();
    navigate({ to: "/adminpergam" });
  };
  if (loading) {
    return /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: "Memuat..." });
  }
  return /* @__PURE__ */ jsxs("form", { onSubmit: handleSave, className: "max-w-6xl space-y-6", children: [
    /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 items-start gap-6 lg:grid-cols-2", children: [
      /* @__PURE__ */ jsxs("div", { className: "card-surface h-full space-y-4 rounded-2xl p-6", children: [
        /* @__PURE__ */ jsx("h2", { className: "font-display text-lg font-bold", children: "Informasi Produk" }),
        /* @__PURE__ */ jsx(Field, { label: "Nama Produk", children: /* @__PURE__ */ jsx(
          "input",
          {
            required: true,
            value: name,
            onChange: (e) => setName(e.target.value),
            className: "input"
          }
        ) }),
        /* @__PURE__ */ jsxs("div", { className: "grid gap-4 sm:grid-cols-2", children: [
          /* @__PURE__ */ jsx(Field, { label: "Kategori", children: /* @__PURE__ */ jsx(
            CustomSelect,
            {
              options: CATEGORIES.map((cat) => ({ value: cat.v, label: cat.label, icon: cat.icon })),
              value: game,
              onChange: (value) => setGame(value),
              placeholder: "Pilih Kategori"
            }
          ) }),
          /* @__PURE__ */ jsx(Field, { label: "Status", children: /* @__PURE__ */ jsxs(
            "select",
            {
              value: status,
              onChange: (e) => setStatus(e.target.value),
              className: "input",
              children: [
                /* @__PURE__ */ jsx("option", { value: "Ready", children: "Ready" }),
                /* @__PURE__ */ jsx("option", { value: "Not Available", children: "Not Available" })
              ]
            }
          ) })
        ] }),
        /* @__PURE__ */ jsx(Field, { label: "Harga (IDR)", children: /* @__PURE__ */ jsx(
          "input",
          {
            type: "number",
            min: 0,
            value: price,
            onChange: (e) => setPrice(Number(e.target.value)),
            className: "input",
            placeholder: "0 jika hanya pakai paket rental"
          }
        ) }),
        (game === "Partner Resmi Bang Pergam" || game === "Paid Promote Bang Pergam") && /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsxs(Field, { label: "Nomor WhatsApp (CTA)", children: [
            /* @__PURE__ */ jsx(
              "input",
              {
                required: true,
                value: whatsappNumber,
                onChange: (e) => setWhatsappNumber(e.target.value),
                className: "input",
                placeholder: "Contoh: 6282312715218"
              }
            ),
            /* @__PURE__ */ jsx("span", { className: "mt-1 block text-[11px] text-muted-foreground", children: 'Tombol WhatsApp pada produk ini akan mengarah ke nomor tersebut. Gunakan format internasional tanpa "+".' })
          ] }),
          /* @__PURE__ */ jsxs(Field, { label: "Link Saluran WhatsApp (opsional)", children: [
            /* @__PURE__ */ jsx(
              "input",
              {
                value: whatsappChannelUrl,
                onChange: (e) => setWhatsappChannelUrl(e.target.value),
                className: "input",
                placeholder: "https://whatsapp.com/channel/..."
              }
            ),
            /* @__PURE__ */ jsx("span", { className: "mt-1 block text-[11px] text-muted-foreground", children: "Jika diisi, akan muncul tombol CTA tambahan untuk saluran WhatsApp pada produk ini. Kosongkan jika tidak ingin menampilkan." })
          ] })
        ] }),
        /* @__PURE__ */ jsx(Field, { label: "Deskripsi", children: /* @__PURE__ */ jsx(
          "textarea",
          {
            required: true,
            rows: 4,
            value: description,
            onChange: (e) => setDescription(e.target.value),
            className: "input resize-y"
          }
        ) }),
        game === "Rental" && status === "Not Available" && /* @__PURE__ */ jsxs(Field, { label: "Estimasi Ready (WIB)", children: [
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "datetime-local",
              value: readyEstimate,
              onChange: (e) => setReadyEstimate(e.target.value),
              className: "input"
            }
          ),
          /* @__PURE__ */ jsx("span", { className: "mt-1 block text-[11px] text-muted-foreground", children: "Setelah waktu ini terlewati, status otomatis menjadi Ready di website." })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "card-surface h-full rounded-2xl p-5 sm:p-6", children: [
        /* @__PURE__ */ jsxs("div", { className: "mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("h2", { className: "font-display text-lg font-bold", children: "Foto Produk" }),
            /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: "Foto utama tampil di katalog. Galeri tampil di detail produk." })
          ] }),
          uploading && /* @__PURE__ */ jsx("span", { className: "inline-flex w-fit items-center rounded-full border border-primary/20 bg-primary/10 px-3 py-1 text-xs font-bold text-primary", children: "Upload..." })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "grid gap-5", children: [
          /* @__PURE__ */ jsxs("section", { className: "space-y-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ jsx("h3", { className: "text-xs font-bold uppercase tracking-wider text-muted-foreground", children: "Foto Utama" }),
              mainImage && /* @__PURE__ */ jsxs(
                "button",
                {
                  type: "button",
                  onClick: () => setMainImage(""),
                  className: "inline-flex items-center gap-1.5 rounded-full border border-destructive/30 px-3 py-1.5 text-xs font-bold text-destructive transition hover:bg-destructive/10",
                  children: [
                    /* @__PURE__ */ jsx(X, { className: "h-3.5 w-3.5" }),
                    "Hapus"
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ jsx(
              "label",
              {
                htmlFor: "main-image-upload",
                className: "group flex min-h-[19rem] cursor-pointer flex-col items-center justify-center overflow-hidden rounded-2xl border border-dashed border-primary/35 bg-primary/5 text-center transition hover:border-primary/70 hover:bg-primary/10",
                children: mainImage ? /* @__PURE__ */ jsx("img", { src: mainImage, alt: "", className: "h-full max-h-[22rem] w-full object-cover" }) : /* @__PURE__ */ jsxs("div", { className: "flex max-w-xs flex-col items-center gap-3 px-5", children: [
                  /* @__PURE__ */ jsx("span", { className: "grid h-14 w-14 place-items-center rounded-2xl bg-card text-primary shadow-sm", children: /* @__PURE__ */ jsx(ImagePlus, { className: "h-7 w-7", strokeWidth: 1.8 }) }),
                  /* @__PURE__ */ jsxs("div", { children: [
                    /* @__PURE__ */ jsx("div", { className: "text-sm font-bold text-foreground", children: "Pilih foto utama" }),
                    /* @__PURE__ */ jsx("div", { className: "mt-1 text-xs leading-5 text-muted-foreground", children: "Disarankan rasio 3:4 agar tampilan katalog tetap rapi." })
                  ] })
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              "input",
              {
                id: "main-image-upload",
                type: "file",
                accept: "image/*",
                onChange: handleMainImageUpload,
                className: "sr-only"
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("section", { className: "space-y-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
              /* @__PURE__ */ jsx("h3", { className: "text-xs font-bold uppercase tracking-wider text-muted-foreground", children: "Galeri Tambahan" }),
              /* @__PURE__ */ jsxs("span", { className: "rounded-full border border-border bg-card/70 px-2.5 py-1 text-xs text-muted-foreground", children: [
                gallery.length,
                " gambar"
              ] })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3 sm:grid-cols-3", children: [
              gallery.map((g, i) => /* @__PURE__ */ jsxs(
                "div",
                {
                  className: "relative aspect-square overflow-hidden rounded-xl border border-border bg-muted",
                  children: [
                    /* @__PURE__ */ jsx("img", { src: g.url, alt: "", className: "h-full w-full object-cover" }),
                    /* @__PURE__ */ jsx(
                      "button",
                      {
                        type: "button",
                        onClick: () => setGallery(gallery.filter((_, idx) => idx !== i)),
                        className: "group absolute right-2 top-2 grid h-7 w-7 place-items-center rounded-full bg-destructive text-destructive-foreground shadow-sm transition-transform hover:scale-105",
                        "aria-label": "Hapus gambar galeri",
                        children: /* @__PURE__ */ jsx(X, { className: "h-3.5 w-3.5 transition-transform group-hover:rotate-90" })
                      }
                    )
                  ]
                },
                i
              )),
              /* @__PURE__ */ jsxs(
                "label",
                {
                  htmlFor: "gallery-upload",
                  className: "flex aspect-square cursor-pointer flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-border bg-card/50 px-3 text-center text-muted-foreground transition hover:border-primary/60 hover:bg-primary/10 hover:text-primary",
                  children: [
                    gallery.length > 0 ? /* @__PURE__ */ jsx(Images, { className: "h-7 w-7", strokeWidth: 1.8 }) : /* @__PURE__ */ jsx(UploadCloud, { className: "h-7 w-7", strokeWidth: 1.8 }),
                    /* @__PURE__ */ jsx("span", { className: "text-xs font-bold", children: "Tambah foto" })
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ jsx(
              "input",
              {
                id: "gallery-upload",
                type: "file",
                accept: "image/*",
                multiple: true,
                onChange: handleGalleryUpload,
                className: "sr-only"
              }
            )
          ] })
        ] })
      ] })
    ] }),
    game === "Rental" && /* @__PURE__ */ jsxs("div", { className: "card-surface rounded-2xl p-6 space-y-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsx("h2", { className: "font-display font-bold text-lg", children: "Paket Rental" }),
        /* @__PURE__ */ jsxs(
          "button",
          {
            type: "button",
            onClick: () => setPackages([...packages, { duration: "", price: 0 }]),
            className: "group inline-flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-full bg-primary text-primary-foreground",
            children: [
              /* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5 transition-transform group-hover:rotate-90" }),
              "Tambah Paket"
            ]
          }
        )
      ] }),
      packages.length === 0 && /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: 'Belum ada paket. Klik "Tambah Paket".' }),
      packages.map((p, i) => /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-[1fr_1fr_auto] gap-2 items-end", children: [
        /* @__PURE__ */ jsx(Field, { label: i === 0 ? "Durasi" : "", children: /* @__PURE__ */ jsx(
          "input",
          {
            required: true,
            value: p.duration,
            onChange: (e) => {
              const next = [...packages];
              next[i] = { ...p, duration: e.target.value };
              setPackages(next);
            },
            placeholder: "6 Jam",
            className: "input"
          }
        ) }),
        /* @__PURE__ */ jsx(Field, { label: i === 0 ? "Harga" : "", children: /* @__PURE__ */ jsx(
          "input",
          {
            required: true,
            type: "number",
            min: 0,
            value: p.price,
            onChange: (e) => {
              const next = [...packages];
              next[i] = { ...p, price: Number(e.target.value) };
              setPackages(next);
            },
            className: "input"
          }
        ) }),
        /* @__PURE__ */ jsx(
          "button",
          {
            type: "button",
            onClick: () => setPackages(packages.filter((_, idx) => idx !== i)),
            className: "h-11 px-3 rounded-xl border border-destructive/40 text-destructive text-xs",
            children: "Hapus"
          }
        )
      ] }, i))
    ] }),
    error && /* @__PURE__ */ jsx("div", { className: "text-sm text-destructive bg-destructive/10 border border-destructive/30 rounded-xl px-4 py-2", children: error }),
    /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap justify-end gap-3 sticky bottom-4 z-10 -mx-3 rounded-2xl border border-border/50 bg-card/80 p-3 backdrop-blur-xl sm:mx-0 sm:bg-transparent sm:p-0 sm:border-transparent sm:backdrop-blur-none", children: [
      /* @__PURE__ */ jsx(
        "button",
        {
          type: "button",
          onClick: () => {
            clearDraft();
            navigate({ to: "/adminpergam" });
          },
          className: "px-5 py-2.5 rounded-full border border-border hover:border-primary/50 text-sm",
          children: "Batal"
        }
      ),
      /* @__PURE__ */ jsx(
        "button",
        {
          type: "submit",
          disabled: saving || uploading,
          className: "px-6 py-2.5 rounded-full bg-primary text-primary-foreground text-sm font-semibold glow-purple-sm disabled:opacity-60",
          children: saving ? "Menyimpan..." : uploading ? "Upload..." : isEdit ? "Simpan Perubahan" : "Buat Produk"
        }
      )
    ] })
  ] });
}
function Field({ label, children }) {
  return /* @__PURE__ */ jsxs("label", { className: "block", children: [
    label && /* @__PURE__ */ jsx("span", { className: "text-xs uppercase tracking-wider text-muted-foreground block mb-1", children: label }),
    children
  ] });
}
export {
  ProductForm as P
};
