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, { useEffect, useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import CustomAlertDialog from "../../Components/CustomAlertDialog";
import * as yup from "yup";
import ToastBox from "../../Components/ToastBox";
import { useUpdateKeyMeritsMutation } from "../../Services/io.service";
import { ChevronDownIcon } from "@chakra-ui/icons";

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

const KeyMeritsEdit = ({
  isOpen,
  onClose,
  firstField,
  id,
  actionId,
  data,
  icons,
}) => {
  const toast = useToast();
  const [alert, setAlert] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [editKeyMerits] = useUpdateKeyMeritsMutation();
  const [selectedIcon, setSelectedIcon] = useState("Select Icon");
  const [selectedImageIcon, setSelectedImageIcon] = useState(null);

  const found = data?.find((item) => item?.id === actionId);
  console.log(found);
  

  const {
    control,
    reset,
    setValue,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(keyMeritsSchema),
  });
  // useEffect to reset the form when `found` changes
  useEffect(() => {
    setValue("icon_xid", found?.icon?.id);
    setSelectedIcon(found?.icon?.iconName); // Update selected icon name
    setSelectedImageIcon(found?.icon?.iconFilePath);
    if (found) {
      reset({
        meritsHeader: found?.meritsHeader,
        meritsDescription: found?.meritsDescription,
        meritsHeaderArabic: found?.meritsHeaderArabic,
        meritsDescriptionArabic: found?.meritsDescriptionArabic,
        icon_xid: found?.icon_xid,
      });
      console.log("==============",found);
      
    }
  }, [found, reset]);

  const onSubmit = async (data) => {
    console.log(data);
    
    setIsLoading(true);
    try {
      const id = actionId;
      const res = await editKeyMerits({ data, id });
      if (res?.data?.statusCode === 201) {
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });
        handleClose()
        reset({
          meritsHeader: "",
        });
        return;
      }
      if (res?.error?.data?.code === 400) {
        toast({
          render: () => (
            <ToastBox message={res?.error?.data?.message} status={"error"} />
          ),
        });
        handleClose()
        reset();
        return;
      }
    } catch (error) {
      if (error) {
        console.log(error);
        toast({
          render: () => (
            <ToastBox
              message={"Something went wrong, please try again!"}
              status={"error"}
            />
          ),
        });
      }
      handleClose()
    }
    reset();
  };

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


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

  const handleClose = () => {
    setIsLoading(false);
    setAlert(false);
    onClose();
    reset();

  }

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

          <DrawerBody>
            <HStack spacing={2} w={"100%"} flexWrap={"wrap"}>
              <FormControl
                mb={2}
                w={"49%"}
                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
                mb={2}
                w={"49%"}
                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="textarea"
                      size={"sm"}
                    />
                  )}
                />
                <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                  {errors.meritsHeaderArabic?.message}
                </FormErrorMessage>
              </FormControl>

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

              <FormControl
                w={"49%"}
                isInvalid={!!errors.icon_xid}
                isRequired={true}
              >
                <FormLabel fontSize={"sm"}>Select Icon</FormLabel>
                <Controller
                  name="icon_xid"
                  control={control}
                  render={({ field }) => (
                    <Menu>
                      <MenuButton
                        h={34}
                        className="border"
                        bg="transparent"
                        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 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)}
                  {errors.icon_xid?.message && 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={"green"}
              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 update this key merits?"}
        isLoading={isLoading}
      />
    </>
  );
};

export default KeyMeritsEdit;
