'use client';

import { X } from 'lucide-react';
import { useEffect } from 'react';
import clsx from 'clsx';

interface BottomDrawerProps {
  isOpen: boolean;
  title: string;
  subtitle?: string;
  onClose: () => void;
  children: React.ReactNode;
  footer?: React.ReactNode;
  showSearch?: boolean;
  onSearch?: (val: string) => void;
}

export default function BottomDrawer({
  isOpen,
  title,
  subtitle,
  onClose,
  children,
  footer,
  showSearch,
  onSearch,
}: BottomDrawerProps) {
  useEffect(() => {
    document.body.style.overflow = isOpen ? 'hidden' : '';
    return () => {
      document.body.style.overflow = '';
    };
  }, [isOpen]);

  return (
    <div
      className={clsx(
        'fixed inset-0 z-50 flex items-end transition-opacity duration-300',
        isOpen ? 'pointer-events-auto bg-black/40' : 'pointer-events-none bg-transparent'
      )}
      onClick={onClose}
    >
      {/* Drawer Content */}
      <div
        className={clsx(
  'w-full bg-white rounded-t-xl shadow-xl transform transition-transform duration-300 ease-in-out dark:bg-background',
  'min-h-[30vh] max-h-[70vh] h-auto overflow-y-auto',
  isOpen ? 'translate-y-0' : 'translate-y-full'
)}

        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="sticky top-0 z-50 bg-white flex items-center justify-between px-4 py-3 border-b dark:bg-darkbg dark:border-darkborder">
          <div>
            <h2 className="text-base font-semibold dark:text-white">{title}</h2>
            {subtitle && <span className="text-sm text-gray-500">{subtitle}</span>}
          </div>
          <button onClick={onClose}>
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* Optional Search */}
        {showSearch && (
          <div className="px-4 py-2 border-b dark:border-darkborder">
            <input
              type="text"
              placeholder="Type here"
              onChange={(e) => onSearch?.(e.target.value)}
              className="w-full px-3 py-2 border rounded text-sm"
            />
          </div>
        )}

        {/* Body */}
        <div className="px-4 py-4 overflow-y-auto h-full">
          {children}
        </div>

        {/* Footer */}
        {footer && (
          <div className="px-4 py-3 border-t bg-white sticky bottom-0 dark:border-darkborder dark:bg-darkbg">
            {footer}
          </div>
        )}
      </div>
    </div>
  );
}
