import {
  Box,
  Button,
  Drawer,
  DrawerBody,
  DrawerCloseButton,
  DrawerContent,
  DrawerFooter,
  DrawerHeader,
  DrawerOverlay,
  FormControl,
  FormErrorMessage,
  FormLabel,
  Image,
  Input,
  Stack,
  useToast,
} from "@chakra-ui/react";
import React, { useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import CustomAlertDialog from "../../Components/CustomAlertDialog";
import { useCreateKeyMeritsMutation } from "../../Services/io.service";
import * as yup from "yup";
import ToastBox from "../../Components/ToastBox";

const keyMeritsSchema = yup.object().shape({
  meritsHeader: yup.string().required("Title is required"),
  meritsDescription: yup.string().required("Sub title is required"),
  iconImage: yup.mixed().required("Icon is required"), // Adjust based on file or string
});

const KeyMeritsAdd = ({ isOpen, onClose, firstField, id }) => {
  const toast = useToast()
  const [alert, setAlert] = useState(false);
  const [createKeyMerits] = useCreateKeyMeritsMutation();
  const [isLoading, setIsLoading] = useState(false);
  const [file, setFile] = useState(null);

  const {
    control,
    reset,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(keyMeritsSchema),
    defaultValues: {
      meritsHeader: "",
      meritsDescription: "",
      iconImage: null,
    },
  });

  const onSubmit = async (data) => {
    setIsLoading(true);
    try {
      const formData = new FormData();
      formData.append("meritsHeader", data.meritsHeader);
      formData.append("meritsDescription", data.meritsDescription);
      if (data.iconImage && data.iconImage instanceof File) {
        formData.append("iconImage", data.iconImage);
        console.log(data.iconImage);
      }
      const res = await createKeyMerits({ data: formData, id });
      if (res?.data?.statusCode === 201) {
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });
        setAlert(false);
        onClose();
        setIsLoading(false);
        reset()
        return
      } 
      if(res?.error?.data?.code === 400){
        toast({
          render: () => <ToastBox message={res?.error?.data?.message} status={'error'} />,
        });
        setAlert(false);
        onClose();
        setIsLoading(false);
        reset()
        return
      }
    } catch (error) {
      if (error) {
        toast({
          render: () => <ToastBox message={"Something went wrong, please try again!"} status={'error'} />,
        });
      }
      setIsLoading(false);
      setAlert(false);
      onClose();
      reset()
    }
    reset()
  };

  const handleSave = () => {
    handleSubmit(onSubmit)();
  };


  const handleFileChange = (e) => {
    const file = e.target.files[0];
    console.log(file);
    if (file) {
      setFile(URL.createObjectURL(file));
    }
  };


  return (
    <>
      <Drawer
        isOpen={isOpen}
        placement="right"
        initialFocusRef={firstField} 
        onClose={onClose}
      >
        <DrawerOverlay />
        <DrawerContent>
          <DrawerCloseButton />
          <DrawerHeader fontSize={"sm"}>Key Merits</DrawerHeader>

          <DrawerBody>
            <Stack spacing={2}>
              <FormControl isInvalid={!!errors.meritsHeader} isRequired={true}>
                <FormLabel fontSize={"sm"}>Title</FormLabel>
                <Controller
                  name="meritsHeader"
                  control={control}
                  render={({ field }) => (
                    <Input {...field} fontSize={"sm"} type="text" size={"sm"} />
                  )}
                />
                <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                  {errors.meritsHeader?.message}
                </FormErrorMessage>
              </FormControl>
              <FormControl isInvalid={!!errors.meritsDescription} isRequired={true}>
                <FormLabel fontSize={"sm"}>Sub Title</FormLabel>
                <Controller
                  name="meritsDescription"
                  control={control}
                  render={({ field }) => (
                    <Input
                      {...field}
                      fontSize={"sm"}
                      type="textarea"
                      size={"sm"}
                    />
                  )}
                />
                <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                  {errors.meritsDescription?.message}
                </FormErrorMessage>
              </FormControl>
              <FormControl isInvalid={!!errors.iconImage} isRequired={true}>
                <FormLabel fontSize={"sm"}>Icon</FormLabel>
                <Controller
                  name="iconImage"
                  control={control}
                  render={({ field: { onChange, onBlur, value } }) => (
                    <Input
                      type="file"
                      className="form-control"
                      onChange={(e) => {
                        onChange(e.target.files[0]);
                        handleFileChange(e);
                      }}
                      onBlur={onBlur}
                      fontSize={"sm"}
                      size={"sm"}
                    />
                    
                  )}
                />
                {file && <Image w={8} h={8} p={1} bg={'#004118'} rounded={'md'} src={file} alt="Preview" mt={2} />}
                <FormErrorMessage fontSize={"xs"} fontWeight={500} >
                  {errors.iconImage?.message}
                </FormErrorMessage>
              </FormControl>
            </Stack>
          </DrawerBody>
          <DrawerFooter>
            <Button
              variant="outline"
              colorScheme={"green"}
              rounded={"sm"}
              size={"sm"}
              mr={3}
              onClick={onClose}
            >
              Cancel
            </Button>

            <Button
              colorScheme={"forestGreen"}
              rounded={"sm"}
              size={"sm"}
              onClick={() => setAlert(true)}
            >
              Save
            </Button>
          </DrawerFooter>
        </DrawerContent>
      </Drawer>
      <CustomAlertDialog
        isOpen={alert}
        onClose={() => setAlert(false)}
        alertHandler={handleSave}
        message={"Are you sure you want to add this key merit?"}
        isLoading={isLoading}
      />
    </>
  );
};

export default KeyMeritsAdd;
