import { Icon } from '@iconify-icon/solid';
import { isNotNil } from 'es-toolkit';
import {
  createEffect,
  createMemo,
  createSignal,
  mergeProps,
  ParentComponent,
  ParentProps,
  Show,
} from 'solid-js';
import { Dynamic } from 'solid-js/web';

interface RadioProps {
  name?: string;
  checked?: boolean;
  disabled?: boolean;
  onChange?: (value?: boolean) => void;
}

const RadioIcon = [
  () => <Icon icon="hugeicons:circle" class="stroke-1" />,
  () => <Icon icon="hugeicons:checkmark-circle-03" class="stroke-1 text-primary" />,
];

const Radio: ParentComponent<RadioProps> = (props) => {
  const mProps = mergeProps<ParentProps<RadioProps>[]>(
    {
      disabled: false,
    },
    props,
  );

  const originalChecked = createMemo(() => mProps.checked);
  const [internalChecked, setInternalChecked] = createSignal<boolean | undefined>(undefined);

  createEffect(() => {
    if (isNotNil(originalChecked()) && originalChecked() !== internalChecked()) {
      setInternalChecked(originalChecked());
    }
  });

  const handleClick = () => {
    if (mProps.disabled) {
      return;
    }
    setInternalChecked((prev) => !prev);
    mProps.onChange?.(internalChecked());
  };

  return (
    <div class="flex flex-row items-center gap-1 cursor-pointer" onClick={handleClick}>
      <Dynamic component={RadioIcon[internalChecked() ? 1 : 0]} />
      <div>{mProps.children}</div>
      <Show when={isNotNil(mProps.name)}>
        <input type="hidden" name={mProps.name} value={internalChecked()} />
      </Show>
    </div>
  );
};

export default Radio;
