import { Select as RadixSelect } from '@radix-ui/themes';
import { createContext, forwardRef, useContext, useMemo } from 'react';

const SelectContext = createContext<{ error?: boolean }>({
  error: false,
});

export type ContentProps = RadixSelect.ContentProps & {
  isNavigation?: boolean;
};

const Content = forwardRef<HTMLDivElement, ContentProps>((props, ref) => {
  const { className, isNavigation, ...rest } = props;
  const { error } = useContext(SelectContext);

  const cls = useMemo(() => {
    const etc = isNavigation ? 'nav-select' : '';
    const errorCls = error ? 'tipp-error' : '';
    return [etc, errorCls, className].join(' ');
  }, [className, error, isNavigation]);

  return (
    <RadixSelect.Content
      position="popper"
      {...rest}
      className={cls}
      ref={ref}
    />
  );
});
Content.displayName = 'Select.Content';

const Trigger = forwardRef<HTMLButtonElement, RadixSelect.TriggerProps>(
  (props, ref) => {
    const { className, ...rest } = props;
    const { error } = useContext(SelectContext);

    const cls = useMemo(() => {
      const errorCls = error ? 'error' : '';
      return [errorCls, className].join(' ');
    }, [className, error]);

    return <RadixSelect.Trigger {...rest} className={cls} ref={ref} />;
  }
);

Trigger.displayName = 'Select.Trigger';

export type SelectRootProps = RadixSelect.RootProps & {
  error?: boolean;
};

function Root(props: SelectRootProps): React.ReactElement {
  const { error, ...rest } = props;

  return (
    <SelectContext.Provider value={{ error }}>
      <RadixSelect.Root {...rest} />
    </SelectContext.Provider>
  );
}

Root.displayName = 'Select.Root';

export const Select = {
  ...RadixSelect,
  Root,
  Trigger,
  Content,
};
