'use client';

import {
  forwardRef,
  type HTMLAttributes,
  type ReactNode,
  createContext,
  useContext,
  useState,
  useCallback,
} from 'react';
import { cn } from '@/lib/cn';

interface TooltipContextValue {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

const TooltipContext = createContext<TooltipContextValue>({
  open: false,
  onOpenChange: () => {},
});

function TooltipProvider({ children }: { children: ReactNode; delayDuration?: number }) {
  return <>{children}</>;
}

function Tooltip({ children }: { children: ReactNode }) {
  const [open, setOpen] = useState(false);

  const onOpenChange = useCallback((value: boolean) => {
    setOpen(value);
  }, []);

  return (
    <TooltipContext.Provider value={{ open, onOpenChange }}>
      <div className="relative inline-flex">{children}</div>
    </TooltipContext.Provider>
  );
}

function TooltipTrigger({
  children,
  asChild: _asChild,
  ...props
}: HTMLAttributes<HTMLDivElement> & { asChild?: boolean }) {
  const { onOpenChange } = useContext(TooltipContext);

  return (
    <div
      onMouseEnter={() => onOpenChange(true)}
      onMouseLeave={() => onOpenChange(false)}
      onFocus={() => onOpenChange(true)}
      onBlur={() => onOpenChange(false)}
      {...props}
    >
      {children}
    </div>
  );
}

const TooltipContent = forwardRef<
  HTMLDivElement,
  HTMLAttributes<HTMLDivElement> & { sideOffset?: number; side?: 'top' | 'bottom' | 'left' | 'right' }
>(({ className, side = 'top', children, ...props }, ref) => {
  const { open } = useContext(TooltipContext);

  if (!open) return null;

  return (
    <div
      ref={ref}
      className={cn(
        'absolute z-50 overflow-hidden rounded-lg border border-[#E5E7EB] bg-white px-3 py-1.5 text-sm text-gray-900 shadow-md',
        side === 'top' && 'bottom-full left-1/2 mb-2 -translate-x-1/2',
        side === 'bottom' && 'top-full left-1/2 mt-2 -translate-x-1/2',
        side === 'left' && 'right-full top-1/2 mr-2 -translate-y-1/2',
        side === 'right' && 'left-full top-1/2 ml-2 -translate-y-1/2',
        className,
      )}
      {...props}
    >
      {children}
    </div>
  );
});
TooltipContent.displayName = 'TooltipContent';

export {
  Tooltip,
  TooltipTrigger,
  TooltipContent,
  TooltipProvider,
};
