import React, { useMemo, useState } from "react"
import { X, ChevronRight } from "lucide-react"
import { useNavigate } from "react-router-dom"  // useNavigate'i ekliyoruz
import type { CategoryNode } from "../../data/categories"

type Props = {
  isOpen: boolean
  categories: CategoryNode[]
  activeSlug?: string | null
  onClose: () => void
  onSelect: (slug: string) => void
}

function TreeNode({
  node,
  level,
  activeSlug,
  expanded,
  onToggle,
  onSelect,
}: {
  node: CategoryNode
  level: number
  activeSlug?: string | null
  expanded: boolean
  onToggle: () => void
  onSelect: (slug: string) => void
}) {
  const hasChildren = (node.children?.length ?? 0) > 0
  const isActive = activeSlug === node.slug

  return (
    <div>
      <div
        className={[
          "flex items-center justify-between gap-2 rounded-xl px-3 py-2",
          "cursor-pointer select-none",
          "hover:bg-white/5 transition",
          isActive ? "bg-white/10 text-text" : "text-text-muted hover:text-text",
        ].join(" ")}
        style={{ paddingLeft: 12 + level * 12 }}
        onClick={() => onSelect(node.slug)}  // Kategori seçildiğinde onSelect fonksiyonu çalışacak
        role="button"
        tabIndex={0}
      >
        <span className="truncate text-sm font-medium">{node.name}</span>

        {hasChildren && (
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation()
              onToggle()
            }}
            className="p-2 rounded-lg hover:bg-white/5 transition text-text-muted cursor-pointer"
            aria-label="Toggle children"
          >
            <ChevronRight className={["w-4 h-4 transition", expanded ? "rotate-90" : ""].join(" ")} />
          </button>
        )}
      </div>

      {hasChildren && expanded && (
        <div className="mt-1 space-y-1">
          {node.children!.map((c) => (
            <CategoryBranch
              key={c.id}
              node={c}
              level={level + 1}
              activeSlug={activeSlug}
              onSelect={onSelect}
            />
          ))}
        </div>
      )}
    </div>
  )
}

function CategoryBranch({
  node,
  level,
  activeSlug,
  onSelect,
}: {
  node: CategoryNode
  level: number
  activeSlug?: string | null
  onSelect: (slug: string) => void
}) {
  const hasChildren = (node.children?.length ?? 0) > 0
  const [expanded, setExpanded] = useState(level <= 0) // istersen false yap

  return (
    <TreeNode
      node={node}
      level={level}
      activeSlug={activeSlug}
      expanded={hasChildren ? expanded : false}
      onToggle={() => setExpanded((v) => !v)}
      onSelect={onSelect}
    />
  )
}

export default function CategoriesSidebar({
  isOpen,
  categories,
  activeSlug,
  onClose,
  onSelect,
}: Props) {
  const navigate = useNavigate()  // React Router'ın navigate hook'u
  const visible = useMemo(() => (isOpen ? "translate-x-0" : "-translate-x-full"), [isOpen])

  // Kategori seçildiğinde yönlendirme yapılacak
  const handleSelect = (slug: string) => {
    onSelect(slug)  // Seçim sonrası onSelect callback'ini çalıştırıyoruz
    navigate(`/category/${slug}`)  // Kategori sayfasına yönlendirme
    onClose()  // Sidebar'ı kapatıyoruz
  }

  return (
    <>
      {isOpen && (
        <div className="fixed inset-0 z-[90] bg-black/40" onClick={onClose} aria-hidden="true" />
      )}

      <aside
        className={[
          "fixed left-0 top-0 h-full w-[320px] z-[100]",
          "bg-surface border-r border-white/10",
          "transform transition-transform duration-200",
          visible,
        ].join(" ")}
      >
        <div className="flex items-center justify-between p-4 border-b border-white/10">
          <div className="text-sm font-semibold text-grey">Kategoriler</div>
          <button
            type="button"
            onClick={onClose}
            className="p-2 rounded-xl hover:bg-white/5 transition text-text-muted cursor-pointer"
            aria-label="Close"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="p-3 text-grey space-y-1 overflow-y-auto h-[calc(100%-64px)]">
          {categories.map((cat) => (
            <CategoryBranch
              key={cat.id}
              node={cat}
              level={0}
              activeSlug={activeSlug}
              onSelect={handleSelect}  // handleSelect fonksiyonunu onSelect olarak veriyoruz
            />
          ))}
        </div>
      </aside>
    </>
  )
}
