import {
    Button,
    FormControl,
    FormErrorMessage,
    FormLabel,
    Input,
    Modal,
    ModalBody,
    ModalCloseButton,
    ModalContent,
    ModalFooter,
    ModalHeader,
    ModalOverlay,
} from "@chakra-ui/react"
import {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,  SchedulePublic, ScheduleUpdate, secheduleService } from "../../client"
import useCustomToast from "../../hooks/useCustomToast"
import { handleError } from "../../utils"
import moment from "moment";

interface EditItemProps {
    sechedule: SchedulePublic
    isOpen: boolean
    onClose: () => void
    type: string
}

const EditSechedule = ({ sechedule, isOpen, onClose }: EditItemProps) => {
    const queryClient = useQueryClient()
    const showToast = useCustomToast()
    const {
        register,
        handleSubmit,
        reset,
        setValue,
        getValues,
        formState: { isSubmitting, errors },
    } = useForm<ScheduleUpdate>({
        mode: "onBlur",
        criteriaMode: "all",
        defaultValues: {
            date: sechedule.date,
            title: sechedule.title,
            info1: sechedule.info1,
            info2: sechedule.info2,
        },
    })

    const [datetime, setDatetime] = useState<string>(sechedule.date);

    const mutation = useMutation({
        mutationFn: (data: ScheduleUpdate) =>
            secheduleService.updateSechedule({ id: sechedule.id, requestBody: data }),
        onSuccess: (data) => {
            showToast("Success!", "Sechedule edit successfully.", "success")
            console.log(data)
            reset()
            onClose()
        },
        onError: (err: ApiError) => {
            handleError(err, showToast)
        },
        onSettled: () => {
            queryClient.invalidateQueries({ queryKey: ["course"] })
        },
    })

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

    return (
        <>
            <Modal
                isOpen={isOpen}
                onClose={onClose}
                size={{ base: "sm", md: "md" }}
                isCentered
            >
                <ModalOverlay />
                <ModalContent as="form" onSubmit={handleSubmit(onSubmit)}>
                    <ModalHeader>Edit Sechedule</ModalHeader>
                    <ModalCloseButton />
                    <ModalBody pb={6}>
                        <DateTimePicker onChange={(newDatetime: Date | null) => {
                            if (newDatetime instanceof Date) {
                                const formattedDate = moment.utc(newDatetime).format()
                                setDatetime(formattedDate)
                                setValue("date", formattedDate)
                            }
                        }} value={moment.utc(datetime).toDate()} />
                        <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 EditSechedule
