import React, { useEffect, useState } from 'react'
import { NameItem, NameType } from '../../../api/models/Types'

export interface INamesViewComponentProps{
    excludeNames: Array<NameItem>,
    names: Array<NameItem>,
	userLanguageId?: string | null | undefined,
}

type NameTab = {
    tabName: string,
    enabled: boolean,
	names: Array<NameItem>
}

export default function NamesViewComponent(props: INamesViewComponentProps) {
	//language
    const [tabs, updateTabs] = useState<Array<NameTab>>([]);
    const [selectedTab, setSelectedTab] = useState<string | null>(null);

	useEffect(() => {
		const names = props.names.filter(q => !props.excludeNames.includes(q) && q.type != NameType.Abbreviation);
    	const abbreviations = props.names.filter(q => !props.excludeNames.includes(q) && q.type == NameType.Abbreviation);
		const tabs = [
			{
				tabName: 'Другие названия',
				enabled: names.length > 0,
				names: names
			} as NameTab,
			{
				tabName: 'Аббривеатуры',
				enabled: abbreviations.length > 0,
				names:abbreviations
			} as NameTab,
		];

		if (!tabs.some(q => q.enabled)) setSelectedTab(null);
		else setSelectedTab(!tabs[0].enabled ? tabs[1].tabName : tabs[0].tabName);
		updateTabs(tabs);
	}, [props]);

	const OnTabSelected = (tabName: string) =>{
		if (selectedTab == tabName) return;
        else setSelectedTab(tabName);
	};

	return (
		<div className='card p-0'>
            <div className='card-header'>
				<ul className="nav nav-underline">
					{
						React.Children.toArray(
							tabs.map((tab) => 
								<li className='user-select-none nav-item' >
									<a className={'nav-link' + (tab.tabName == selectedTab ? ' active' : '') + (!tab.enabled ? ' disabled' : '')} onClick={() => OnTabSelected(tab.tabName)}>{tab.tabName}</a>
								</li>
							)
						)
					}
                </ul>

            </div>

            {selectedTab != undefined && selectedTab != null &&
				<div className='card-body vstack gap-2'>
					{
						React.Children.toArray(
							tabs.filter(q => q.tabName == selectedTab).map((tab) => 
								React.Children.toArray(
									tab.names.map((item) => ShowName(item))
									)
							)
						)
					}
				</div>
            }

        </div>
    )
}

function ShowName(name: NameItem){
    return (
        <div className='border p-1 rounded bg-secondary'>
			{<span className={name.type == NameType.Original ? 'fw-bold' : ''}>[{name.language.codeIso3}]</span>} <span className='user-select-all'>{name.value}</span>
		</div>
    )
}