import React from "react";
import { Course } from "@/data";
import { Semester } from "@/data/student";
import { useTranslation } from "react-i18next";
import { useSpacing } from "@/styles";
import { Field, FieldProps } from "formik";
import { TextField as TextFieldFormik } from "formik-material-ui";
import { Checkbox, Grid } from "@material-ui/core";
import { identityTransformer, Transformer } from "@/serialization";

export type CourseFormValues = Omit<Course, 'id'>;

export const initialCourseFormValues: CourseFormValues = {
    name: "",
    desiredSemesters: []
}

export const courseFormValuesTransformer: Transformer<Course, CourseFormValues> = identityTransformer;

export const DesiredSemestersField = ({ field, form, meta, ...props }: FieldProps<Semester[]>) => {
    const { name, value = [] } = field;
    const { t } = useTranslation("management");

    const toggle = (sid: Semester) => () => {
        if (!value.includes(sid)) {
            form.setFieldValue(name, [...value, sid]);
        } else {
            form.setFieldValue(name, value.filter((a) => a != sid));
        }
    }
    const isChecked = (sid: Semester) => value.includes(sid);

    const desiredSemesterCheckboxes = [];
    for (var semesterId = 1; semesterId <= 10; semesterId++) {
        const sid = semesterId;

        desiredSemesterCheckboxes.push(
            <Grid item xs={3}>
                <Checkbox edge="start" onChange={ toggle(sid) } checked={ isChecked(sid) }/>
                { t("course.field.desiredSemester", {semesterId: semesterId})}
            </Grid>
        );
    }

    return <Grid container spacing={3}>
        { desiredSemesterCheckboxes }
    </Grid>
}

export function CourseForm() {
    const { t } = useTranslation("management");
    const spacing = useSpacing(2);

    return <div className={ spacing.vertical }>
        <Field label={ t("page.field.title") } name="name" fullWidth component={ TextFieldFormik }/>
        <Field name="desiredSemesters" component={ DesiredSemestersField } />
    </div>
}
