'use client'

import { useRouter } from 'next/navigation'
import { GitBranch } from 'lucide-react'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { setSelectedBranch } from '@/lib/branch-actions'

type Branch = { id: string; name: string }

export function BranchSelector({
  branches,
  currentBranchId,
}: {
  branches: Branch[]
  currentBranchId: string | null
}) {
  const router = useRouter()

  if (branches.length === 0) return null

  async function handleChange(v: string | null) {
    if (!v) return
    await setSelectedBranch(v)
    router.refresh()
  }

  return (
    <div className="flex items-center gap-2 px-3 py-2">
      <GitBranch className="h-3.5 w-3.5 text-amber-600 shrink-0" />
      <Select value={currentBranchId ?? undefined} onValueChange={handleChange}>
        <SelectTrigger className="h-7 text-xs border-amber-200 bg-amber-50 text-amber-800 flex-1 min-w-0">
          <SelectValue placeholder="Салбар сонгох">
            {branches.find(b => b.id === currentBranchId)?.name ?? null}
          </SelectValue>
        </SelectTrigger>
        <SelectContent>
          {branches.map(b => (
            <SelectItem key={b.id} value={b.id} className="text-xs">
              {b.name}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  )
}
