import { ChevronDownIcon } from "@chakra-ui/icons";
import React, { useEffect, useState } from "react";
import {
  Badge,
  Button,
  FormControl,
  FormLabel,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  FormErrorMessage,
} from "@chakra-ui/react";
import {
  useGetIOprepopulateDataQuery,
  useUpdateCancleStatusMutation,
  useUpdateCancleStatusToMutation,
  useUpdateStatusIoMutation,
} from "../../../../Services/io.service";
import { useParams } from "react-router-dom";

const UpdateIOStatus = ({ isOpen, onClose, status }) => {
  const params = useParams();
  const id = params?.id;
  const [selectedItem, setSelectedItem] = useState();
  const [isLoadingg, setIsLoading] = useState(false);
  const [error, setError] = useState("");
  const [selectedStatusId, setSelectedStatusId] = useState("");

  const { data } = useGetIOprepopulateDataQuery();
  const [updateStatusIo] = useUpdateStatusIoMutation();
  const [updateCancleStatus] = useUpdateCancleStatusToMutation();

  // useEffect(() => {
  //   setSelectedStatusId(status?.[0]?.id);
  // }, [status]);

  const handleMenuItemClick = (item, id) => {
    setSelectedItem(item);
    setSelectedStatusId(id);
  };

  const handleSubmit = async () => {
    if (!selectedStatusId) {
      setError("Please select status");
      return;
    }
    setError("");
    setIsLoading(true);
    try {
      let res;

      // If selectedItem is 'Cancelled', make the updateCancelStatus API call
      if (selectedItem === "Cancelled") {
        res = await updateCancleStatus({
          id
        });
      } 
      // Otherwise, make the updateStatusIo API call
      else {
        res = await updateStatusIo({
          data: {
            ioStatus_xid: selectedStatusId,
          },
          id,
        });
      }
  
      console.log("API Response:", res);
      setIsLoading(false);
      handleClose();
    } catch (error) {
      setIsLoading(false);
    }
  };

  const handleClose = () => {
    setSelectedItem(null);
    setSelectedStatusId(null);
    onClose();
    setError("");
  };

  return (
    <Modal isOpen={isOpen} onClose={handleClose}>
      <ModalOverlay />
      <ModalContent>
        <ModalHeader fontSize={"md"}>Update IO Status Transaction</ModalHeader>
        <ModalCloseButton />
        <ModalBody>
          <FormControl isInvalid={!!error}>
            <FormLabel as={"label"} fontSize={"sm"} fontWeight={500}>
              Status
            </FormLabel>
            <Menu>
              <MenuButton
                as={Button}
                rightIcon={<ChevronDownIcon />}
                fontSize={"sm"}
                fontWeight={500}
                w={"100%"}
                textAlign={"left"}
              >
                {selectedItem ? (
                  <Badge
                    rounded={"full"}
                    pt={1.5}
                    pb={1.5}
                    ps={4}
                    pe={4}
                    mt={1.5}
                    mb={1.5}
                    textTransform={"none"}
                    colorScheme={
                      selectedItem === "Draft"
                        ? "gray"
                        : selectedItem === "Processing"
                        ? "yellow"
                        : selectedItem === "Open"
                        ? "blue"
                        : selectedItem === "Closed"
                        ? "green"
                        : selectedItem === "Exited"
                        ? "red"
                        : selectedItem === "Cancelled"
                        ? "orange"
                        : "purple"
                    }
                    py={"3px"}
                    px={"8px"}
                  >
                    {selectedItem}
                  </Badge>
                ) : (
                  "Select Item"
                )}
              </MenuButton>

              {status?.length > 0 ? (
                <MenuList w={"400px"}>
                  {status?.map(({ id, statusAdmin }) => (
                    <MenuItem
                      key={id}
                      fontSize={"sm"}
                      onClick={() => handleMenuItemClick(statusAdmin, id)}
                    >
                      <Badge
                        rounded={"full"}
                        pt={1.5}
                        pb={1.5}
                        ps={4}
                        pe={4}
                        mt={1.5}
                        mb={1.5}
                        textTransform={"none"}
                        colorScheme={
                          statusAdmin === "Draft"
                            ? "gray"
                            : statusAdmin === "Processing"
                            ? "yellow"
                            : statusAdmin === "Open"
                            ? "blue"
                            : statusAdmin === "Closed"
                            ? "green"
                            : statusAdmin === "Exited"
                            ? "red"
                            : statusAdmin === "Cancelled"
                            ? "orange"
                            : "purple"
                        }
                        py={"1px"}
                        px={"8px"}
                      >
                        {statusAdmin}
                      </Badge>
                    </MenuItem>
                  ))}
                </MenuList>
              ) : (
                ""
              )}
            </Menu>
            <FormErrorMessage fontSize={"xs"} fontWeight={600}>
              {error}
            </FormErrorMessage>
          </FormControl>
        </ModalBody>
        <ModalFooter>
          <Button
            colorScheme="forestGreen"
            mr={3}
            color={"#fff"}
            size={"sm"}
            rounded={"sm"}
            onClick={handleSubmit}
            isLoading={isLoadingg}
          >
            Save
          </Button>
          <Button size={"sm"} rounded={"sm"} mr={3} onClick={handleClose}>
            Close
          </Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
};

export default UpdateIOStatus;
