// src/components/filters/CustomDateRangeItem.jsx
import React, { useMemo, useState } from "react";
import { Calendar } from "react-multi-date-picker";
import persian from "react-date-object/calendars/persian";
import persian_fa from "react-date-object/locales/persian_fa";

export default function CustomDateRangeItem({ item, isActive, onApply }) {
  const [show, setShow] = useState(false);
  const [range, setRange] = useState([null, null]); // [from, to]

  const hasRange = !!range?.[0] && !!range?.[1];

  const faLabel = useMemo(() => {
    if (!hasRange) return "";
    try {
      return `${range[0].format("YYYY/MM/DD")} تا ${range[1].format("YYYY/MM/DD")}`;
    } catch {
      return "";
    }
  }, [hasRange, range]);

  return (
    <div className="space-y-2">
      {/* آیتم */}
      <button
        type="button"
        onClick={() => setShow((p) => !p)}
        className={`dark:text-white text-right w-full text-sm px-1 py-2 flex gap-2 items-center rounded-md
          ${show || isActive ? "dark:bg-[#A1E3F919] bg-[#A1E3F980]" : "dark:hover:bg-[#A1E3F919] hover:bg-[#A1E3F980]"}
        `}
      >
        {item.icon}
        <div className="flex flex-col items-start">
          <span>{item.label}</span>
          {faLabel && <span className="text-[11px] opacity-70">{faLabel}</span>}
        </div>
      </button>

      {/* ✅ نه پاپ‌آپ، نه دراپ‌داون: مستقیم زیر input */}
      {show && (
        <div className="mt-1 space-y-2">
          {/* Input نمایشی (صرفاً برای نمایش بازه انتخاب شده) */}
          <input
            type="text"
            readOnly
            value={faLabel || ""}
            placeholder="انتخاب بازه تاریخ (جلالی)"
            className="w-full dark:bg-[#A1E3F919] bg-[#A1E3F980] rounded-md px-3 py-2 text-xs dark:text-white text-right focus:outline-none"
          />

          {/* Calendar ثابت زیر input */}
          <div className="w-full rounded-xl border border-black/5 dark:border-white/10 -mr-1 dark:bg-[#001F3F] bg-[#f2f2f2]">
            <Calendar
              value={range}
              onChange={(val) => {
                const next = Array.isArray(val) ? val : [val, null];
                setRange(next);

                // ✅ وقتی بازه کامل شد، اعمال کن و جمعش کن
                if (next?.[0] && next?.[1]) {
                  const from = next[0].convert("gregorian").format("YYYY-MM-DD");
                  const to = next[1].convert("gregorian").format("YYYY-MM-DD");
                  onApply?.({ from, to });

                  // اگر می‌خوای بعد انتخاب جمع بشه:
                  setShow(false);
                }
              }}
              range
              calendar={persian}
              locale={persian_fa}
              className="rmdp-mobile"
            />
          </div>
        </div>
      )}
    </div>
  );
}
