import Input from "@/components/generics/input/Input";
import "./AbbreviationsBlock.scss";
import { AbbreviationsBlockProps } from "./AbbreviationBlock.interface";
import { useEffect, useMemo, useState } from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { setAbbreviation } from "@/shared/hooks/useAbbreviations/reducer";

export const AbbreviationsBlock = ({ abbreviation, values }: AbbreviationsBlockProps) => {
  const { abbreviations } = useAppSelector((state) => state.request);
  const storedValue = useMemo(() => abbreviations.find((e) => e.key === abbreviation), [abbreviations, abbreviation]);

  const [selectedOption, setSelectedOption] = useState<string>(storedValue?.value ?? values[0]);
  const dispatch = useAppDispatch();

  useEffect(() => {
    dispatch(setAbbreviation({ key: abbreviation, value: selectedOption }));
  }, [abbreviation, dispatch, selectedOption]);

  return (
    <div className="abbreviation_block">
      <div className="label">
        <span>
          Сокращение <b className="abbreviation">{abbreviation}</b> :
        </span>
      </div>
      <div className="abbreviation_container">
        <div className="values">
          {values.map((value, index) => (
            <div key={value + index} className="values_optiuon" onClick={() => setSelectedOption(value)}>
              <div className={`name ${selectedOption === value ? "checked" : ""}`}>{value}</div>
              <div className="radio">
                <Input
                  type="radio"
                  name={`${abbreviation}_value`}
                  onSetValue={() => {}}
                  checked={selectedOption === value}
                />
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};
