import {
    Button,
    FormControl,
    FormErrorMessage,
    FormLabel,
    Input,
    Textarea,
    Container
} from "@chakra-ui/react"
import {useQueryClient, useMutation } from "@tanstack/react-query"
import { createFileRoute } from "@tanstack/react-router"
import {useState } from "react"
import useCustomToast from "../../../hooks/useCustomToast"
import { CoursesService, type ApiError, CourseCreate, } from "../../../client"
import { handleError } from "../../../utils"
import { type SubmitHandler, useForm } from "react-hook-form"
import { EditorState, convertToRaw } from 'draft-js';
import { Editor } from "react-draft-wysiwyg";
import draftToHtml from 'draftjs-to-html';
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";


export const Route = createFileRoute("/_layout/Courses/AddCourse")({
    component: AddCourse,
})


function AddCourseForms() {

    const toolbar = {
        options: ['inline', 'blockType', 'fontSize', 'list', 'textAlign', 'history', 'embedded', 'emoji',],
        inline: { inDropdown: true },
        list: { inDropdown: true },
        textAlign: { inDropdown: true },
        link: { inDropdown: true },
        history: { inDropdown: true },
    }

    const showToast = useCustomToast()
    const queryClient = useQueryClient()

    const [contentEditorState, setContentEditorState] = useState<EditorState>(EditorState.createEmpty());
    const [contents, setContent] = useState<string>('');
    const [infoEditorState, setInfoEditorState] = useState<EditorState>(EditorState.createEmpty());
    const [info, setInfo] = useState<string>('');
    const [longDescriptionEditorState, setLongDescriptionEditorState] = useState<EditorState>(EditorState.createEmpty());
    const [longDescription, setlongDescription] = useState<string>('');
    const [remarksEditorState, setRemarksEditorState] = useState<EditorState>(EditorState.createEmpty());
    const [remarks, setRemarks] = useState<string>('');
    const {
        register,
        handleSubmit,
        setValue,
        formState: { isSubmitting, errors, isDirty },
    } = useForm<CourseCreate>({
        mode: "onBlur",
        criteriaMode: "all",
        defaultValues: {
            title: "",
            sort_description: "",
            long_description: "",
            information: "",
            contant: "",
            remark: "",
        }
    })

    const mutation = useMutation({
        mutationFn: (data: CourseCreate) =>
            CoursesService.createCourse({ requestBody: data }),
        onSuccess: () => {
            showToast("Success!", "Course create successfully.", "success")

        },
        onError: (err: ApiError) => {
            handleError(err, showToast)
        },
        onSettled: () => {
            queryClient.invalidateQueries({ queryKey: ["courses"] })
            history.go(-1)
        },
    })

    const onSubmit: SubmitHandler<CourseCreate> = async (data) => {
        mutation.mutate(data)
    }



    return (

        <Container maxW="full" mt="20" as="form" onSubmit={handleSubmit(onSubmit)}>

            <FormControl isInvalid={!!errors.title}>
                <FormLabel htmlFor="title">Title</FormLabel>
                <Input
                    id="address"
                    type="text"
                    {...register("title", {
                        required: "title is required",
                    })}

                />
                {errors.title && (
                    <FormErrorMessage>{errors.title.message}</FormErrorMessage>
                )}
            </FormControl>
            <FormControl mt={4}></FormControl>
            <FormControl >
                <FormLabel htmlFor="sort_description">Short Description</FormLabel>
                <Textarea
                    id="sort_description"
                    {...register("sort_description", {
                        required: "sort_description is required",
                    })}
                />

            </FormControl>
            <FormControl mt={4}></FormControl>
            <FormControl >
                <FormLabel htmlFor="long_description">Long Description</FormLabel>
                <Editor
                    editorState={longDescriptionEditorState}
                    wrapperClassName="wrapper-class"
                    editorClassName="demo-editor"
                    onEditorStateChange={newState => {
                        setLongDescriptionEditorState(newState);
                        setlongDescription(draftToHtml(convertToRaw(newState.getCurrentContent())));
                        setValue("long_description", longDescription);
                    }}
                    
                    toolbar={toolbar}
                />
            </FormControl>
            <FormControl mt={4}></FormControl>
            <FormControl >
                <FormLabel htmlFor="information">Information</FormLabel>
                <Editor
                    editorState={infoEditorState}
                    wrapperClassName="wrapper-class"
                    editorClassName="demo-editor"
                    onEditorStateChange={newState => {
                        setInfoEditorState(newState);
                        setInfo(draftToHtml(convertToRaw(newState.getCurrentContent())));
                        setValue("information", info);

                    }}
                    toolbar={toolbar}
                />
            </FormControl>
            <FormControl mt={4}></FormControl>
            <FormControl >
                <FormLabel htmlFor="contant">Content</FormLabel>
                <Editor
                    editorState={contentEditorState}
                    wrapperClassName="wrapper-class"
                    editorClassName="demo-editor"
                    onEditorStateChange={newState => {
                        setContentEditorState(newState);
                        setContent(draftToHtml(convertToRaw(newState.getCurrentContent())));
                        setValue("contant", contents);
                    }}
                    toolbar={toolbar}
                />

            </FormControl>
            <FormControl mt={4}></FormControl>
            <FormControl >
                <FormLabel htmlFor="remark">Remark</FormLabel>
                <Editor
                    editorState={remarksEditorState}
                    wrapperClassName="wrapper-class"
                    editorClassName="demo-editor"
                    onEditorStateChange={newState => {
                        setRemarksEditorState(newState);
                        setRemarks(draftToHtml(convertToRaw(newState.getCurrentContent())));
                        setValue("remark", remarks);

                    }}
                    toolbar={toolbar}
                />

            </FormControl>

            <FormControl mt={4}></FormControl>
            {/* <button
                type="button"
                onClick={() => {
                    const values = getValues()
                    console.log(values)
                   // history.go(-1)// { test: "test-input", test1: "test1-input" }
                }}
            >
                Get Values
            </button> */}
            <Button
                variant="primary"
                type="submit"
                isLoading={isSubmitting}
                isDisabled={!isDirty}

            >
                Save
            </Button>
            <FormControl mt={20}></FormControl>

        </Container>

    )


}


function AddCourse() {

    return (
        <Container maxW="full">

            <AddCourseForms />

        </Container>
    )
}
