import {
  Box,
  Button,
  Drawer,
  DrawerBody,
  DrawerCloseButton,
  DrawerContent,
  DrawerFooter,
  DrawerHeader,
  DrawerOverlay,
  FormControl,
  FormLabel,
  Input,
  Text,
  useDisclosure,
} from "@chakra-ui/react";
import React, { useContext, useRef, useState, useEffect } from "react";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import { MdHistory } from "react-icons/md";

// Convert date to YYYY-MM-DD format
const formatDate = (dateString) => {
  if (!dateString) return "Invalid Date";
  let date = new Date(dateString);
  if (isNaN(date.getTime())) {
    // Try to handle different formats
    const parts = dateString.split(/[- :]/);
    if (parts.length >= 3) {
      date = new Date(parts[0], parts[1] - 1, parts[2]);
    }
  }
  if (isNaN(date.getTime())) {
    return "Invalid Date";
  }
  const options = {
    weekday: "short",
    year: "numeric",
    month: "short",
    day: "numeric",
  };
  return date.toLocaleDateString("en-US", options);
};

const ExchangeHistory = ({ id, setIsLoading, history }) => {
  const btnRef = useRef();
  const { isOpen, onOpen, onClose } = useDisclosure();
  const { rateExchange, setRateExchange } = useContext(GlobalStateContext);

  const foundObject = rateExchange.find((item) => item.id === id);

  const [effectFrom, setEffectFrom] = useState("");
  const [effectTill, setEffectTill] = useState("");
  const [newRate, setNewRate] = useState("");
  const [alert, setAlert] = useState(false);

  useEffect(() => {
    if (foundObject) {
      setEffectFrom(formatDate(foundObject.effectFrom));
      //   setEffectTill(formatDate(foundObject.effectTill));
      setNewRate(foundObject.rate);
    }
  }, [foundObject]);

  //   const handleSave = () => {
  //     setIsLoading(true);
  //     const updatedExchange = rateExchange.map((item) =>
  //       item.id === id
  //         ? {
  //             ...item,
  //             effectFrom: new Date(effectFrom),
  //             rate: parseFloat(newRate),
  //           }
  //         : item
  //     );
  //     setTimeout(() => {
  //       setRateExchange(updatedExchange);
  //       setIsLoading(false);
  //       setAlert(false);
  //       onClose();
  //     }, 100);
  //     setIsLoading(true);
  //   };

  return (
    <>
      <Button
        leftIcon={<MdHistory />}
        ref={btnRef}
        onClick={onOpen}
        color={"green.500"}
        size={"xs"}
        variant={"ghost"}
        rounded={"md"}
        ms={"auto"}
      >
        History
      </Button>
      <Drawer
        isOpen={isOpen}
        placement="right"
        onClose={onClose}
        finalFocusRef={btnRef}
      >
        <DrawerOverlay />
        <DrawerContent>
          <DrawerCloseButton />
          <DrawerHeader fontSize={"md"}>Exchange History</DrawerHeader>

          <DrawerBody>
            {/* <FormControl mb={4}>
              <FormLabel fontSize={"sm"}>Previous exchange rate</FormLabel>
              <Text fontSize={"sm"}>{foundObject?.rate}</Text>
            </FormControl> */}

            <Box mt={4}>
              {history &&
                history.map((entry, index) => {
                  // console.log("entry:", entry);
                  return (
                    <>
                      {id === entry.id ? (
                        <Box key={index}>
                          <Box
                            mt={2}
                            display={"flex"}
                            alignItems={"end"}
                            justifyContent={"space-between"}
                          >
                            <Box>
                              <Text fontSize={"sm"} marginBottom={"0px"}>
                                <strong>Previous Rate:</strong>
                              </Text>
                              <Text fontSize={"sm"}>
                                {entry.previousRate}{" "}
                                <Text as={"span"} fontSize={"sm"}>
                                  {foundObject?.toCurr}
                                </Text>
                              </Text>
                            </Box>

                            <Box>
                              <Text fontSize={"sm"} marginBottom={"0px"}>
                                <strong>Effect Till:</strong>
                              </Text>
                              <Text fontSize={"sm"}>
                                {formatDate(entry.effectFrom)}
                              </Text>
                            </Box>
                          </Box>

                          <Box
                            display={"flex"}
                            alignItems={"end"}
                            justifyContent={"space-between"}
                          >
                            <Box>
                              <Text fontSize={"sm"} marginBottom={"0px"}>
                                <strong>New Rate:</strong>
                              </Text>
                              <Text fontSize={"sm"}>
                                {" "}
                                {entry?.newRate}{" "}
                                <Text as={"span"} fontSize={"sm"}>
                                  {foundObject?.toCurr}
                                </Text>
                              </Text>
                            </Box>
                            <Box>
                              <Text fontSize={"sm"} marginBottom={"0px"}>
                                <strong>Effect From:</strong>
                              </Text>
                              <Text fontSize={"sm"}>
                                {formatDate(entry.effectFrom)}
                              </Text>
                            </Box>
                          </Box>
                        </Box>
                      ) : (
                        ""
                      )}
                    </>
                  );
                })}

              {/* <Text fontSize={"sm"} marginBottom={"0px"}>
                <strong>New Rate:</strong>
              </Text>
              <Text fontSize={"sm"}>
                {" "}
                {foundObject?.rate} {foundObject?.toCurr}
              </Text> */}
            </Box>
          </DrawerBody>

          <DrawerFooter>
            <Button
              variant="outline"
              colorScheme={"green"}
              rounded={"sm"}
              size={"sm"}
              mr={3}
              onClick={onClose}
            >
              Close
            </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 rates?"}
      />
    </>
  );
};

export default ExchangeHistory;
