import {
    Button,
    FormControl,
    FormErrorMessage,
    FormLabel,
    Container,
    Heading,
    Box,
    NumberInput,
    NumberInputField,
    NumberInputStepper,
    NumberIncrementStepper,
    NumberDecrementStepper,
    Image,
    HStack,
    VStack,
    Text,
    Grid
} from "@chakra-ui/react"
import { useQueryClient, useMutation } from "@tanstack/react-query"
import { useEffect } from "react"
import useCustomToast from "../../hooks/useCustomToast"
import { Info_imageService, type ApiError, CourseDetailsPublic, ImageCreate } from "../../client"
import { handleError } from "../../utils"
import { type SubmitHandler, useForm } from "react-hook-form"
import ActionsMenu from "../../components/Common/ActionsMenu"





const CourseInfoImages = () => {

    const queryClient = useQueryClient();
    const courseDetails = queryClient.getQueryData(['course']) as CourseDetailsPublic | undefined;
    //const url = import.meta.env.VITE_API_URL
    const showToast = useCustomToast()
    const {
        register,
        handleSubmit,
        reset,
        setValue,
        formState: { isSubmitting, errors, isDirty },
    } = useForm<ImageCreate>({
        mode: "onBlur",
        criteriaMode: "all",
        defaultValues: {
            course_id: '',
            image: undefined,
            index: 0,
        }
    })

    const mutation = useMutation({
        mutationFn: (data: ImageCreate) =>
            Info_imageService.createImage({ formData: data }),
        onSuccess: (data) => {
            showToast("Success!", "Image added successfully.", "success")
            console.log(data)
            queryClient.setQueryData(['course'], data)
            reset()
        },
        onError: (err: ApiError) => {
            handleError(err, showToast)
        },
        onSettled: () => {
            queryClient.invalidateQueries({ queryKey: ["courses"] })

        },
    })

    useEffect(() => {
        if (courseDetails) {
            setValue("course_id", courseDetails.id)
        }
    }, [courseDetails]);

    const onSubmit: SubmitHandler<ImageCreate> = async (data) => {
        if (data.image instanceof FileList && data.image.length > 0) {
            data.image = data.image[0]
        }
        if (courseDetails?.info_images && courseDetails.info_images.length >= 5) {
            showToast("Error!", "You can only add 5 images", "error")
            return
        } else {
            mutation.mutate(data)
        }
    }




    return (
        <Container maxW="full">
            <Box
                w={{ sm: "full", md: "50%" }}
                as="form"
                onSubmit={handleSubmit(onSubmit)}
            >
                <Box w="100%" maxW="full" overflowX="auto">
                    <VStack align="flex-start">
                        <HStack spacing={4} overflowX="auto">

                            {courseDetails?.info_images.map((image, index) => (
                                <Box width={200} height={200} >
                                    <Grid templateColumns='repeat(2, 1fr)' gap={1}>
                                        <Text >{image.index}</Text>
                                        <ActionsMenu type={"Info_Image"} value={image} />
                                    </Grid>

                                    <Image key={index} src={import.meta.env.VITE_IMAGE_URL + "/" + image.image} objectFit="cover" />

                                </Box>
                            ))}
                        </HStack>
                    </VStack>
                </Box>
                <Heading size="sm" py={4}>
                    Add Course Image
                </Heading>
                <FormControl mt={4}></FormControl>
                <FormControl isRequired isInvalid={!!errors.index}>
                    <FormLabel htmlFor="index">Index</FormLabel >
                    <NumberInput min={0} max={20}  >
                        <NumberInputField {...register("index", {
                            required: "index is required.",
                        })} />
                        <NumberInputStepper>
                            <NumberIncrementStepper />
                            <NumberDecrementStepper />
                        </NumberInputStepper>
                    </NumberInput>
                    {errors.index && (
                        <FormErrorMessage>{errors.index.message}</FormErrorMessage>
                    )}
                </FormControl>
                <FormControl mt={4}></FormControl>
                <FormControl isInvalid={!!errors.image} isRequired>
                    <FormLabel>{'Image Upload'}</FormLabel>
                    <input type="file" {...register("image", {
                        required: "index is required.",
                    })} />
                    <FormErrorMessage>
                        {errors.image && errors?.image.message}
                    </FormErrorMessage>
                </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>
            </Box>
        </Container >
    )
}
export default CourseInfoImages;