import { FunctionalComponent, h, Fragment } from "preact";
import { Project } from "../../models/project";
import { ProjectReducerActions, updateParam } from "../../hooks/use-project-reducer";
import { getRoundUpEstimations, getCurrency, getTimeUnit } from "../../models/params";
import TaskCategoriesTable from "./task-categories-table";

export interface ParamsTabProps {
    project: Project
    dispatch: (action: ProjectReducerActions) => void
}

const ParamsTab: FunctionalComponent<ParamsTabProps> = ({ project, dispatch }) => {
    const onRoundUpChange = (evt: Event) => {
        const checked = (evt.currentTarget as HTMLInputElement).checked;
        dispatch(updateParam("roundUpEstimations", checked));
    };

    const onCurrencyChange = (evt: Event) => {
        const value = (evt.currentTarget as HTMLInputElement).value;
        dispatch(updateParam("currency", value));
    };

    const timeUnit = getTimeUnit(project);

    const onTimeUnitLabelChange = (evt: Event) => {
        const value = (evt.currentTarget as HTMLInputElement).value;
        dispatch(updateParam("timeUnit", { ...timeUnit, label: value }));
    };

    const onTimeUnitAcronymChange = (evt: Event) => {
        const value = (evt.currentTarget as HTMLInputElement).value;
        dispatch(updateParam("timeUnit", { ...timeUnit, acronym: value }));
    };

    return (
        <Fragment>
            <div class="field">
                <input type="checkbox"
                    id="roundUpEstimations"
                    name="roundUpEstimations" 
                    class="switch"
                    onChange={onRoundUpChange}
                    checked={getRoundUpEstimations(project)} />
                <label for="roundUpEstimations">Arrondir les estimations de temps à l'entier supérieur</label>
            </div>
            <hr />
            <div class="field">
                <label class="label">Unité de temps</label>
                <div class="control">
                    <input class="input" type="text"
                        onChange={onTimeUnitLabelChange}
                        value={timeUnit.label} />
                </div>
                <label class="label">Acronyme</label>
                <div class="control">
                    <input class="input" type="text"
                        onChange={onTimeUnitAcronymChange}
                        value={timeUnit.acronym} />
                </div>
            </div>
            <hr />
            <div class="field">
                <label class="label">Devise</label>
                <div class="control">
                    <input class="input" type="text"
                        onChange={onCurrencyChange}
                        value={getCurrency(project)} />
                </div>
            </div>
            <hr />
            <TaskCategoriesTable project={project} dispatch={dispatch} />
        </Fragment>
    );
};

export default ParamsTab;
