'use client';

import * as React from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { clsx } from 'clsx';
import { Button } from './Button.js';

export interface DrawerProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  title: React.ReactNode;
  description?: React.ReactNode;
  side?: 'right' | 'left';
  children: React.ReactNode;
}

export function Drawer({
  open,
  onOpenChange,
  title,
  description,
  side = 'right',
  children,
}: DrawerProps) {
  return (
    <Dialog.Root open={open} onOpenChange={onOpenChange}>
      <Dialog.Portal>
        <Dialog.Overlay className="fixed inset-0 z-[9998] bg-black/50 backdrop-blur-sm" />
        <Dialog.Content
          className={clsx(
            'fixed top-0 z-[9999] flex h-dvh w-full max-w-xl flex-col border-[var(--bl-border)] bg-[var(--bl-bg-elevated)] text-[var(--bl-text-primary)] shadow-xl focus:outline-none',
            side === 'right' ? 'right-0 border-l' : 'left-0 border-r'
          )}
        >
          <div className="flex items-start justify-between gap-4 border-b border-[var(--bl-border)] p-5">
            <div className="min-w-0">
              <Dialog.Title className="m-0 text-lg font-semibold leading-7">{title}</Dialog.Title>
              {description && (
                <Dialog.Description className="mt-1 text-sm leading-6 text-[var(--bl-text-secondary)]">
                  {description}
                </Dialog.Description>
              )}
            </div>
            <Dialog.Close asChild>
              <Button type="button" variant="ghost" size="sm" aria-label="Close drawer">
                <X className="h-4 w-4" aria-hidden="true" />
              </Button>
            </Dialog.Close>
          </div>
          <div className="min-h-0 flex-1 overflow-y-auto p-5">{children}</div>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
}
