import React, {useEffect, useState} from 'react'
import {EpisodeShort} from "../../../../api/models/Types.tsx";
import ErrorInput from "../../../common/error/ErrorInput.tsx";
import {UserInfo} from "../../../../api/models/AccountTypes.tsx";
import {GetTitleNames} from "../../../common/view/NameComponent.tsx";

export interface IAnimeSeasonVariantSelectComponentProps {
    Episodes?: Array<EpisodeShort> | null | undefined,
    user: UserInfo | null | undefined,
    order?: number | null | undefined,
    number?: number | null | undefined,
    OnEpisodeSelected?: (episodeOrder: number | null, episodeNumber: number | null) => void,
}

export default function AnimeSeasonVariantSelectComponent(props: IAnimeSeasonVariantSelectComponentProps) {
	const [episodeVariantOrder, setEpisodeVariantOrder] = useState<number | null>(null);
	const [number, setNumber] = useState<number | null>(null);
	const [defaultEpisodeNumber, setDefaultEpisodeNumber] = useState<number>(0);

    const selectEpisode = (value?: string | null | undefined) => {
        console.log('aa');
        const parsed = Number.parseInt(value ?? '');
        const order = !Number.isNaN(parsed) ? parsed : null;
        const defaultNumber = GetDefaultEpisodeNumber(order, props.Episodes ?? []);
        if (defaultNumber != defaultEpisodeNumber){
            setDefaultEpisodeNumber(defaultNumber);
            setNumber(null);
        }
        setEpisodeVariantOrder(order);
        props.OnEpisodeSelected?.(order, number);
    };
    
    useEffect(() => {
        setEpisodeVariantOrder(props.order ?? null);
        const defaultNumber = GetDefaultEpisodeNumber(props.order ?? null, props.Episodes ?? []);
        setNumber(props.number ?? null);
        setDefaultEpisodeNumber(defaultNumber);
    }, []);
    
    if (props.Episodes == null || props.Episodes.length === 0) {
        return (<> </>);
    }

    return (
        <div className='card bg-body-tertiary p-0'>
            <div className='card-body'>

                <div className='row'>
                    <div className='col-10'>
                        <ErrorInput error={''}>
                            <div className="input-group input-group-sm">
                                <span className="input-group-text">Вариант эпизода</span>
                                <ErrorInput error={''}>
                                    <select className="form-select" aria-label="Язык описания" value={episodeVariantOrder ?? ''}
                                            disabled={props.Episodes.length == 0}
                                            onChange={(event) => selectEpisode(event.target.value)}>
                                        {/*<option value={''} >Выберите эпизод</option>*/}
                                        <option value={''}>
                                            {ShowEpisodeShort()}
                                        </option>
                                        {
                                            // React.Children.toArray(
                                            //     languagesData.map((item) =>
                                            //         <option value={item.id}>
                                            //             {item.name} [{item.codeIso3}]
                                            //         </option>
                                            //     ))

                                            React.Children.toArray(
                                                props.Episodes.map((item: EpisodeShort) => {
                                                    return (
                                                        <option value={item.order}>
                                                            {ShowEpisodeShort(item, props.user?.languageId)}
                                                        </option>
                                                    )
                                                })
                                            )
                                        }
                                        {/* <option value="2">Два</option> */}
                                    </select>
                                </ErrorInput>
                            </div>
                        </ErrorInput>
                    </div>
                    <div className='col'>
                        <ErrorInput error={''}>
                            <div className="input-group input-group-sm">
                                <span className="input-group-text">Номер</span>
                                <ErrorInput error={''}>
                                    <input className="form-control form-control-sm" type="number" id="episodeNumber" name="episodeNumber" min="0"
                                           placeholder={GetDefaultEpisodeNumber(episodeVariantOrder, props.Episodes ?? []).toString()}
                                           value={number?.toString() ?? ''}
                                           onChange={(e) => {
                                               var value = Number.parseFloat(e.target.value);
                                               setNumber(!isNaN(value) ? value : null);
                                               props.OnEpisodeSelected?.(episodeVariantOrder, number);
                                           }}
                                        // onKeyDown={(e) => {
                                        //     if (IsDeleteKeyPressed(e)) {
                                        //         setNumber(null);
                                        //     }
                                        // }}
                                    />
                                </ErrorInput>
                            </div>
                        </ErrorInput>
                    </div>
                </div>

            </div>
        </div>
    )
}


