import { FunctionalComponent, h } from "preact";
import { useEffect } from "preact/hooks";
import style from "./style.module.css";
import { newProject } from "../../models/project";
import { useProjectReducer, updateProjectLabel } from "../../hooks/use-project-reducer";
import { getProjectStorageKey } from "../../util/storage";
import { useLocalStorage } from "../../hooks/use-local-storage";
import EditableText from "../../components/editable-text";
import Tabs from "../../components/tabs";
import EstimationTab from "./estimation-tab";
import ParamsTab from "./params-tab";

export interface ProjectProps {
    projectId: string
}

const Project: FunctionalComponent<ProjectProps> = ({ projectId }) => {
    const projectStorageKey = getProjectStorageKey(projectId);
    const [ storedProject, storeProject ] = useLocalStorage(projectStorageKey, newProject(projectId));
    const [ project, dispatch ] = useProjectReducer(storedProject);

    const onProjectLabelChange = (projectLabel: string) => {
        dispatch(updateProjectLabel(projectLabel));
    };

    // Save project in local storage on change
    useEffect(()=> {
        storeProject(project);
    }, [project]);

    return (
        <div class={`container ${style.estimation}`}>
            <EditableText
                editIconClass="is-size-4"
                render={(value) => (<h2 class="is-size-3">{value}</h2>)}
                onChange={onProjectLabelChange}
                value={project.label ? project.label : "Projet sans nom"} />
            <div class={style.tabContainer}>
                <Tabs items={[
                        {
                            label: 'Estimation',
                            icon: '📋',
                            render: () => <EstimationTab project={project} dispatch={dispatch} />
                        },
                        {
                            label: 'Paramètres',
                            icon: '⚙️',
                            render: () => <ParamsTab project={project} dispatch={dispatch} />
                        },
                        {
                            label: 'Exporter',
                            icon: '↗️',
                            render: () => null
                        }
                    ]}
                />
            </div>
        </div>
    );
};

export default Project;
