import React, {useState} from "react";
import {TfiTrash} from "react-icons/tfi";

export type Timespan = {
    hours: number,
    minutes: number,
    seconds: number,
}

export function TimespanFromTicks(ticks?: number | null) : Timespan | null{
    if (ticks == null) return null;
    const milliseconds = ticks / 10000;
    const hours = Math.floor(milliseconds / 3600000);
    const minutes = Math.floor((milliseconds % 3600000) / 60000);
    const seconds = Math.floor((milliseconds % 60000) / 1000);
    return { hours: hours, minutes: minutes, seconds: seconds } as Timespan;
}

export function TimespanToTicks(timespan?: Timespan | null) : number | null{
    if (timespan == null) return null;
    const milliseconds = (timespan.hours * 3600000) + (timespan.minutes * 60000) + (timespan.seconds * 1000);
    return milliseconds * 10000;
}
export interface ITimespanComponentProps{
    value?: Timespan | null,
    title?: string | null,
    onChange?: (value?: Timespan | null) => void,
}

export default function TimespanComponent(props: ITimespanComponentProps){

    const [hours, setHours] = useState<number | null>(null);
    const [seconds, setSeconds] = useState<number | null>(null);
    const [minutes, setMinutes] = useState<number | null>(null);

    React.useEffect(() => {
        if (props.value == null) {
            setHours(null);
            setMinutes(null);
            setSeconds(null);
        }
        else{
            setHours(props.value.hours);
            setMinutes(props.value.minutes);
            setSeconds(props.value.seconds);
        }
    }, [props]);
    
    return(
        <>
            <div className='input-group'>
                {(props.title != null && props.title.length > 0) &&
                    <span className="input-group-text">{props.title}</span>
                }
                <input className="form-control" type="number" id="hours" name="hours" min="0" placeholder="часы"
                       value={hours?.toString() ?? ''}
                       onChange={(e) => {
                           const hours = NumberTryParse(e.target.value);
                           setHours(hours ?? null);
                           props.onChange?.(HmsToTimespan(hours ?? null, minutes, seconds));
                       }}
                       onKeyDown={(e) => {
                           if (IsDeleteKeyPressed(e)) {
                               // setHours(null);
                               setHours(0);
                               props.onChange?.(HmsToTimespan(0, minutes, seconds));
                           }
                       }}
                />

                <input className="form-control" type="number" id="minutes" name="minutes" min="0" max="59"
                       placeholder="минуты" value={minutes?.toString() ?? ''}
                       onChange={(e) => {
                           const minutes = NumberTryParse(e.target.value);
                           if (minutes != null && (minutes < 0 || minutes > 59)) return;
                           setMinutes(minutes ?? null);
                           props.onChange?.(HmsToTimespan(hours, minutes ?? null, seconds));
                       }}
                       onKeyDown={(e) => {
                           if (IsDeleteKeyPressed(e)) {
                               // setMinutes(null);
                               setMinutes(0);
                               props.onChange?.(HmsToTimespan(hours, 0, seconds));
                           }
                       }}
                />

                <input className="form-control" type="number" id="seconds" name="seconds" min="0" max="59"
                       placeholder="секунды" value={seconds?.toString() ?? ''}
                       onChange={(e) => {
                           const seconds = NumberTryParse(e.target.value);
                           if (seconds != null && (seconds < 0 || seconds > 59)) return;
                           setSeconds(seconds ?? null);
                           props.onChange?.(HmsToTimespan(hours, minutes, seconds ?? null));
                       }}
                       onKeyDown={(e) => {
                           if (IsDeleteKeyPressed(e)) {
                               // setSeconds(null);
                               setSeconds(0);
                               props.onChange?.(HmsToTimespan(hours, minutes, 0));
                           }
                       }}
                />

                <div className="input-group-append">
                    <button type='button' className='btn btn-danger'
                            onClick={() => {
                                const timespan = HmsToTimespan(null, null, null);
                                setHours(timespan?.hours ?? null);
                                setMinutes(timespan?.minutes ?? null);
                                setSeconds(timespan?.seconds ?? null);
                                props.onChange?.(timespan);
                            }}>
                        <TfiTrash/>
                    </button>
                </div>
            </div>
        </>
    )
}

function HmsToTimespan(hours: number | null, minutes: number | null, seconds: number | null): Timespan | null {
    if (hours == undefined && minutes == undefined && seconds == undefined) return null;
    return {
        hours: hours ?? 0,
        minutes: minutes ?? 0,
        seconds: seconds ?? 0
    } as Timespan;
}

function NumberTryParse(stringValue: string | null | undefined) : number | null {
    const regex = /((\D+?\.\D*?|\d+?\.\D+?|\D+?\.\d+?|\d+\.|\D+\.)|(\D+?\,\D+?|\d+?\,\D+?|\D+?\,\d+?|\d+\,|\D+\,))$|[^\d.,]+/;
    if (stringValue == null || regex.test(stringValue) || stringValue.length == 0) return null;
    var returnValue = Number.parseFloat(stringValue);
    return !isNaN(returnValue) ? returnValue : null ;
}


function IsDeleteKeyPressed(e: React.KeyboardEvent<HTMLDivElement>) : boolean {
    return e.key == 'Delete';
}

// function IsBackspaceKeyPressed(e: React.KeyboardEvent<HTMLDivElement>) : boolean {
//     return e.key == 'Backspace';
// }

// function IsUpKeyPressed(e: React.KeyboardEvent<HTMLDivElement>) : boolean {
//     return e.key == 'Up';
// }

// function IsDownKeyPressed(e: React.KeyboardEvent<HTMLDivElement>) : boolean {
//     return e.key == 'Down';
// }