import {
  Box,
  Button,
  Drawer,
  DrawerBody,
  DrawerCloseButton,
  DrawerContent,
  DrawerFooter,
  DrawerHeader,
  DrawerOverlay,
  FormControl,
  FormLabel,
  Input,
  Text,
  Tooltip,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useRef, useState, useEffect } from "react";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import { FiEdit3 } from "react-icons/fi";
import { BiMessageSquareEdit } from "react-icons/bi";
import { TbEdit } from "react-icons/tb";
import { EditIcon, ViewIcon } from "@chakra-ui/icons";
import { formatDate } from "../../../Components/Functions/UTCConvertor";
import {
  useGetExchangeRateByIdQuery,
  useUpdateExchangeRateMutation,
} from "../../../Services/exchange.rate.service";
import ToastBox from "../../../Components/ToastBox";
import { getTomorrowDate } from "../../../Constants/Constants";
import FullscreenLoaders from "../../../Components/Loaders/FullscreenLoaders";

// Convert date to YYYY-MM-DD format
const formatDateValue = (date) => {
  if (!date) return "";
  const d = new Date(date);
  let month = "" + (d.getMonth() + 1);
  let day = "" + d.getDate();
  const year = d.getFullYear();

  if (month.length < 2) month = "0" + month;
  if (day.length < 2) day = "0" + day;

  return [year, month, day].join("-");
};

const EditExchangeRate = ({
  id,
  setIsLoading,
  isOpen,
  onOpen,
  onClose,
  btnRef,
}) => {
  const toast = useToast();
  const {} = useDisclosure();
  const [isBtnLoading, setIsBtnLoading] = useState(false);

  const { data, isLoading, errors } = useGetExchangeRateByIdQuery(id, {
    skip: !id,
  });

  const [updateExchange] = useUpdateExchangeRateMutation();
  const foundObject = data?.data;
  const [rate, setRate] = useState("");
  const [alert, setAlert] = useState(false);

  useEffect(() => {
    if (foundObject) {
      setRate(foundObject.rate);
    }
  }, [foundObject]);

  const handleSave = async () => {
    setIsBtnLoading(true);
    try {
      const data = {
        rate: rate,
      };
      const res = await updateExchange({ data, id });
      if (res?.data?.statusCode === 200) {
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });
        setIsBtnLoading(false);
        setAlert(false);
        onClose();
      }
    } catch (error) {}
  };

  return (
    <>
      <Drawer
        // size={"md"}
        isOpen={isOpen}
        placement="right"
        onClose={onClose}
        finalFocusRef={btnRef}
      >
        <form
          onSubmit={(e) => {
            e.preventDefault();
            setAlert(true);
          }}
        >
          <DrawerOverlay />
          <DrawerContent>
            <DrawerCloseButton />
            <DrawerHeader fontSize={"md"}>Edit rate</DrawerHeader>

            {isLoading ? (
              <FullscreenLoaders />
            ) : (
              <>
                {" "}
                <DrawerBody>
                  <Box display={"flex"} mb={5}>
                    <Box
                      w={"50%"}
                      display={"flex"}
                      flexDirection={"column"}
                      gap={1}
                    >
                      <FormLabel fontSize={"sm"}>From</FormLabel>
                      <Text as={"span"} fontSize={"sm"} fontWeight={"bold"}>
                        {foundObject?.fromCurrency?.currencyCode}
                      </Text>
                    </Box>
                    <Box
                      w={"50%"}
                      display={"flex"}
                      flexDirection={"column"}
                      gap={1}
                    >
                      <FormLabel fontSize={"sm"}>To</FormLabel>
                      <Text as={"span"} fontSize={"sm"} fontWeight={"bold"}>
                        {foundObject?.toCurrency?.currencyCode}
                      </Text>
                    </Box>
                  </Box>

                  {/* <FormControl mb={4}>
                <FormLabel fontSize={"sm"}>Last effective date</FormLabel>
                <Text color={'gray.500'}  fontSize={"sm"}>
                  {formatDate(foundObject?.effectiveFrom)}
                </Text>
              </FormControl>   */}
                  <FormControl mb={4}>
                    <FormLabel fontSize={"sm"}>Effective from</FormLabel>
                    <Text fontSize={"sm"}>{formatDate(getTomorrowDate())}</Text>
                  </FormControl>

                  <FormControl mb={4} isRequired>
                    <FormLabel fontSize={"sm"}>Rate</FormLabel>
                    <Input
                      required
                      type="number"
                      placeholder="Type rate here..."
                      size={"sm"}
                      value={rate}
                      onChange={(e) => setRate(e.target.value)}
                    />
                  </FormControl>
                </DrawerBody>
                <DrawerFooter>
                  <Button
                    variant="outline"
                    colorScheme={"forestGreen"}
                    rounded={"sm"}
                    size={"sm"}
                    mr={3}
                    onClick={onClose}
                  >
                    Cancel
                  </Button>

                  <Button
                    colorScheme={"forestGreen"}
                    rounded={"sm"}
                    size={"sm"}
                    type="submit"
                  >
                    Save
                  </Button>
                </DrawerFooter>
              </>
            )}
          </DrawerContent>
        </form>
      </Drawer>
      <CustomAlertDialog
        isOpen={alert}
        onClose={() => setAlert(false)}
        alertHandler={handleSave}
        message={"Are you sure you want to update rates?"}
        isLoading={isBtnLoading}
      />
    </>
  );
};

export default EditExchangeRate;
