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

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
          }
        }
      })
    })
  }
  const btnClasses = "w-full text-left p-2 m-2 hover:bg-slate-300 rounded disabled disabled:cursor-not-allowed disabled:opacity-40 cursor-pointer ";

  return <>
    <HeaderMenu />
    <div className={"container mx-auto flex flex-wrap sm:m-2"}>

      <div className={"basis-1/3"}>
        I know:
          { languages.map(language => (
          <motion.button whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.9 }} key={language.id} onClick={() => selectLanguage('primary', language.id)}
                  disabled={language.selectedAsSecondary}
              className={btnClasses + (language.selectedAsPrimary ? 'bg-indigo-600 text-white' : '')}>
            { language.name}
          </motion.button>
        ))}
      </div>
      <div className={"basis-1/3"}>
        I'm learning
        <div className={"block"}>
          { languages.map(language => (
            <motion.button whileHover={{ scale: 1.05 }} key={language.id}
                    onClick={() => selectLanguage('secondary', language.id)}
                    disabled={language.selectedAsPrimary}
                    className={btnClasses +
                      (language.selectedAsSecondary ? 'bg-indigo-600' : '')}>{ language.name}</motion.button>
          ))}
        </div>
      </div>
    </div>
  </>
}

export default AddNewVocabulary;