import { Button, Dialog, DialogActions, DialogContent, DialogProps, DialogTitle } from "@material-ui/core";
import React from "react";
import { Form, Formik } from "formik";
import { initialStaticPageFormValues, StaticPageForm, StaticPageFormValues, staticPageFormValuesTransformer } from "@/management/page/form";
import { Actions } from "@/components";
import { Save } from "@material-ui/icons";
import { useTranslation } from "react-i18next";
import { Cancel } from "mdi-material-ui";
import { useSpacing } from "@/styles";
import { initialCourseFormValues, CourseForm, CourseFormValues, courseFormValuesTransformer } from "@/management/course/form";
import { Course } from "@/data";

export type EditCourseDialogProps = {
    onSave?: (page: Course) => void;
    value?: Course;
} & DialogProps;

export function EditCourseDialog({ onSave, value, ...props }: EditCourseDialogProps) {
    const { t } = useTranslation("management");
    const spacing = useSpacing(3);

    const handleSubmit = (values: CourseFormValues) => {
        onSave?.(courseFormValuesTransformer.reverseTransform(values));
    };

    const initialValues = value
        ? courseFormValuesTransformer.transform(value)
        : initialCourseFormValues;

    return <Dialog { ...props } maxWidth="lg">
        <Formik initialValues={ initialValues } onSubmit={ handleSubmit }>
            <Form className={ spacing.vertical }>
                <DialogTitle>{ t(value ? "type.edit.title" : "type.create.title") }</DialogTitle>
                <DialogContent>
                    <CourseForm />
                </DialogContent>
                <DialogActions>
                    <Actions>
                        <Button variant="contained" color="primary" startIcon={ <Save /> } type="submit">{ t("save") }</Button>
                        <Button startIcon={ <Cancel /> } onClick={ ev => props.onClose?.(ev, "escapeKeyDown") }>{ t("cancel") }</Button>
                    </Actions>
                </DialogActions>
            </Form>
        </Formik>
    </Dialog>
}

