import React, { useMemo } from "react";
import ModalShell from "./ModalShell";

function hexToRgba(hex, alpha = 0.2) {
  try {
    let h = (hex || "").replace("#", "").trim();
    if (h.length === 3) h = h.split("").map((c) => c + c).join("");
    if (h.length !== 6) return `rgba(67,190,255,${alpha})`;
    const r = parseInt(h.slice(0, 2), 16);
    const g = parseInt(h.slice(2, 4), 16);
    const b = parseInt(h.slice(4, 6), 16);
    return `rgba(${r},${g},${b},${alpha})`;
  } catch {
    return `rgba(67,190,255,${alpha})`;
  }
}

export default function ColorPickerModal({
  open,
  onClose,
  title = "تغییر رنگ",
  itemName = "",
  colorsCfg,
  colorOptions = [],
  colorsLoading = false,
  onPick, // (colorIdOrNull) => Promise|void
}) {
  const allowReset = !!colorsCfg?.allow_custom_color || true; // اگر cfg نداری هم ریست رو نشون بده

  const sorted = useMemo(() => {
    const arr = Array.isArray(colorOptions) ? [...colorOptions] : [];
    // اگر بک‌اند sort_order داشت بهتره همون ترتیب رو نگه داریم
    return arr;
  }, [colorOptions]);

  return (
    <ModalShell open={!!open} title={title} onClose={onClose}>
      <div className="space-y-4">
        <div className="rounded-xl border border-black/10 dark:border-white/10 bg-white/60 dark:bg-white/5 p-3">
          <div className="text-xs text-black/60 dark:text-white/70">آیتم</div>
          <div className="font-extrabold text-sm sm:text-base truncate">{itemName || "—"}</div>
        </div>

        {colorsLoading ? (
          <div className="rounded-xl border border-black/10 dark:border-white/10 bg-white/60 dark:bg-white/5 p-4 text-sm text-black/60 dark:text-white/70">
            در حال دریافت رنگ‌ها...
          </div>
        ) : (
          <div className="space-y-3">
            {allowReset && (
              <button
                type="button"
                onClick={() => onPick?.(null)}
                className="w-full rounded-xl px-4 py-2 text-sm font-extrabold border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10"
              >
                بازگشت به رنگ پیش‌فرض
              </button>
            )}

            {sorted.length === 0 ? (
              <div className="rounded-xl border border-black/10 dark:border-white/10 bg-white/60 dark:bg-white/5 p-4 text-sm text-black/60 dark:text-white/70">
                رنگی برای نمایش وجود ندارد.
              </div>
            ) : (
              <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                {sorted.map((c) => {
                  const hex = c.hex || c.color || c.value || "#43BEFF";
                  const label = c.title || c.label || c.key || "Color";
                  const id = c.id ?? c.color_id ?? c.key;

                  return (
                    <button
                      key={String(id)}
                      type="button"
                      onClick={() => onPick?.(id)}
                      className="rounded-xl border border-black/10 dark:border-white/10 bg-white/60 dark:bg-white/5 p-3 text-left hover:bg-black/5 dark:hover:bg-white/10 transition"
                    >
                      <div className="flex items-center gap-2">
                        <span
                          className="h-6 w-6 rounded-lg border border-black/10 dark:border-white/10"
                          style={{
                            background: `linear-gradient(180deg, ${hex}, ${hexToRgba(hex, 0.35)})`,
                          }}
                        />
                        <div className="min-w-0">
                          <div className="text-sm font-extrabold truncate">{label}</div>
                          <div className="text-[11px] text-black/50 dark:text-white/50 truncate">{hex}</div>
                        </div>
                      </div>
                    </button>
                  );
                })}
              </div>
            )}
          </div>
        )}

        <div className="flex gap-2">
          <button
            type="button"
            onClick={onClose}
            className="flex-1 rounded-xl px-4 py-2 text-sm font-bold border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10"
          >
            بستن
          </button>
        </div>
      </div>
    </ModalShell>
  );
}
