"use client";

import { useState } from "react";
import { ChevronDown, ChevronRight } from "lucide-react";

// Generic accordion tree filter
export default function AccordionTreeFilter({
  data = [],
  selected = [],
  onChange,
  labelKey = "name",
  valueKey = "id",
  childrenKey = "children",
  countKey = "count", // 👈 supports counts like products inside category
}) {
  const [expanded, setExpanded] = useState({});

  const toggleExpand = (id) => {
    setExpanded((prev) => ({ ...prev, [id]: !prev[id] }));
  };

  const isChecked = (id) => selected.includes(id);

  const toggleItem = (id) => {
    const newSelected = isChecked(id)
      ? selected.filter((val) => val !== id)
      : [...selected, id];
    onChange(newSelected);
  };

  const renderTree = (nodes) =>
    nodes.map((node) => {
      const id = node[valueKey];
      const label = node[labelKey];
      const children = node[childrenKey] || [];
      const count = node[countKey] ?? 0;

      return (
        <li key={id} className="text-sm text-gray-800">
          <div className="flex items-center gap-2 mb-1 hover:bg-gray-50 rounded px-1 py-[2px]">
            {children.length > 0 ? (
              <button
                type="button"
                onClick={() => toggleExpand(id)}
                className="text-gray-500 hover:text-black transition"
              >
                {expanded[id] ? (
                  <ChevronDown size={16} />
                ) : (
                  <ChevronRight size={16} />
                )}
              </button>
            ) : (
              <span className="w-[16px]" />
            )}

            <label className="flex items-center gap-2 cursor-pointer w-full">
              {/* <input
                type="checkbox"
                checked={isChecked(id)}
                onChange={() => toggleItem(id)}
                className="accent-brand-gold"
              /> */}
              <input
                type="checkbox"
                checked={isChecked(id)}
                onChange={() => toggleItem(id)}
                className="w-4 h-4 rounded border border-gray-300 bg-white checked:bg-brand-dark checked:text-white text-white appearance-none 
                flex items-center justify-center relative before:content-[''] before:absolute before:inset-0 before:flex before:items-center 
                before:justify-center checked:before:content-['✔'] checked:before:text-brand-gold checked:before:text-xs"
              />

              <span className="flex-1 font-medium hover:text-brand-dark">
                {label}
              </span>
              <span className="text-gray-400 text-xs">({count})</span>
            </label>
          </div>

          {expanded[id] && children.length > 0 && (
            <ul className="ml-3 border-l border-gray-200  space-y-1">
              {renderTree(children)}
            </ul>
          )}
        </li>
      );
    });

  return <ul className="space-y-1">{renderTree(data)}</ul>;
}
