import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

const getTimeFormat = (currentLanguage: string) => new Intl.DateTimeFormat(currentLanguage, {
    dateStyle: "full",
    timeStyle: "long",
    timeZone: "Europe/Warsaw",
}).format(new Date());

export const Header = () => {
    const { t, i18n: { changeLanguage, language } } = useTranslation();
    const [currentLanguage, setCurrentLanguage] = useState(language);
    const [clock, setClock] = useState(getTimeFormat(currentLanguage));

    useEffect(() => {
        setClock(getTimeFormat(currentLanguage));
        const _ = setInterval(() => setClock(getTimeFormat(currentLanguage)), 1000);
        return () => clearInterval(_);
    }, [currentLanguage]);


    const handleChangeLanguage = () => {
        const newLanguage = currentLanguage === "en" ? "pl" : "en";
        setCurrentLanguage(newLanguage);
        changeLanguage(newLanguage);
    }

    return <div className='sticky flex flex-col gap-24 top-4 select-none'>
        <div className='p-4 border-1 border-[#757575] rounded-xl flex flex-col md:flex-row grow justify-around bg-[#1C1C1C]'>
            <h1 className='text-white'>{t('header.home')}</h1>

            <h1 className='text-white'>{clock}</h1>
            <h1 className='text-white'>
                <button className='cursor-pointer' onClick={handleChangeLanguage}>{['PL', 'EN'].map<React.ReactNode>(x => currentLanguage.includes(x.toLocaleLowerCase()) ? (<b>{x}</b>) : x).reduce((prev, curr) => [prev, '/', curr])}</button>
            </h1>
        </div>
    </div>;
}