import clsx from 'clsx';
import { useEffect, useRef } from 'react';

export type ElementType<T> = T extends (infer U)[] ? U : never;

export interface RadioChangeProps<ValueType> {
  event: React.ChangeEvent<HTMLInputElement>;
  label?: string;
  value: ValueType;
}
export interface SelectTemplateProps<ValueType> {
  values?: ValueType[];
  valueKey?: keyof ValueType;
  labels?: string[];
  selectedLabel?: string;
  selectedValue?: string;
  onRadioChange?: ({ event, label, value }: RadioChangeProps<ValueType>) => void;
}

export const SelectTemplate = ({
  values = [],
  valueKey,
  labels = [],
  selectedLabel,
  selectedValue,
  onRadioChange,
}: SelectTemplateProps<any>) => {
  const refs = useRef<(HTMLLabelElement | null)[]>([]);

  const handleRadioChange = ({ event, label, value }: RadioChangeProps<ElementType<typeof values>>) => {
    onRadioChange?.({ event, label, value });
  };

  useEffect(() => {
    const scrollIntoView = (array: any[], selected: string | undefined) => {
      const index = array?.indexOf(selected ?? '');
      if (index !== -1 && refs.current[index]) {
        refs.current[index]?.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
    };
    scrollIntoView(labels, selectedLabel);
    scrollIntoView(values, selectedValue);
  }, [selectedLabel, labels, selectedValue, values]);

  return (
    <div
      style={{ height: '100%', maxHeight: '50dvh', overflowY: 'auto' }}
      className="show-scrollbar mx-[24px] pb-[30px] pt-[20px]"
    >
      {values?.map((value, index) => {
        return (
          <label
            htmlFor={labels?.[index]}
            key={labels?.[index]}
            className={clsx('btm-sheet-btn block h-[52px] text-[15px]', {
              'selected font-bold text-[#366FC4]':
                selectedLabel === labels?.[index] ||
                selectedValue === (valueKey ? values?.[index]?.[valueKey] : values?.[index]),
            })}
          >
            <input
              className="hidden"
              type="radio"
              id={labels?.[index]}
              //   name={name}
              value={valueKey ? value?.[valueKey] : `${value}`}
              onChange={(event) => handleRadioChange({ 
                event, 
                label: labels?.[index], 
                value 
              })}
            />
            {labels?.[index]}
            <br />
          </label>
        );
      })}
    </div>
  );
};
