import React, { useState, useRef, useEffect } from "react";
import { useTopics } from "../contexts/TopicsContext";
import { Link } from "react-router-dom";
import { capitalizeCzech } from "../utils/cz_uk";

const Picker = () => {
  const [menuOpen, setMenuOpen] = useState(false);
  const [activeTopic, setActiveTopic] = useState<string | null>(null);
  const [selectedSubtopic, setSelectedSubtopic] = useState<string | null>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const { topics, isLoading, isError } = useTopics();

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && event.target instanceof Node && !menuRef.current.contains(event.target)) {
        setMenuOpen(false);
        setActiveTopic(null);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);


  if (isLoading) return <p>Loading topics...</p>;
  if (isError || !topics) return <p>Failed to load topics.</p>;

  return (
    <div className="relative inline-block">
      <a
        href="#"
        onClick={(e) => {
          e.preventDefault();
          setMenuOpen(!menuOpen);
        }}
        className="text-white hover:underline cursor-pointer"
      >
        Témata
      </a>

      {menuOpen && (
        <div ref={menuRef} className="absolute text-green-950 mt-2 flex bg-yellow-50 border rounded shadow-lg z-10">
          {/* Left: Topics */}
          <div className="w-54">
            {topics.map((topic) => (
              <button
                key={topic.name}
                onMouseEnter={() => setActiveTopic(topic.name)}
                className={`block w-full text-left px-4 py-2 text-sm ${
                  activeTopic === topic.name
                    ? "bg-gray-100 text-green-950 font-semibold rounded"
                    : "hover:bg-gray-50 rounded"
                }`}
              >
                {capitalizeCzech(topic.name)}
              </button>
            ))}
          </div>

          {/* Right: Subtopics */}
          {activeTopic && (
            <div className="w-48 border-l">
              {topics
                .find((t) => t.name === activeTopic)
                ?.subtopics.map((subtopic) => (
                  <button
                    key={subtopic.id.toString()}
                    onClick={() => {
                      setSelectedSubtopic(subtopic.subtopic);
                      setMenuOpen(false);
                    }}
                    className="block w-full text-left px-4 py-2 text-sm hover:bg-gray-50 rounded"
                  >
                    <Link 
                      to={`/articles`} 
                      className="text-green-950" 
                      data-subtopic={subtopic.subtopic}
                      state={{topicFilter: subtopic.subtopic}}
                    >
                      {capitalizeCzech(subtopic.subtopic)}
                    </Link>
                  </button>
                ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default Picker;
