import React, { useEffect, useState } from 'react'
import { Description } from '../../../api/models/Types'
import { TruncateString } from '../../../common/Helper';

export interface IDescriptionViewComponentProps{
    descriptions: Array<Description>,
	userLanguageId?: string | null | undefined,
}

type DescriptionTab = {
    tabName: string,
    enabled: boolean,
	descriptions: Array<DescriptionItem>
    
}

type DescriptionItem = {
    order: number | null,
    shortName: string,
    description: Description
}

export default function DescriptionViewComponent(props: IDescriptionViewComponentProps) {
    //language
    const [tabs, updateTabs] = useState<Array<DescriptionTab>>([]);
    const [selectedTab, setSelectedTab] = useState<string | null>(null);
    const [selectedDescription, setSelectedDescription] = useState<number | null>(null);

    useEffect(() => {
		const descriptionInUserLanguage = props.descriptions.find(q => q.language.id == props.userLanguageId && q.isOriginal) ??
        props.descriptions.find(q => q.language.id == props.userLanguageId);
        const mainTabDescription = descriptionInUserLanguage ?? props.descriptions.find(q => q.isOriginal) ?? props.descriptions?.[0];
        const anotherDescriptions = props.descriptions.filter(q => q != mainTabDescription);
		const tabs = [
			{
				tabName: 'Описание',
				enabled: mainTabDescription != null,
                descriptions: mainTabDescription != undefined && mainTabDescription != null
                    ? [ { order: null, shortName: '', description: mainTabDescription, } as DescriptionItem ]
                    : [],
			} as DescriptionTab,
			{
				tabName: 'Другие описания',
				enabled: anotherDescriptions.length > 0,
				descriptions: anotherDescriptions.map((item, index) => (
                    {
                        order: index,
                        shortName: `${index + 1}. [${item.language.codeIso3}] ${TruncateString(item.value, 20)}`,
                        description: item,
                    } as DescriptionItem
                )),
			} as DescriptionTab,
		];

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

    
	const OnTabSelected = (tabName: string) =>{
		if (selectedTab == tabName) return;
        else{
            setSelectedTab(tabName);
            setSelectedDescription(0);
        }
	};
    
	const OnDescriptionSelected = (descriptionOrder: number) =>{
		if (selectedDescription == descriptionOrder) return;
        else setSelectedDescription(descriptionOrder);
	};

    return (
        <div className='card p-0'>
            <div className='card-header'>
                <ul className="nav nav-underline">
                    <li className='user-select-none nav-item' >
                        <a className={NavLinkClasses(tabs, selectedTab, 'Описание')} onClick={() => OnTabSelected('Описание')}>Описание</a>
                    </li>
                    <li className='user-select-none nav-item' >
                        <a className={NavLinkClasses(tabs, selectedTab, 'Другие описания')} onClick={() => OnTabSelected('Другие описания')} >Другие описания</a>
                    </li>
                </ul>

            </div>
            {selectedTab != undefined && selectedTab != null &&

                <div className='card-body'>

                    {selectedTab == 'Описание' && ContainsAnyDescriptions(tabs, 'Описание')  &&
                        <div className='overflow-x-hidden overflow-y-auto m-0' style={{height:'20rem'}}>
                            {
                                ShowDescription(tabs.find(q => q.tabName == selectedTab)?.descriptions[0])
                            }
                        </div>
                    }

                    {selectedTab == 'Другие описания' && ContainsAnyDescriptions(tabs, 'Другие описания')  &&
                        <div className="row mx-0">
                            <div className="col-4 ps-0">
                                <div id="list-example" className="list-group">
                                    {props.descriptions &&
                                        React.Children.toArray(
                                            tabs.find(q => q.tabName == selectedTab)?.descriptions.sort((a, b) => Number(a.description.isOriginal) - Number(b.description.isOriginal))
                                                .map((item) => 
                                                    <span className={'user-select-none list-group-item list-group-item-action' + (selectedDescription == item.order ? ' active' : '')}
                                                        onClick={() => OnDescriptionSelected(item.order ?? 0)}>
                                                            {(item.order ?? 0) + 1}. [{item.description.language.codeIso3}] {TruncateString(item.description.value, 20)}
                                                    </span>
                                                )
                                        )
                                    }
                                </div>
                            </div>
                            <div className="col-8 ps-0 overflow-x-hidden overflow-y-auto" style={{height:'20rem'}}>
                                { ShowDescription(tabs.find(q => q.tabName == selectedTab)?.descriptions.find(q => q.order == selectedDescription)) }
                            </div>
                        </div>
                    }

                </div>

            }
        </div>
    )
}

function ShowDescription(item: DescriptionItem | undefined){
    if (item == undefined) return (<></>);
    return (
        <>
            {item.order != null &&
                <h4 id={item.description.language.id}>Описание {item.order + 1}</h4>
            }
            <span>{item.description.value}</span>
        </>
    );
}

function ContainsAnyDescriptions(tabs: Array<DescriptionTab>, selectedTab: string | null){
    return tabs.find(q => q.tabName == selectedTab && q.descriptions.length > 0) != null;
}

function NavLinkClasses(tabs: Array<DescriptionTab>, selectedTab: string | null, tabName: string | null){
    return 'nav-link' + (selectedTab == tabName ? ' active' : '') + (!ContainsAnyDescriptions(tabs, tabName) ? ' disabled' : '');
}