import {
    Button,
    FormControl,
    FormErrorMessage,
    FormLabel,
    Input,
    Modal,
    ModalBody,
    ModalCloseButton,
    ModalContent,
    ModalFooter,
    ModalHeader,
    ModalOverlay,
} from "@chakra-ui/react"
import { useEffect, useState } from "react"
import { useMutation, useQueryClient } from "@tanstack/react-query"
import { type SubmitHandler, useForm } from "react-hook-form"
import DateTimePicker from 'react-datetime-picker';
import 'react-calendar/dist/Calendar.css';
import { type ApiError, type ScheduleCreate, secheduleService } from "../../client"
import useCustomToast from "../../hooks/useCustomToast"
import { handleError } from "../../utils"
import moment from "moment";

interface AddSecheduleProps {
    isOpen: boolean
    onClose: () => void
    courseId: string
}

const AddSechedule = ({ isOpen, onClose, courseId }: AddSecheduleProps) => {
    const queryClient = useQueryClient()
    const showToast = useCustomToast()
    const {
        register,
        handleSubmit,
        reset,
        setValue,
        getValues,
        formState: { errors, isSubmitting },
    } = useForm<ScheduleCreate>({
        mode: "onBlur",
        criteriaMode: "all",
        defaultValues: {
            date: "",
            title: "",
            info1: "",
            info2: "",
            course_id: courseId,
        },
    })

    useEffect(() => {
        setValue("course_id", courseId);
        setValue("date", moment.utc(new Date()).format());
    }, [setValue, courseId]);

    const [datetime, setDatetime] = useState<Date>(new Date());

    const mutation = useMutation({
        mutationFn: (data: ScheduleCreate) =>
            secheduleService.createSechedule({ requestBody: data }),
        onSuccess: (data) => {
            showToast("Success!", "Sechedule created successfully.", "success")
            console.log(data)
            reset(
            {
                    date: moment.utc(new Date()).format(),
                    title: "",
                    info1: "",
                    info2: "",
                    course_id: courseId,
                }
            )
            onClose()
        },
        onError: (err: ApiError) => {
            handleError(err, showToast)
        },
        onSettled: () => {
            queryClient.invalidateQueries({ queryKey: ["course"] })
        },
    })

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

    return (
        <>
            <Modal
                isOpen={isOpen}
                onClose={onClose}
                size={{ base: "sm", md: "md" }}
                isCentered
            >
                <ModalOverlay />
                <ModalContent as="form" onSubmit={handleSubmit(onSubmit)}>
                    <ModalHeader>Add Sechedule</ModalHeader>
                    <ModalCloseButton />
                    <ModalBody pb={6}>
                        <DateTimePicker onChange={(newDatetime: Date | null) => {
                            if (newDatetime instanceof Date) {
                                setDatetime(newDatetime)
                                setValue("date", moment.utc(newDatetime).format())
                            }
                        }} value={datetime} />
                        <FormControl isRequired isInvalid={!!errors.title}>
                            <FormLabel htmlFor="title">Title</FormLabel>
                            <Input
                                id="title"
                                {...register("title", {
                                    required: "Title is required.",
                                })}
                                placeholder="Title"
                                type="text"
                            />
                            {errors.title && (
                                <FormErrorMessage>{errors.title.message}</FormErrorMessage>
                            )}
                        </FormControl>
                        <FormControl mt={4}>
                            <FormLabel htmlFor="info1">Info 1</FormLabel>
                            <Input
                                id="description"
                                {...register("info1")}
                                placeholder="info1"
                                type="text"
                            />
                        </FormControl>
                        <FormControl mt={4}>
                            <FormLabel htmlFor="info2">Info 2</FormLabel>
                            <Input
                                id="description"
                                {...register("info2")}
                                placeholder="info2"
                                type="text"
                            />
                        </FormControl>

                    </ModalBody>

                    <ModalFooter gap={3}>
                        <Button onClick={() => {
                            const values = getValues()
                            console.log(values)
                        }}>
                            test
                        </Button>
                        <Button variant="primary" type="submit" isLoading={isSubmitting}>
                            Save
                        </Button>
                        <Button onClick={onClose}>Cancel</Button>
                    </ModalFooter>
                </ModalContent>
            </Modal>
        </>
    )
}
export default AddSechedule
