import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { ChevronDown, ChevronRight, Pin } from 'lucide-react'
import { getTreeNavigatePath } from '@/lib/routing'
import { cn } from '@/lib/utils'
import type { PinnedFlow } from '@/api/pinnedFlows'

interface PinnedFlowsSectionProps {
  flows: PinnedFlow[]
  onUnpin: (treeId: string) => void
}

export function PinnedFlowsSection({ flows, onUnpin }: PinnedFlowsSectionProps) {
  const navigate = useNavigate()
  const [collapsed, setCollapsed] = useState(false)

  return (
    <div className="px-3 py-2">
      <button
        onClick={() => setCollapsed(!collapsed)}
        className="flex w-full items-center gap-1 px-3 mb-1 font-heading text-[0.6875rem] font-bold uppercase tracking-[0.04em] text-muted-foreground hover:text-foreground transition-colors"
      >
        {collapsed ? <ChevronRight size={12} /> : <ChevronDown size={12} />}
        Pinned
      </button>

      {!collapsed && (
        <div className="space-y-0.5 max-h-[280px] overflow-y-auto">
          {flows.length === 0 ? (
            <p className="px-3 py-2 text-xs text-muted-foreground">
              Pin your most-used flows here
            </p>
          ) : (
            flows.map(flow => (
              <button
                key={flow.tree_id}
                onClick={() => navigate(getTreeNavigatePath(flow.tree_id, flow.tree_type))}
                onContextMenu={(e) => {
                  e.preventDefault()
                  onUnpin(flow.tree_id)
                }}
                className={cn(
                  'group flex w-full items-center gap-2.5 rounded-lg px-3 py-1.5 text-[0.8125rem] font-medium transition-colors',
                  'text-muted-foreground hover:bg-[hsl(var(--sidebar-hover))] hover:text-foreground'
                )}
                title={`${flow.tree_name} (right-click to unpin)`}
              >
                <span className="text-sm shrink-0">
                  {flow.tree_type === 'procedural' ? '📋' : '🔧'}
                </span>
                <span className="truncate flex-1 text-left">{flow.tree_name}</span>
                <Pin size={12} className="shrink-0 opacity-0 group-hover:opacity-40 transition-opacity" />
              </button>
            ))
          )}
        </div>
      )}
    </div>
  )
}
