import React, {
  useState,
  useEffect,
  forwardRef,
  useImperativeHandle,
} from 'react';
import { CheckCircle, Circle, ChevronDown, ChevronRight } from 'lucide-react';
import { useEstablishment } from '@/context/EstablishmentContext';

const TreeView = forwardRef(function TreeView(
  { data, expandAll, onSelectionChange },
  ref
) {
  const [openDomains, setOpenDomains] = useState({});
  const [openCategories, setOpenCategories] = useState({});
  const [selectedCompetencies, setSelectedCompetencies] = useState({}); // { [competence_id]: true }

  // N'ouvre ou ne ferme tout que si expandAll change explicitement
  useEffect(() => {
    if (!data) return;
    const allDomains = {};
    const allCategories = {};
    if (expandAll) {
      data.forEach((domaine) => {
        allDomains[domaine.domaine_id] = true;
        domaine.categories.forEach((cat) => {
          allCategories[cat.categorie_id] = true;
        });
      });
      setOpenDomains(allDomains);
      setOpenCategories(allCategories);
    } else {
      // On ne ferme tout que si l'utilisateur décoche explicitement "Tout dérouler"
      setOpenDomains({});
      setOpenCategories({});
    }
  }, [expandAll]); // <-- uniquement expandAll

  // Appelle le callback à chaque changement de sélection
  useEffect(() => {
    if (onSelectionChange) {
      const selected = Object.entries(selectedCompetencies)
        .filter(([_, selected]) => selected)
        .map(([id]) => id);
      onSelectionChange(selected);
    }
  }, [selectedCompetencies, onSelectionChange]);

  const toggleDomain = (id) =>
    setOpenDomains((prev) => ({ ...prev, [id]: !prev[id] }));
  const toggleCategory = (id) =>
    setOpenCategories((prev) => ({ ...prev, [id]: !prev[id] }));

  const handleCompetenceClick = (competence) => {
    if (competence.state === 'required') return;
    setSelectedCompetencies((prev) => {
      const next = {
        ...prev,
        [competence.competence_id]: !prev[competence.competence_id],
      };
      return next;
    });
  };

  // Pour exposer la sélection au parent
  useImperativeHandle(ref, () => ({
    getSelectedCompetencies: () => {
      const selected = Object.entries(selectedCompetencies)
        .filter(([_, selected]) => selected)
        .map(([id]) => id);
      return selected;
    },
    clearSelection: () => setSelectedCompetencies({}),
  }));

  const { profileRole } = useEstablishment();

  return (
    <div>
      {data.map((domaine) => (
        <div key={domaine.domaine_id} className="mb-4">
          <button
            className="w-full text-left px-3 py-2 bg-primary/10 hover:bg-primary/20 rounded font-semibold text-secondary flex items-center gap-2"
            onClick={() => toggleDomain(domaine.domaine_id)}
          >
            {openDomains[domaine.domaine_id]
              ? <ChevronDown className="w-4 h-4 flex-shrink-0" />
              : <ChevronRight className="w-4 h-4 flex-shrink-0" />
            }
            {domaine.domaine_nom}
          </button>
          {openDomains[domaine.domaine_id] && (
            <div className="ml-4">
              {domaine.categories.map((categorie) => (
                <div key={categorie.categorie_id} className="mb-2">
                  <button
                    className="w-full text-left px-2 py-1 bg-primary/5 hover:bg-primary/10 rounded text-secondary flex items-center gap-2"
                    onClick={() => toggleCategory(categorie.categorie_id)}
                  >
                    {openCategories[categorie.categorie_id]
                      ? <ChevronDown className="w-4 h-4 flex-shrink-0" />
                      : <ChevronRight className="w-4 h-4 flex-shrink-0" />
                    }
                    {categorie.categorie_nom}
                  </button>
                  {openCategories[categorie.categorie_id] && (
                    <ul className="ml-4">
                      {categorie.competences.map((competence) => {
                        const isSelected =
                          selectedCompetencies[competence.competence_id];
                        return (
                          <li
                            key={competence.competence_id}
                            className={`py-1 flex items-center gap-2 ${
                              competence.state === 'required'
                                ? 'text-secondary font-bold'
                                : competence.state === 'custom'
                                  ? isSelected
                                    ? 'text-gray-500 cursor-pointer hover:text-primary'
                                    : 'text-primary font-semibold cursor-pointer'
                                  : isSelected
                                    ? 'text-primary font-semibold cursor-pointer'
                                    : 'text-gray-500 cursor-pointer hover:text-primary'
                            }`}
                            onClick={
                              profileRole !== 0
                                ? () => handleCompetenceClick(competence)
                                : undefined
                            }
                            style={{
                              cursor:
                                competence.state === 'required'
                                  ? 'default'
                                  : profileRole !== 0
                                    ? 'pointer'
                                    : 'default',
                              userSelect: 'none',
                            }}
                          >
                            {competence.state === 'required' && (
                              <CheckCircle className="w-4 h-4 text-primary" />
                            )}
                            {competence.nom}
                          </li>
                        );
                      })}
                    </ul>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      ))}
    </div>
  );
});

export default TreeView;