// function ShowDuration(ticks: number | null | undefined) {
//     const timespan = TimespanFromTicks(ticks);
//     return (
//         <>
//             {TimePartToStringWith(timespan?.hours)}:{TimePartToStringWith(timespan?.minutes)}:{TimePartToStringWith(timespan?.seconds)}
//         </>
//     )
// }

//extract to component
// function TimePartToStringWith(number: number | null | undefined): string {
//
//     return number?.toString().padStart(2, '0') ?? '--';
// }

//extract to component
// function Date(date: string | null | undefined) {
//     return date != null ? DateToString(GetDate(date)) : '—//—';
// }

function GetDefaultEpisodeNumber(order: number | null, episodes: Array<EpisodeShort>) : number {
    const selectedEpisodeNumbers = (order == null ? episodes : episodes.filter(q => q.order == order))
        .map(q => q.number);    
    return (selectedEpisodeNumbers.length == 0 ? 0 : Math.max(...selectedEpisodeNumbers)) + 1;
}

function ShowEpisodeShort(episode?: EpisodeShort | null, languageId?: string | null) {
    if (episode == null){
        return (
            <>-- // --</>
        );
    }
    return(
        <>
            Эпизод {episode.number}. {episode.names.length > 0 && GetTitleNames(episode.names, languageId, true)?.titleElement} || {episode.order} | {episode.number} 
        </>
        // <div className='row mb-2 border rounded py-2 bg-body-secondary'>
        //     {item.preview != null &&
        //         <div className='col-1'>
        //             <MediaInfoComponent
        //                 mediaInfo={item.preview?.url == null ? null : {
        //                     type: item.preview.type,
        //                     data: item.preview.url,
        //                 } as MediaInfoModel}
        //                 classes={'card-img-top rounded-3 border border-5 border-secondary'}
        //             />
        //
        //         </div>
        //     }
        //     <div className="col">
        //         <div className="row justify-content-between">
        //             <div className='col-auto align-self-center'>
        //                 <h4 className='text-primary m-0' role='button'>
        //                     {/*{isSeason ? 'Сезон' : 'Эпизод'} {animeItem.number} ({animeItem.order}).*/}
        //                     {/*{isSeason ? 'Сезон' : 'Эпизод'} {props.animeItem.number}{(props.animeItem.variant != null ? `(${props.animeItem.variant})` : '')}. {props.animeItem.commonProperties.names.length > 0 && <>{name}</>}*/}
        //                     Эпизод {item.number}. {item.names.length > 0 && <>{GetTitleNames(item.names, props.user?.languageId, true)?.titleElement}</>}
        //                 </h4>
        //             </div>
        //         </div>
        //         <div className="row">
        //             <div className='card p-0 mt-2'>
        //                 <div className='card-body p-0'>
        //                     <div className='table-responsive'>
        //                         <table className="table m-0">
        //                             <tbody>
        //                             <>
        //                                 <tr>
        //                                     <th>Дата выхода</th>
        //                                     <td className='text-end'>
        //                                         {Date(item.releaseDate)}
        //                                     </td>
        //                                 </tr>
        //                                 <tr>
        //                                     <th>Длительность:</th>
        //                                     <td className='text-end'>
        //                                         {ShowDuration(item?.durationTicks)}
        //                                     </td>
        //                                 </tr>
        //                             </>
        //                             </tbody>
        //                         </table>
        //                     </div>
        //                 </div>
        //             </div>
        //         </div>
        //     </div>
        // </div>
    );
}