import { useState, useCallback } from "react";
import type { DungeonData, Role } from "@/types/dungeon";
import { useWowheadTooltips } from "@/hooks/useWowheadTooltips";
import { DungeonHeader } from "./DungeonHeader";
import { RoleFilterBar } from "./RoleFilterBar";
import { BossSection } from "./BossSection";
import { TrashSection } from "./TrashSection";
import { SectionDivider } from "./SectionDivider";

const ALL_ROLES = new Set<Role>(["tank", "healer", "dps", "everyone"]);

function toSlug(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/(^-|-$)/g, "");
}

interface DungeonPageProps {
  dungeon: DungeonData;
}

export function DungeonPage({ dungeon }: DungeonPageProps) {
  useWowheadTooltips([dungeon.id]);
  const [activeRoles, setActiveRoles] = useState<Set<Role>>(ALL_ROLES);

  const handleToggleRole = useCallback((role: Role) => {
    setActiveRoles((prev) => {
      const next = new Set(prev);
      if (next.has(role)) {
        next.delete(role);
      } else {
        next.add(role);
      }
      return next;
    });
  }, []);

  return (
    <div>
      <DungeonHeader dungeon={dungeon} />
      <RoleFilterBar activeRoles={activeRoles} onToggleRole={handleToggleRole} />
      {dungeon.sections.map((section, i) => {
        switch (section.type) {
          case "trash": {
            const sectionId = `trash-${toSlug(section.data.header)}`;
            return <TrashSection key={i} data={section.data} sectionId={sectionId} />;
          }
          case "boss": {
            const sectionId = `boss-${toSlug(section.data.name)}`;
            return <BossSection key={i} data={section.data} activeRoles={activeRoles} sectionId={sectionId} />;
          }
          case "divider":
            return <SectionDivider key={i} />;
        }
      })}
    </div>
  );
}
