'use client';

import * as React from 'react';
import { useOnClickOutside } from 'usehooks-ts';
import { SelectContext } from './SelectContext';

export default function Select({
  children,
  value: controlledValue,
  onChange,
  defaultValue,
}: {
  children: React.ReactNode;
  value?: string;
  onChange?: (value: string) => void;
  defaultValue?: string;
}) {
  const [open, setOpen] = React.useState(false);
  const [internalValue, setInternalValue] = React.useState(defaultValue || '');
  const ref = React.useRef<HTMLDivElement>(null);

  const handleClickOutside = () => {
    setOpen(false);
  };

  useOnClickOutside<HTMLDivElement>(ref as React.RefObject<HTMLDivElement>, handleClickOutside);

  const value = controlledValue !== undefined ? controlledValue : internalValue;
  const handleChange = onChange || setInternalValue;

  return (
    // eslint-disable-next-line react/no-unstable-context-value
    <SelectContext.Provider value={{ open, setOpen, value, onChange: handleChange }}>
      <div className="relative" ref={ref}>{children}</div>
    </SelectContext.Provider>
  );
}
