"use client"

import * as React from "react"
import { useIsMobile } from "@/hooks/use-mobile"
import { Button } from "@/components/ui/button"
import { Drawer as DrawerPrimitive } from "vaul"
import { MoreVerticalIcon, XIcon } from "lucide-react"
import { cn } from "@/lib/utils"

interface ActionItem {
  label: string
  icon?: React.ReactNode
  onClick?: () => void
  className?: string
  variant?: "default" | "outline" | "ghost" | "destructive" | "secondary"
  href?: string
}

interface ResponsiveActionsProps {
  actions: ActionItem[]
  className?: string
}

/**
 * ResponsiveActions
 * On desktop: renders action buttons inline
 * On mobile: collapses into a "⋮" icon that opens a bottom drawer with action items
 */
export function ResponsiveActions({ actions, className }: ResponsiveActionsProps) {
  const isMobile = useIsMobile()
  const [open, setOpen] = React.useState(false)

  if (!isMobile) {
    return (
      <div className={cn("flex gap-2", className)}>
        {actions.map((action, i) => (
          <Button
            key={i}
            variant={(action.variant as any) || "outline"}
            onClick={action.onClick}
            className={action.className}
          >
            {action.icon && <span className="ml-1.5">{action.icon}</span>}
            {action.label}
          </Button>
        ))}
      </div>
    )
  }

  return (
    <DrawerPrimitive.Root open={open} onOpenChange={setOpen}>
      <DrawerPrimitive.Trigger asChild>
        <Button variant="ghost" size="icon" className="shrink-0 md:hidden">
          <MoreVerticalIcon className="w-5 h-5" />
        </Button>
      </DrawerPrimitive.Trigger>
      <DrawerPrimitive.Portal>
        <DrawerPrimitive.Overlay className="fixed inset-0 z-50 bg-black/20 supports-backdrop-filter:backdrop-blur-xs" />
        <DrawerPrimitive.Content className="fixed z-50 flex flex-col bg-background inset-x-0 bottom-0 rounded-t-2xl border-t shadow-2xl max-h-[60vh]">
          <div className="mx-auto mt-3 mb-2 h-1.5 w-[60px] shrink-0 rounded-full bg-muted-foreground/20" />
          <DrawerPrimitive.Title className="sr-only">عملیات</DrawerPrimitive.Title>
          <div className="flex flex-col gap-2 p-4 pb-8 overflow-y-auto">
            {actions.map((action, i) => (
              <Button
                key={i}
                variant={(action.variant as any) || "outline"}
                className={cn("w-full h-12 text-sm justify-start gap-3 rounded-xl", action.className)}
                onClick={() => {
                  action.onClick?.()
                  setOpen(false)
                }}
              >
                {action.icon}
                {action.label}
              </Button>
            ))}
          </div>
        </DrawerPrimitive.Content>
      </DrawerPrimitive.Portal>
    </DrawerPrimitive.Root>
  )
}
