import React, { useState, useCallback } from "react";
import "./RadialMenu.css";

const CATEGORIES = [
  { id: "News", icon: "fa-solid fa-newspaper", color: "#3b82f6", label: "News" },
  { id: "Friends", icon: "fa-solid fa-users", color: "#10b981", label: "Social" },
  { id: "Events", icon: "fa-solid fa-calendar", color: "#f59e0b", label: "Events" },
  { id: "Market", icon: "fa-solid fa-store", color: "#8b5cf6", label: "Market" },
];

const SUBCATEGORIES = {
  News: [
    { id: "World", icon: "fa-solid fa-globe", label: "World" },
    { id: "Politics", icon: "fa-solid fa-landmark", label: "Politics" },
    { id: "Tech", icon: "fa-solid fa-microchip", label: "Tech" },
    { id: "Finance", icon: "fa-solid fa-chart-line", label: "Finance" },
    { id: "Local", icon: "fa-solid fa-location-dot", label: "Local" },
  ],
  Friends: [
    { id: "Nearby", icon: "fa-solid fa-location-crosshairs", label: "Near" },
    { id: "Chats", icon: "fa-solid fa-comments", label: "Chats" },
    { id: "Groups", icon: "fa-solid fa-user-group", label: "Groups" },
  ],
  Events: [
    { id: "Today", icon: "fa-solid fa-calendar-day", label: "Today" },
    { id: "Music", icon: "fa-solid fa-music", label: "Music" },
    { id: "Sports", icon: "fa-solid fa-football", label: "Sports" },
  ],
  Market: [
    { id: "Deals", icon: "fa-solid fa-tags", label: "Deals" },
    { id: "Tech", icon: "fa-solid fa-laptop", label: "Tech" },
    { id: "Auto", icon: "fa-solid fa-car", label: "Auto" },
  ],
};

const TIME_OPTIONS = [
  { label: "now", hours: 3 },
  { label: "6h", hours: 6 },
  { label: "24h", hours: 24 },
  { label: "7d", hours: 168 },
  { label: "2w", hours: 336 },
];

