import * as SheetPrimitive from '@radix-ui/react-dialog'
import { cva, type VariantProps } from 'class-variance-authority'
import type * as React from 'react'
import { SvgDelete1 } from '@chainlink/blocks-icons'
import { cn } from '../../utils'
import { ButtonIcon, type ButtonIconProps } from '../Button'
import {
  Sheet,
  SheetClose,
  SheetFooter,
  SheetOverlay,
  SheetPortal,
  SheetTitle,
  SheetTrigger,
  SheetHeader,
} from '../Sheet/sheet'

const SidePanel = Sheet
SidePanel.displayName = 'SidePanel'

const SidePanelTrigger = SheetTrigger
SidePanelTrigger.displayName = 'SidePanelTrigger'

const SidePanelFooter = SheetFooter
SidePanelFooter.displayName = 'SidePanelFooter'

const SidePanelClose = SheetClose
SidePanelClose.displayName = 'SidePanelClose'

type SidePanelCloseMobileProps = ButtonIconProps & {
  ref?: React.Ref<HTMLButtonElement>
}

const SidePanelCloseMobile = ({
  className,
  ref,
  ...props
}: SidePanelCloseMobileProps) => (
  <SidePanelClose asChild>
    <ButtonIcon
      className={cn('absolute right-6 top-4 md:hidden', className)}
      {...props}
      ref={ref}
      size="sm"
    >
      <SvgDelete1 />
    </ButtonIcon>
  </SidePanelClose>
)
SidePanelCloseMobile.displayName = 'SidePanelCloseMobile'

const SidePanelCloseDesktop = () => (
  <div className="absolute -left-16 top-4 hidden md:block">
    <SidePanelClose asChild>
      <button className="flex flex-col items-center gap-2 rounded-sm transition-colors">
        <svg
          className="rounded"
          width="48"
          height="48"
          viewBox="0 0 48 48"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <rect
            className="transition-colors hover:fill-blue-700"
            width="48"
            height="48"
            rx="4"
            fill="var(--gray-950)"
          />
          <path
            d="M30.1666 17.3334L16.8333 30.6667M16.8333 17.3334L30.1666 30.6667"
            stroke="white"
            strokeWidth="1.5"
          />
        </svg>
      </button>
    </SidePanelClose>
    <div className="mx-auto mt-2 text-center text-xs text-[#6C7585]">Esc</div>
  </div>
)

export const SidePanelVariants = cva(
  'w-full md:w-[calc(100%-80px)] fixed z-[17] bg-background-alt shadow-lg ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500 flex flex-col transition-all',
  {
    variants: {
      side: {
        right:
          'inset-y-0 right-0 h-full border-l border-border data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right',
      },
      variant: {
        narrow: 'sm:max-w-screen-lg',
        wide: 'sm:max-w-screen-xl',
      },
    },
    defaultVariants: {
      side: 'right',
      variant: 'narrow',
    },
  },
)

export interface SidePanelContentProps
  extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
    VariantProps<typeof SidePanelVariants> {
  ref?: React.Ref<React.ElementRef<typeof SheetPrimitive.Content>>
}

const SidePanelContent = ({
  side,
  variant,
  className,
  children,
  ref,
  ...props
}: SidePanelContentProps) => (
  <SheetPortal>
    <SheetOverlay />
    <SheetPrimitive.Content
      ref={ref}
      className={cn(SidePanelVariants({ side, variant }), className)}
      {...props}
    >
      {children}
      <SidePanelCloseDesktop />
    </SheetPrimitive.Content>
  </SheetPortal>
)
SidePanelContent.displayName = 'SidePanelContent'

const SidePanelScrollArea = ({ children }: { children: React.ReactNode }) => (
  <div className="flex h-full flex-col overflow-y-auto [&>*:last-child]:flex-grow">
    {children}
  </div>
)

type SidePanelTitleProps = React.ComponentPropsWithoutRef<typeof SheetTitle> & {
  ref?: React.Ref<React.ElementRef<typeof SheetTitle>>
}

const SidePanelTitle = ({ className, ref, ...props }: SidePanelTitleProps) => (
  <SheetTitle ref={ref} className={cn(className)} {...props} />
)
SidePanelTitle.displayName = 'SidePanelTitle'

// SidePanelHeader composes SheetHeader with built-in close button
// Uses grid on mobile: content wrapper on left, close on right
// Desktop: flex row
const SidePanelHeader = ({
  className,
  children,
  ...props
}: React.ComponentPropsWithoutRef<typeof SheetHeader>) => {
  return (
    <SheetHeader
      className={cn(
        'space-y-0',
        // Mobile: grid with content on left, close on right
        'grid grid-cols-[1fr_auto] items-center gap-2',
        // Desktop: flex row
        'md:flex md:flex-row',
        className,
      )}
      {...props}
    >
      {/* Content wrapper - contains all children (title, left items, right items) */}
      <div className="flex flex-1 items-center gap-4">{children}</div>
      {/* Close button always on right - override absolute positioning to make it flow */}
      <SidePanelCloseMobile className="static" />
    </SheetHeader>
  )
}
SidePanelHeader.displayName = 'SidePanelHeader'

export {
  SidePanel,
  SidePanelTrigger,
  SidePanelContent,
  SidePanelScrollArea,
  SidePanelCloseMobile,
  SidePanelTitle,
  SidePanelFooter,
  SidePanelClose,
  SidePanelHeader,
}
