import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { ArrowRight, ChevronsDownUp, ChevronsUpDown, Search } from "lucide-react";
import { useCategoryTaxonomy } from "../../hooks/useCategoryTaxonomy";
import CategoryTaxonomyTree, {
  TAXONOMY_COLLAPSE_ACCESSORS,
} from "../categories/CategoryTaxonomyTree";
import type { TaxonomyNode } from "../../services/categoryTaxonomyService";
import { useCollapsibleGroups } from "../../hooks/useCollapsibleGroups";

interface StepDiscoverProps {
  onNext: () => void;
}

// Flattens the taxonomy so the hook's bulk ops (expand/collapse all, allExpanded)
// can walk every parent at any depth.
function flattenNodes(nodes: TaxonomyNode[]): TaxonomyNode[] {
  const flat: TaxonomyNode[] = [];
  const walk = (n: TaxonomyNode) => {
    flat.push(n);
    n.children.forEach(walk);
  };
  nodes.forEach(walk);
  return flat;
}

function countNodes(nodes: TaxonomyNode[]): {
  roots: number;
  subcategories: number;
  leaves: number;
} {
  let roots = 0;
  let subcategories = 0;
  let leaves = 0;
  for (const root of nodes) {
    roots += 1;
    for (const child of root.children) {
      if (child.children.length === 0) leaves += 1;
      else {
        subcategories += 1;
        for (const leaf of child.children) {
          if (leaf.children.length === 0) leaves += 1;
          else subcategories += 1;
        }
      }
    }
  }
  return { roots, subcategories, leaves };
}

/**
 * Step 1 — Discover: read-only navigation of the v1 taxonomy. Reuses the same
 * CategoryTaxonomyTree component as the standalone guide page (#117) so the
 * two surfaces stay visually consistent.
 */
export default function StepDiscover({ onNext }: StepDiscoverProps) {
  const { t } = useTranslation();
  const { taxonomy } = useCategoryTaxonomy();
  const [search, setSearch] = useState("");

  // State machine only (issue #290): in-memory (storageKey null), collapsed by
  // default — same as the standalone guide page it shares CategoryTaxonomyTree with.
  const groups = useCollapsibleGroups<TaxonomyNode>(null, TAXONOMY_COLLAPSE_ACCESSORS, {
    defaultExpanded: false,
  });

  const counts = countNodes(taxonomy.roots);
  const total = counts.roots + counts.subcategories + counts.leaves;

  const flatNodes = useMemo(() => flattenNodes(taxonomy.roots), [taxonomy.roots]);

  const handleExpandAll = () => groups.expandAll(flatNodes);
  const handleCollapseAll = () => groups.collapseAll(flatNodes);
  // Correct "all expanded" test (issue #290): every group must be open, fixing the
  // old expanded.size > 0 bug that flipped the button after a single expand.
  const allExpanded = groups.allExpanded(flatNodes);

  return (
    <section className="space-y-6">
      <header className="space-y-1">
        <h2 className="text-xl font-semibold">
          {t("categoriesSeed.migration.discover.title")}
        </h2>
        <p className="text-sm text-[var(--muted-foreground)]">
          {t("categoriesSeed.migration.discover.subtitle")}
        </p>
      </header>

      <div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-5 space-y-2">
        <h3 className="font-semibold">
          {t("categoriesSeed.migration.discover.intro.title")}
        </h3>
        <p className="text-sm text-[var(--muted-foreground)]">
          {t("categoriesSeed.migration.discover.intro.body")}
        </p>
      </div>

      <div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-5 space-y-4">
        <p
          className="text-sm text-[var(--muted-foreground)]"
          aria-live="polite"
        >
          {t("categoriesSeed.guidePage.counter", {
            roots: counts.roots,
            subcategories: counts.subcategories,
            leaves: counts.leaves,
            total,
          })}
        </p>

        <div className="flex flex-col sm:flex-row gap-3">
          <div className="relative flex-1">
            <Search
              size={16}
              className="absolute left-3 top-1/2 -translate-y-1/2 text-[var(--muted-foreground)] pointer-events-none"
              aria-hidden="true"
            />
            <input
              type="search"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder={t("categoriesSeed.guidePage.searchPlaceholder")}
              aria-label={t("categoriesSeed.guidePage.searchPlaceholder")}
              className="w-full pl-9 pr-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--background)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--primary)]/30"
            />
          </div>
          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={allExpanded ? handleCollapseAll : handleExpandAll}
              className="inline-flex items-center gap-2 px-3 py-2 text-sm rounded-lg border border-[var(--border)] hover:bg-[var(--muted)] transition-colors"
            >
              {allExpanded ? (
                <>
                  <ChevronsDownUp size={16} />
                  {t("categoriesSeed.guidePage.collapseAll")}
                </>
              ) : (
                <>
                  <ChevronsUpDown size={16} />
                  {t("categoriesSeed.guidePage.expandAll")}
                </>
              )}
            </button>
          </div>
        </div>
      </div>

      <div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-3">
        <CategoryTaxonomyTree
          nodes={taxonomy.roots}
          isCollapsed={groups.isCollapsed}
          onToggle={groups.toggle}
          searchQuery={search}
        />
      </div>

      <div className="flex justify-end">
        <button
          type="button"
          onClick={onNext}
          className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-[var(--primary)] text-white hover:opacity-90 transition-opacity"
        >
          {t("categoriesSeed.migration.discover.next")}
          <ArrowRight size={16} />
        </button>
      </div>
    </section>
  );
}
