// src/components/storage/ColorPickerInline.jsx
import React, { useMemo, useState } from "react";
import { IoColorPaletteOutline } from "react-icons/io5";
import { TbCheck } from "react-icons/tb";
import MenuBtn from "./MenuBtn";
import { getEffectiveHex, hexToRgba, normalizeHex } from "../../utils/storage";

export default function ColorPickerInline({
  title = "تغییر رنگ",
  item,
  colors = [],
  config,
  kind = "file", // 'file' | 'folder'
  loading = false,
  onPick, // async (colorIdOrNull) => void
}) {
  const [open, setOpen] = useState(false);
  const [saving, setSaving] = useState(false);

  const effectiveHex = getEffectiveHex(item);
  const currentColorId = item?.color_id ? String(item.color_id) : null;

  const defaultId =
    kind === "folder"
      ? config?.default_folder_color?.id
      : config?.default_file_color?.id;

  const currentLabel = useMemo(() => {
    const byId =
      currentColorId && colors.find((c) => String(c.id) === String(currentColorId));
    if (byId) return byId.title || byId.key;

    const byHex = colors.find(
      (c) => normalizeHex(c.hex) === normalizeHex(effectiveHex)
    );
    if (byHex) return byHex.title || byHex.key;

    return "رنگ فعلی";
  }, [colors, currentColorId, effectiveHex]);

  const doPick = async (colorIdOrNull) => {
    try {
      setSaving(true);
      await onPick?.(colorIdOrNull);
      setOpen(false);
    } finally {
      setSaving(false);
    }
  };

  const Swatch = ({ hex, active }) => (
    <span
      className={`inline-flex items-center justify-center w-6 h-6 rounded-lg border ${
        active ? "border-black/40 dark:border-white/50" : "border-black/10 dark:border-white/15"
      }`}
      style={{
        background: hexToRgba(hex, 0.22),
        boxShadow: active ? `0 0 0 2px ${hexToRgba(hex, 0.2)}` : "none",
      }}
      title={hex}
    >
      <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: normalizeHex(hex) }} />
    </span>
  );

  return (
    <div className="w-full">
      <MenuBtn onAction={() => setOpen((p) => !p)}>
        <IoColorPaletteOutline className="text-[#43BEFF]" />
        <span className="flex-1">{title}</span>

        <span className="inline-flex items-center gap-2 text-xs font-bold">
          <Swatch hex={effectiveHex} active />
          <span className="opacity-80">{currentLabel}</span>
        </span>
      </MenuBtn>

      {open && (
        <div className="mt-2 rounded-xl border border-black/10 dark:border-white/10 bg-white/70 dark:bg-white/5 p-2 space-y-1">
          {loading ? (
            <div className="px-2 py-2 text-xs text-black/60 dark:text-white/70">
              در حال دریافت رنگ‌ها...
            </div>
          ) : (
            <>
              <button
                type="button"
                className="w-full flex items-center gap-2 rounded-lg px-2 py-2 hover:bg-black/5 dark:hover:bg-white/10 text-sm font-semibold"
                disabled={saving}
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  doPick(null);
                }}
              >
                <Swatch
                  hex={normalizeHex(colors.find((c) => String(c.id) === String(defaultId))?.hex || effectiveHex)}
                  active={currentColorId === null}
                />
                <div className="flex-1 text-right">
                  <div className="text-black dark:text-white">بازنشانی (پیش‌فرض)</div>
                  <div className="text-[11px] text-black/50 dark:text-white/60">color_id = null</div>
                </div>
                {currentColorId === null && <TbCheck className="opacity-70" />}
              </button>

              <div className="h-px bg-black/5 dark:bg-white/10 my-1" />

              {colors.map((c) => {
                const isActive =
                  (currentColorId && String(c.id) === String(currentColorId)) ||
                  (!currentColorId && normalizeHex(c.hex) === normalizeHex(effectiveHex));

                return (
                  <button
                    key={String(c.id)}
                    type="button"
                    className="w-full flex items-center gap-2 rounded-lg px-2 py-2 hover:bg-black/5 dark:hover:bg-white/10 text-sm font-semibold"
                    disabled={saving}
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      doPick(String(c.id));
                    }}
                  >
                    <Swatch hex={c.hex} active={isActive} />
                    <div className="flex-1 text-right">
                      <div className="text-black dark:text-white">{c.title || c.key}</div>
                      <div className="text-[11px] text-black/50 dark:text-white/60">{normalizeHex(c.hex)}</div>
                    </div>
                    {isActive && <TbCheck className="opacity-70" />}
                  </button>
                );
              })}
            </>
          )}
        </div>
      )}
    </div>
  );
}
