'use client'

import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import { createClient } from '@/lib/supabase/client'
import {
  Coffee,
  LayoutDashboard,
  Package,
  BookOpen,
  ShoppingCart,
  BarChart3,
  LogOut,
  ChevronLeft,
  ChevronRight,
  GitBranch,
  ArrowLeftRight,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { useState } from 'react'
import { Button } from './ui/button'
import { toast } from 'sonner'
import { BranchSelector } from './branch-selector'

const nav = [
  { href: '/dashboard', label: 'Хяналтын самбар', icon: LayoutDashboard },
  { href: '/materials', label: 'Түүхий эд', icon: Package },
  { href: '/products', label: 'Бүтээгдэхүүн', icon: Coffee },
  { href: '/technology-cards', label: 'Технологийн карт', icon: BookOpen },
  { href: '/sales', label: 'Борлуулалт', icon: ShoppingCart },
  { href: '/transfers', label: 'Шилжүүлэг', icon: ArrowLeftRight },
  { href: '/reports', label: 'Тайлан', icon: BarChart3 },
  { href: '/branches', label: 'Салбарууд', icon: GitBranch },
]

export function Sidebar({
  shopName,
  branches,
  currentBranchId,
}: {
  shopName: string
  branches: { id: string; name: string }[]
  currentBranchId: string | null
}) {
  const pathname = usePathname()
  const router = useRouter()
  const [collapsed, setCollapsed] = useState(false)

  async function handleLogout() {
    const supabase = createClient()
    await supabase.auth.signOut()
    toast.success('Системээс гарлаа')
    router.push('/')
    router.refresh()
  }

  return (
    <aside
      className={cn(
        'flex flex-col bg-white border-r border-gray-200 transition-all duration-300 h-screen sticky top-0',
        collapsed ? 'w-16' : 'w-60'
      )}
    >
      {/* Logo */}
      <div className="flex items-center gap-3 p-4 border-b border-gray-100">
        <div className="bg-amber-600 rounded-lg p-1.5 shrink-0">
          <Coffee className="h-5 w-5 text-white" />
        </div>
        {!collapsed && (
          <span className="font-semibold text-gray-900 truncate text-sm">{shopName}</span>
        )}
      </div>

      {/* Branch selector */}
      {!collapsed && (
        <div className="border-b border-gray-100">
          <BranchSelector branches={branches} currentBranchId={currentBranchId} />
        </div>
      )}

      {/* Nav */}
      <nav className="flex-1 p-2 space-y-1 overflow-y-auto">
        {nav.map(({ href, label, icon: Icon }) => {
          const active = pathname === href || pathname.startsWith(href + '/')
          return (
            <Link
              key={href}
              href={href}
              className={cn(
                'flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors',
                active
                  ? 'bg-amber-50 text-amber-700'
                  : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900'
              )}
            >
              <Icon className="h-5 w-5 shrink-0" />
              {!collapsed && <span>{label}</span>}
            </Link>
          )
        })}
      </nav>

      {/* Bottom */}
      <div className="p-2 border-t border-gray-100 space-y-1">
        <Button
          variant="ghost"
          className="w-full justify-start gap-3 text-gray-600 hover:text-red-600 hover:bg-red-50"
          onClick={handleLogout}
        >
          <LogOut className="h-5 w-5 shrink-0" />
          {!collapsed && <span>Гарах</span>}
        </Button>
        <Button
          variant="ghost"
          size="sm"
          className="w-full justify-center"
          onClick={() => setCollapsed(!collapsed)}
        >
          {collapsed ? <ChevronRight className="h-4 w-4" /> : <ChevronLeft className="h-4 w-4" />}
        </Button>
      </div>
    </aside>
  )
}
