import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { useSpacing } from "@/styles";
import { Field, Form, Formik } from "formik";
import { Button, Dialog, DialogActions, DialogContent, DialogProps, DialogTitle, Typography } from "@material-ui/core";
import { CKEditorField } from "@/field/ckeditor";
import { Actions } from "@/components/actions";
import { Cancel, Send } from "mdi-material-ui";
import { createPortal } from "react-dom";
import { capitalize } from "@/helpers";

export type ContactFormValues = {
    content: string;
}

const initialContactFormValues: ContactFormValues = {
    content: "",
}

export type ContactDialogProps = {
    onSend: (values: ContactFormValues) => void;
} & DialogProps;

export function ContactForm() {
    const { t } = useTranslation();
    const spacing = useSpacing(2);

    return <div className={ spacing.vertical } style={{ overflow: 'hidden' }}>
        <Field label={ t("forms.contact.field.content") } name="content" component={ CKEditorField }/>
    </div>
}

export function ContactDialog({ onSend, ...props }: ContactDialogProps) {
    const spacing = useSpacing(2);
    const { t } = useTranslation();

    return <Dialog { ...props } maxWidth="lg">
        <Formik initialValues={ initialContactFormValues } onSubmit={ onSend }>
            <Form className={ spacing.vertical }>
                <DialogTitle>{ capitalize(t("forms.contact.title")) }</DialogTitle>
                <DialogContent>
                    <ContactForm />
                </DialogContent>
                <DialogActions>
                    <Actions>
                        <Button variant="contained" color="primary" startIcon={ <Send /> } type="submit">{ t("send") }</Button>
                        <Button startIcon={ <Cancel /> } onClick={ ev => props.onClose?.(ev, "escapeKeyDown") }>{ t("cancel") }</Button>
                    </Actions>
                </DialogActions>
            </Form>
        </Formik>
    </Dialog>
}

export type ContactActionProps = {
    children: (props: { action: () => void }) => React.ReactNode
};

export function ContactAction({ children }: ContactActionProps) {
    const [open, setOpen] = useState<boolean>(false);

    const handleClose = () => { setOpen(false) };
    const handleSubmit = (values: ContactFormValues) => {
        setOpen(false);
    }

    return <>
        { children({ action: () => setOpen(true) }) }
        { createPortal(
            <ContactDialog open={ open } onSend={ handleSubmit } onClose={ handleClose }/>,
            document.getElementById("modals") as HTMLElement
        ) }
    </>
}
