import { Theme } from "@radix-ui/themes"
import { cva } from "class-variance-authority"
import clsx from "clsx"
import type * as React from "react"
import { useMemo, useRef } from "react"
import { Drawer as DrawerPrimitive } from "vaul"
import { DrawerContext, useDrawerContext } from "./drawer.context"
import { useSwipeToClose } from "./drawer.hook"
import type { DrawerDirection } from "./drawer.type"

const drawerContentVariants = cva(
  "group/drawer-content bg-background fixed z-50 flex h-auto flex-col",
  {
    variants: {
      direction: {
        top: [
          "data-[vaul-drawer-direction=top]:inset-x-0",
          "data-[vaul-drawer-direction=top]:top-0",
          "data-[vaul-drawer-direction=top]:mb-24",
          "data-[vaul-drawer-direction=top]:max-h-[80vh]",
          "data-[vaul-drawer-direction=top]:rounded-b-lg",
        ],
        bottom: [
          "data-[vaul-drawer-direction=bottom]:inset-x-0",
          "data-[vaul-drawer-direction=bottom]:bottom-0",
          "data-[vaul-drawer-direction=bottom]:mt-24",
          "data-[vaul-drawer-direction=bottom]:max-h-[80vh]",
          "data-[vaul-drawer-direction=bottom]:rounded-t-lg",
        ],
        right: [
          "data-[vaul-drawer-direction=right]:inset-y-0",
          "data-[vaul-drawer-direction=right]:right-0",
        ],
        left: [
          "data-[vaul-drawer-direction=left]:inset-y-0",
          "data-[vaul-drawer-direction=left]:left-0",
        ],
      },
      width: {
        sm: ["data-[vaul-drawer-direction=right]:w-80", "data-[vaul-drawer-direction=left]:w-80"],
        md: ["data-[vaul-drawer-direction=right]:w-96", "data-[vaul-drawer-direction=left]:w-96"],
        lg: [
          "data-[vaul-drawer-direction=right]:w-[28rem]",
          "data-[vaul-drawer-direction=left]:w-[28rem]",
        ],
        xl: [
          "data-[vaul-drawer-direction=right]:w-[32rem]",
          "data-[vaul-drawer-direction=left]:w-[32rem]",
        ],
        "2xl": [
          "data-[vaul-drawer-direction=right]:w-[36rem]",
          "data-[vaul-drawer-direction=left]:w-[36rem]",
        ],
        full: [
          "data-[vaul-drawer-direction=right]:w-full",
          "data-[vaul-drawer-direction=left]:w-full",
        ],
        auto: [
          "data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:sm:max-w-sm",
          "data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:sm:max-w-sm",
        ],
      },
    },
    defaultVariants: {
      direction: "bottom",
      width: "auto",
    },
  },
)

type DrawerProps = React.ComponentProps<typeof DrawerPrimitive.Root> & {
  direction?: DrawerDirection
}

type DrawerContentProps = React.ComponentProps<typeof DrawerPrimitive.Content> & {
  width?: "sm" | "md" | "lg" | "xl" | "2xl" | "full" | "auto"
  onOpenChange?: (open: boolean) => void
}

function Drawer({ direction = "bottom", open, onOpenChange, ...props }: DrawerProps) {
  useSwipeToClose({
    isOpen: open ?? false,
    direction,
    onClose: () => onOpenChange?.(false),
    threshold: 50,
  })

  const contextValue = useMemo(
    () => ({
      direction,
      isOpen: open ?? false,
      onOpenChange: onOpenChange || (() => {}),
    }),
    [direction, open, onOpenChange],
  )

  return (
    <DrawerContext.Provider value={contextValue}>
      <DrawerPrimitive.Root
        data-slot="drawer"
        direction={direction}
        open={open}
        onOpenChange={onOpenChange}
        {...props}
      >
        {props.children}
      </DrawerPrimitive.Root>
    </DrawerContext.Provider>
  )
}

function DrawerTrigger({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
  return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
}

function DrawerPortal({ ...props }: Readonly<React.ComponentProps<typeof DrawerPrimitive.Portal>>) {
  return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
}

function DrawerClose({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Close>) {
  return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
}

function DrawerOverlay({
  className,
  ...props
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
  return (
    <DrawerPrimitive.Overlay
      data-slot="drawer-overlay"
      className={clsx(
        "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/80",
        className,
      )}
      {...props}
    />
  )
}

function DrawerContent({
  className,
  children,
  width = "auto",
  onOpenChange,
  ...props
}: DrawerContentProps) {
  const contentRef = useRef<HTMLDivElement>(null)

  const { direction } = useDrawerContext()

  return (
    <DrawerPortal data-slot="drawer-portal">
      <DrawerOverlay />
      <DrawerPrimitive.Content
        ref={contentRef}
        data-slot="drawer-content"
        className={clsx(drawerContentVariants({ direction, width }), className)}
        {...props}
      >
        <Theme appearance="light" accentColor="blue" grayColor="slate" radius="large">
          <div className="bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block group-data-[vaul-drawer-direction=top]/drawer-content:block" />
          {children}
        </Theme>
      </DrawerPrimitive.Content>
    </DrawerPortal>
  )
}

function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="drawer-header"
      className={clsx("flex flex-col gap-1.5 p-4", className)}
      {...props}
    />
  )
}

function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="drawer-footer"
      className={clsx("mt-auto flex flex-col gap-2 p-4", className)}
      {...props}
    />
  )
}

function DrawerTitle({ className, ...props }: React.ComponentProps<typeof DrawerPrimitive.Title>) {
  return (
    <DrawerPrimitive.Title
      data-slot="drawer-title"
      className={clsx("text-foreground font-semibold", className)}
      {...props}
    />
  )
}

function DrawerDescription({
  className,
  ...props
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
  return (
    <DrawerPrimitive.Description
      data-slot="drawer-description"
      className={clsx("text-muted-foreground text-sm", className)}
      {...props}
    />
  )
}

export {
  Drawer,
  DrawerClose,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerOverlay,
  DrawerPortal,
  DrawerTitle,
  DrawerTrigger,
}