export default function RadialMenu({
  onCategoryToggle,
  onSubcategoryToggle,
  onTime,
  onWeather,
  onClearAllFilters,
  activeCategories = [],
  activeSubcategories = [],
  activeTime,
  weatherEnabled,
}) {
  const [leftOpen, setLeftOpen] = useState(false);
  const [rightOpen, setRightOpen] = useState(false);

  // Get colors for split FAB
  const activeColors = CATEGORIES
    .filter(c => activeCategories.includes(c.id))
    .map(c => c.color);

  const hasActiveFilters = activeCategories.length > 0 || activeSubcategories.length > 0;

  const handleLeftToggle = () => {
    setLeftOpen(!leftOpen);
    if (!leftOpen) setRightOpen(false);
  };

  const handleRightToggle = () => {
    setRightOpen(!rightOpen);
    if (!rightOpen) setLeftOpen(false);
  };

  const handleCategoryClick = (catId) => {
    onCategoryToggle?.(catId);
  };

  const handleSubcatClick = (catId, subId) => {
    onSubcategoryToggle?.(catId, subId);
  };

  const handleTimeClick = (hours) => {
    onTime?.(hours);
    setRightOpen(false); // Close menu after selection
  };

  const handleWeatherClick = () => {
    onWeather?.();
  };

  const handleClearAll = () => {
    // Clear all category filters
    for (const cat of activeCategories) {
      onCategoryToggle?.(cat);
    }
    setLeftOpen(false);
    onClearAllFilters?.();
  };

  // Build gradient for multi-select FAB
  const fabGradient = activeColors.length === 0
    ? "linear-gradient(135deg, #6366f1 0%, #4f46e5 100%)"
    : activeColors.length === 1
    ? `linear-gradient(135deg, ${activeColors[0]} 0%, ${activeColors[0]}dd 100%)`
    : `conic-gradient(${activeColors.map((c, i) => `${c} ${i * (360 / activeColors.length)}deg ${(i + 1) * (360 / activeColors.length)}deg`).join(", ")})`;

  return (
    <>
      {/* Backdrop */}
      {(leftOpen || rightOpen) && (
        <div
          className="fab-backdrop"
          style={{ zIndex: 8999 }}
          onClick={() => { setLeftOpen(false); setRightOpen(false); }}
        />
      )}

      {/* LEFT FAB - Categories */}
      <div className={`fab-left ${leftOpen ? "is-open" : ""}`} style={leftOpen ? { zIndex: 9000 } : undefined}>
        {/* Categories ring - expand DOWN-RIGHT */}
        <div className="fab-ring">
          {CATEGORIES.map((cat, i) => {
            // Find index of first active category to rotate
            const firstActiveIdx = CATEGORIES.findIndex(c => activeCategories.includes(c.id));
            // Rotate so active category is at middle-right (angle 0 = straight right)
            const rotateOffset = firstActiveIdx >= 0 ? -firstActiveIdx * 50 : 0;
            const angle = -25 + (i * 50) + rotateOffset;
            const rad = (angle * Math.PI) / 180;
            const r = 68;
            const x = Math.cos(rad) * r;
            const y = Math.sin(rad) * r;
            const isActive = activeCategories.includes(cat.id);

            // Subcategories for this category
            const subcats = SUBCATEGORIES[cat.id] || [];
            const subRadius = 65;
            // Spread subcats more - center them around the category angle
            const subSpacing = 45;
            const subStartAngle = angle - ((subcats.length - 1) * subSpacing) / 2;

            return (
              <React.Fragment key={cat.id}>
                {/* Category button */}
                <button
                  className={`fab-item fab-cat ${leftOpen ? "is-visible" : ""} ${isActive ? "is-active" : ""}`}
                  style={{ "--x": `${x}px`, "--y": `${y}px`, "--delay": `${i * 40}ms`, "--color": cat.color }}
                  onClick={() => handleCategoryClick(cat.id)}
                  title={cat.id}
                >
                  <i className={cat.icon} />
                  <span className="fab-item-label">{cat.label}</span>
                </button>

                {/* Subcategories - appear around the category when active */}
                {/* Logic: empty = all selected, clicking toggles exclusion */}
                {isActive && leftOpen && subcats.map((sub, si) => {
                  const subAngle = subStartAngle + (si * subSpacing);
                  const subRad = (subAngle * Math.PI) / 180;
                  const subX = x + Math.cos(subRad) * subRadius;
                  const subY = y + Math.sin(subRad) * subRadius;
                  // Inverted logic: active if NOT in excluded list, or if list is empty
                  const catSubs = activeSubcategories.filter(s => s.startsWith(cat.id + ":"));
                  const isSubActive = catSubs.length === 0 || activeSubcategories.includes(`${cat.id}:${sub.id}`);

                  return (
                    <button
                      key={`${cat.id}-${sub.id}`}
                      className={`fab-item fab-sub ${isSubActive ? "is-active" : "is-excluded"}`}
                      style={{
                        "--x": `${subX}px`,
                        "--y": `${subY}px`,
                        "--delay": `${i * 40 + si * 25 + 80}ms`,
                        "--color": cat.color
                      }}
                      onClick={() => handleSubcatClick(cat.id, sub.id)}
                      title={sub.id}
                    >
                      <i className={sub.icon} />
                      <span className="fab-item-label fab-sub-label">{sub.label}</span>
                    </button>
                  );
                })}
              </React.Fragment>
            );
          })}
        </div>

        {/* Main FAB - split colors */}
        <button
          className="fab-btn fab-btn-split"
          onClick={leftOpen && hasActiveFilters ? handleClearAll : handleLeftToggle}
          style={{ background: fabGradient }}
          title={leftOpen && hasActiveFilters ? "Clear all filters" : "Categories"}
        >
          {leftOpen ? (
            <i className="fa-solid fa-xmark" />
          ) : activeCategories.length === 0 ? (
            <i className="fa-solid fa-layer-group" />
          ) : activeCategories.length === 1 ? (
            <i className={CATEGORIES.find(c => c.id === activeCategories[0])?.icon || "fa-solid fa-layer-group"} />
          ) : (
            <span className="fab-count">{activeCategories.length}</span>
          )}
        </button>
        <span className="fab-label fab-label-cat">{leftOpen ? "Clear" : activeCategories.length > 0 ? activeCategories.join(", ") : "Filter"}</span>
      </div>

      {/* RIGHT FAB - Time & Weather */}
      <div className={`fab-right ${rightOpen ? "is-open" : ""}`} style={rightOpen ? { zIndex: 9000 } : undefined}>
        <div className="fab-ring">
          {/* Time options */}
          {TIME_OPTIONS.map((t, i) => {
            const angle = 110 + (i * 35);
            const rad = (angle * Math.PI) / 180;
            const r = 60;
            const x = Math.cos(rad) * r;
            const y = Math.sin(rad) * r;
            return (
              <button
                key={t.hours}
                className={`fab-item fab-time ${rightOpen ? "is-visible" : ""} ${activeTime === t.hours ? "is-active" : ""}`}
                style={{ "--x": `${x}px`, "--y": `${y}px`, "--delay": `${i * 35}ms` }}
                onClick={() => handleTimeClick(t.hours)}
              >
                {t.label}
              </button>
            );
          })}

          {/* Weather toggle */}
          <button
            className={`fab-item fab-action ${rightOpen ? "is-visible" : ""} ${weatherEnabled ? "is-active" : ""}`}
            style={{
              "--x": `${Math.cos((285 * Math.PI) / 180) * 60}px`,
              "--y": `${Math.sin((285 * Math.PI) / 180) * 60}px`,
              "--delay": "200ms",
              "--color": "#06b6d4"
            }}
            onClick={handleWeatherClick}
            title="Weather"
          >
            <i className="fa-solid fa-cloud-sun" />
          </button>
        </div>

        {/* Main FAB */}
        <button className="fab-btn fab-btn-right" onClick={handleRightToggle}>
          <i className={rightOpen ? "fa-solid fa-xmark" : "fa-solid fa-clock"} />
        </button>
        <span className="fab-label">{TIME_OPTIONS.find(t => t.hours === activeTime)?.label || "2w"}</span>
      </div>
    </>
  );
}
