import { useStore } from "@/shared/model/store";
import { ChangeEvent, useEffect, useState } from "react";

export interface FilterSelectMidProps {
  title: string;
  selectSetter: (value: any) => void;
  showType: 'GID' | 'MID'
};
export const FilterSelectMid = ({
  title,
  selectSetter,
  showType = 'GID'
}: FilterSelectMidProps) => {
  const midOptions = useStore.getState().UserStore.selectOptionsMids;
  const midOptionsWithoutGids = useStore.getState().UserStore.selectOptionsMidsWithoutGids;
  const userMid = useStore.getState().UserStore.mid;

  let options = midOptions;
  if(showType === 'MID'){
    options = midOptionsWithoutGids;
  }
  let midItem = options.filter((value, index) => {
    return value.value === userMid;
  });

  const [filterMid, setFilterMid] = useState<string>((midItem.length > 0)? userMid: '');

  const getSelectMidOptions = () => {
    let rs = [];
    let options = midOptions;
    if(showType === 'MID'){
      options = midOptionsWithoutGids;
    }
    for(let i=0;i<options.length;i++){
      rs.push(
        <option
          key={ `key-filter-select-${i}` }
          value={ options[i]?.value }
        >{ options[i]?.name }</option>
      );
    }
    return rs;
  };
  const onChangeMidSelect = (val: string) => {
    setFilterMid(val);
  };

  useEffect(() => {
    selectSetter(filterMid);
  }, [filterMid]);
  
  return (
    <>
      <div className="opt-field">
        <div 
          className="opt-label"
          style={{ fontSize: 'var(--fs-14)' }}
        >{ title }</div>
        <div className="opt-controls">
          <select 
            className="flex-1"
            value={ filterMid } 
            onChange={ (e: ChangeEvent<HTMLSelectElement>) => onChangeMidSelect(e.target.value)}
          >
            { getSelectMidOptions() }
          </select>
        </div>
      </div>
    </>
  );
};