import {
  Box,
  Button,
  Drawer,
  DrawerBody,
  DrawerCloseButton,
  DrawerContent,
  DrawerFooter,
  DrawerHeader,
  DrawerOverlay,
  FormControl,
  FormErrorMessage,
  FormLabel,
  HStack,
  Image,
  Input,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  Stack,
  Text,
  Textarea,
  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";
import { ChevronDownIcon } from "@chakra-ui/icons"; // Import ChevronDownIcon for the dropdown button

const keyMeritsSchema = yup.object().shape({
  meritsHeader: yup.string().required("Title is required"),
  meritsDescription: yup.string().required("Description is required"),
  meritsHeaderArabic: yup.string().required("Arabic title is required"),
  meritsDescriptionArabic: yup
    .string()
    .required("Arabic Description is required"),
  icon_xid: yup.string().required("Icon is required"), // Adjust based on file or string
});

const KeyMeritsAdd = ({ isOpen, onClose, firstField, id, icons }) => {
  const toast = useToast();
  const [formData, setFormData] = useState(null);
  const [alert, setAlert] = useState(false);
  const [createKeyMerits] = useCreateKeyMeritsMutation();
  const [isLoading, setIsLoading] = useState(false);
  const [file, setFile] = useState(null);
  const [selectedIcon, setSelectedIcon] = useState("Select Icon");
  const [selectedImageIcon, setSelectedImageIcon] = useState(null);

  const {
    control,
    reset,
    handleSubmit,
    setValue, // Add setValue to programmatically set the selected icon
    formState: { errors },
  } = useForm({
    resolver: yupResolver(keyMeritsSchema),
    defaultValues: {
      meritsHeader: "",
      meritsDescription: "",
      meritsHeaderArabic: "",
      meritsDescriptionArabic: "",
      icon_xid: "",
    },
  });

  const onSubmit = (data) => {
    if (Object.keys(errors).length === 0) {
      setFormData(data);
      setAlert(true);
    }
  };

  const handleConfirm = async () => {
    setIsLoading(true);
    try {
      const res = await createKeyMerits({ data: formData, id });
      console.log(res?.error?.status);
      
      if (res?.data?.statusCode === 201) {
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });
        handleClose()

        return;
      }
      if (res?.error?.status === 400 || res?.error?.status === 500 ) {
        toast({
          render: () => (
            <ToastBox message={res?.error?.data?.message} status={"error"} />
          ),
        });
        setIsLoading(false);
        setAlert(false);
        return;
      } 
    } catch (error) {
      if (error) {
        toast({
          render: () => (
            <ToastBox
              message={"Something went wrong, please try again!"}
              status={"error"}
            />
          ),
        });
      }
      setIsLoading(false);
      handleClose()
    }
    reset();
  };

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

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

  const handleIconSelect = (id, iconName, iconFilePath) => {
    setValue("icon_xid", id);
    setSelectedIcon(iconName); // Update selected icon name
    setSelectedImageIcon(iconFilePath);
  };

  const handleClose = () => {
    onClose();
    setIsLoading(false);
    setAlert(false);
    reset();
    setFile(null);
    setSelectedImageIcon(null);
    setSelectedIcon("Select Icon");
  };

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

          <DrawerBody>
            <HStack spacing={2} w={"100%"} flexWrap={"wrap"}>
              <FormControl
                w={"49%"}
                mb={2}
                isInvalid={!!errors.meritsHeader}
                isRequired={true}
              >
                <FormLabel fontSize={"sm"}>Title (English)</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
                w={"49%"}
                mb={2}
                isInvalid={!!errors.meritsHeaderArabic}
                isRequired={true}
              >
                <FormLabel fontSize={"sm"}>Title (Arabic)</FormLabel>
                <Controller
                  name="meritsHeaderArabic"
                  control={control}
                  render={({ field }) => (
                    <Input
                      textAlign={"right"}
                      {...field}
                      fontSize={"sm"}
                      type="text"
                      size={"sm"}
                    />
                  )}
                />
                <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                  {errors.meritsHeaderArabic?.message}
                </FormErrorMessage>
              </FormControl>

              <FormControl
                w={"49%"}
                mb={2}
                isInvalid={!!errors.meritsDescription}
                isRequired={true}
              >
                <FormLabel fontSize={"sm"}>Sub title</FormLabel>
                <Controller
                  name="meritsDescription"
                  control={control}
                  render={({ field }) => (
                    <Textarea
                      {...field}
                      fontSize={"sm"}
                      type="textarea"
                      size={"sm"}
                      rows={2}
                    />
                  )}
                />
                <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                  {errors.meritsDescription?.message}
                </FormErrorMessage>
              </FormControl>

              <FormControl
                w={"49%"}
                mb={2}
                isInvalid={!!errors.meritsDescriptionArabic}
                isRequired={true}
              >
                <FormLabel fontSize={"sm"}>Sub title (Arabic)</FormLabel>
                <Controller
                  name="meritsDescriptionArabic"
                  control={control}
                  render={({ field }) => (
                    <Textarea
                      {...field}
                      fontSize={"sm"}
                      type="textarea"
                      size={"sm"}
                      textAlign={"right"}
                      rows={2}
                    />
                  )}
                />
                <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                  {errors.meritsDescriptionArabic?.message}
                </FormErrorMessage>
              </FormControl>

              <FormControl
                w={"49%"}
                mb={2}
                isInvalid={!!errors.icon_xid}
                isRequired={true}
              >
                <FormLabel fontSize={"sm"}>Select Icon</FormLabel>
                <Controller
                  name="icon_xid"
                  control={control}
                  render={({ field }) => (
                    <Menu>
                      <MenuButton
                        h={34}
                        bg={"transparent"}
                        className="border"
                        size={"sm"}
                        fontWeight={500}
                        rounded={"sm"}
                        w={"100%"}
                        textAlign={"left"}
                        as={Button}
                        rightIcon={<ChevronDownIcon />}
                        border={
                          !errors.icon_xid?.message ||
                          (!selectedImageIcon && "2px solid #e53e3e")
                        }
                      >
                        <Box display="flex" alignItems="center">
                          {selectedImageIcon && <Image
                            src={`${import.meta.env.VITE_IMAGE_URL}${selectedImageIcon}`}
                            alt={selectedImageIcon}
                            boxSize="1rem"
                            mr="12px"
                          />}{" "}
                          <Text as={"span"} fontSize={"sm"} fontWeight={500}>
                            {selectedIcon}
                          </Text>
                        </Box>
                      </MenuButton>
                      <MenuList overflow={'scroll'} minW="415px" size={"sm"} fontWeight={500}>
                        {icons?.map(({ iconName, id, iconFilePath }) => (
                          <MenuItem
                            key={id}
                            onClick={() =>
                              handleIconSelect(id, iconName, iconFilePath)
                            }
                          >
                            <Box display="flex" alignItems="center">
                              <Image
                                src={`${import.meta.env.VITE_IMAGE_URL}${iconFilePath}`}
                                alt={iconName}
                                boxSize="1rem"
                                mr="12px"
                              />
                              <Text
                                as={"span"}
                                fontSize={"sm"}
                                fontWeight={500}
                              >
                                {iconName}
                              </Text>
                            </Box>
                          </MenuItem>
                        ))}
                      </MenuList>
                    </Menu>
                  )}
                />
                <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                  {!errors.icon_xid?.message ||
                    (!selectedImageIcon && errors.icon_xid?.message)}
                </FormErrorMessage>
              </FormControl>
            </HStack>
          </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={handleSave}
            >
              Save
            </Button>
          </DrawerFooter>
        </DrawerContent>
      </Drawer>
      <CustomAlertDialog
        isOpen={alert}
        onClose={handleClose}
        // alertHandler={handleSave}
        alertHandler={handleConfirm}
        message={"Are you sure you want to add this key merits?"}
        isLoading={isLoading}
      />
    </>
  );
};

export default KeyMeritsAdd;
