import HeaderMenu from "../components/UI/HeaderMenu.tsx";
import {useEffect, useState} from "react";
import {LanguageEntity} from "../types/LanguageEntity.ts";
import api from "../api.tsx";

const AddNewVocabulary = () => {
  type SelectableLanguageEntity = LanguageEntity & { selectedAsPrimary: boolean, selectedAsSecondary: boolean };
  const [languages, setLanguages] = useState<SelectableLanguageEntity[]>([]);

  useEffect(() => {
    api.get<LanguageEntity[]>('language').then(languages => {
      setLanguages(languages.data.map(language => { return { ...language, selectedAsPrimary: false, selectedAsSecondary: false}}));
      console.log(languages.data);
    })
  },[])

  function selectLanguage(type: 'primary'| 'secondary', languageId: string, ) {
    setLanguages((languages) => {
      return languages.map(language => {
        if(language.id === languageId) {
          return {
            ...language,
            selectedAsPrimary: type === 'primary',
            selectedAsSecondary: type === 'secondary'
          }
        } else {
          return {
            ...language,
            selectedAsPrimary: type === 'primary' ? false : language.selectedAsPrimary,
            selectedAsSecondary: type === 'secondary' ? false : language.selectedAsSecondary
          }
        }
      })
    })
  }

  return <>
    <HeaderMenu />
    <div className={"container m-1 flex"}>
      <div className={"basis-1/3"}>
        I know:
          { languages.map(language => (
          <button key={language.id} onClick={() => selectLanguage('primary', language.id)}
                  disabled={language.selectedAsSecondary}
              className={"w-full text-left p-2 m-2 hover:bg-slate-500 rounded cursor-pointer " + (language.selectedAsPrimary ? 'bg-indigo-600' : '')}>
            { language.name}
          </button>
        ))}
      </div>
      <div className={"basis-1/3"}>
        I'm learning
        <div className={"block"}>
          { languages.map(language => (
            <button key={language.id}
                    onClick={() => selectLanguage('secondary', language.id)}
                    disabled={language.selectedAsPrimary}
                    className={"w-full text-left p-2 m-2 hover:bg-slate-500 rounded disabled:cursor-not-allowed disabled:text-gray-50 " +
                      (language.selectedAsSecondary ? 'bg-indigo-600' : '')}>{ language.name}</button>
          ))}
        </div>
      </div>
    </div>
  </>
}

export default AddNewVocabulary;