import React, { useContext, useEffect, useState } from "react";
import {
  Box,
  Button,
  FormControl,
  FormLabel,
  Input,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Text,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import { Controller, useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import GlobalStateContext from "../../../../Contexts/GlobalStateContext";
import { useParams } from "react-router-dom";
import { useAmountIvestmentMutation } from "../../../../Services/io.service";
import ToastBox from "../../../../Components/ToastBox";
import CurrencyInput from "../../../../Components/CurrencyInput";
import RequestRejectModal from "./RequestRejectModal";
import ApproveInvestedModal from "./ApproveInvestedModal";
import { formatDate } from "../../../Master/Sponser/Sponsers";
import { encryptString, isMaker } from "../../../../Constants/Constants";

// Validation schema
const validationSchema = yup.object().shape({
  transactionDate: yup.date().required("Date is required"),
  Total_Amount: yup.number().required("Amount is required"),
  amountInvested: yup.number().required("Amount to invest is required"),
  IoCash: yup
    .number()
    .positive("IO Cash must be positive")
    .required("IO Cash is required"),
});

// Function to format currency
const formatCurrency = (value) => {
  if (isNaN(value)) return "";
  const formatted = parseFloat(value).toFixed(2).toString();
  const [integer, decimal] = formatted.split(".");
  const formattedInteger = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return decimal ? `${formattedInteger}.${decimal}` : formattedInteger;
};

const ViewAmountInvested = ({ isOpen, onClose, id: investorId }) => {
  const params = useParams();
  const toast = useToast();
  const id = params?.id;
  const {
    control,
    register,
    handleSubmit,
    reset,
    watch,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(validationSchema),
  });
  const [isLoading, setIsLoading] = useState(false);
  const { IODetails } = useContext(GlobalStateContext);
  const [amountInvested] = useAmountIvestmentMutation();
  const [actionId, setActionId] = useState(false);

  const {
    isOpen: isConfirmOpen,
    onOpen: onConfirmOpen,
    onClose: onConfirmClose,
  } = useDisclosure();
  const {
    isOpen: isRejectOpen,
    onOpen: onRejectOpen,
    onClose: onRejectClose,
  } = useDisclosure();

  useEffect(() => {
    if (IODetails?.totalAmtInvestmentInUSD) {
      const totalAmount = parseFloat(IODetails.totalAmtInvestmentInUSD);
      const ioCashUpdate = parseFloat(IODetails.totalAmtInvestmentInUSD);
      reset({
        Total_Amount: totalAmount,
        IoCash: ioCashUpdate,
      });
    }
  }, [IODetails, reset]);

  const onSubmit = async (data) => {
    console.log(data);
    setIsLoading(true);

    try {
      const res = await amountInvested({ data, id });
      console.log(res);
      if (res?.data?.statusCode === 200) {
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });
        setIsLoading(false);
        onClose();
      } else if (res?.error?.status === 400) {
        toast({
          render: () => (
            <ToastBox message={res?.error?.data?.message} status={"error"} />
          ),
        });
        setIsLoading(false);
      }
    } catch (error) {
      setIsLoading(false);
    }
  };

  // const formatDate = (date) => new Date(date).toLocaleDateString();

  const handleAmountChange = (e) => {
    // e might be an object or just a value, handle both cases
    const amount =
      typeof e === "object" && e.target
        ? parseFloat(e.target.value) || 0
        : parseFloat(e) || 0;
    const totalAmount = parseFloat(IODetails?.totalAmtInvestmentInUSD) || 0;
    const ioCash = (totalAmount - amount).toFixed(2);

    reset({
      amountInvested: parseFloat(amount),
      IoCash: parseFloat(ioCash),
      Total_Amount: IODetails?.totalAmtInvestmentInUSD,
    });
  };

  console.log(
    "=========hitttt",
    IODetails?.ioTransactionRecords?.Pending?.[0]?.createdAt
  );

  return (
    <Modal isOpen={isOpen} onClose={onClose}>
      <ModalOverlay />
      <ModalContent>
        <ModalHeader fontSize={"md"}>Amount Invested</ModalHeader>
        <ModalCloseButton />
        <ModalBody>
          <form onSubmit={handleSubmit(onSubmit)}>
            <FormControl
              mb={"15px"}
              isInvalid={!!errors.transactionDate}
              isRequired
            >
              <FormLabel as={"label"} fontSize={"sm"} fontWeight={500}>
                Date
              </FormLabel>
              <Input
                type="text"
                value={formatDate(
                  IODetails?.ioTransactionRecords?.Pending?.[0]?.createdAt
                )}
                // value={IODetails?.ioTransactionRecords?.Pending?.[0]?.createdAt}
                size="sm"
                rounded={"sm"}
                textAlign={"end"}
                focusBorderColor="forestGreen.300"
                fontSize={"sm"}
                readOnly
              />
              {/* <Text>
                {IODetails?.ioTransactionRecords?.Approved?.[0]?.createdAt} dccd
              </Text> */}
            </FormControl>

            <FormControl
              mb={"15px"}
              isInvalid={!!errors.Total_Amount}
              isReadOnly
            >
              <FormLabel as={"label"} fontSize={"sm"} fontWeight={500}>
                Amount
              </FormLabel>
              <Input
                type="text"
                value={formatCurrency(watch("Total_Amount") || 0)}
                size="sm"
                rounded={"sm"}
                textAlign={"end"}
                focusBorderColor="forestGreen.300"
                fontSize={"sm"}
                readOnly
              />
            </FormControl>

            <FormControl
              mb={"15px"}
              isInvalid={!!errors.amountInvested}
              isRequired
            >
              <FormLabel as={"label"} fontSize={"sm"} fontWeight={500}>
                Amount to invest
              </FormLabel>
              <Input
                type="text"
                value={formatCurrency(
                  IODetails?.ioTransactionRecords?.Pending?.[0]
                    ?.transactionAmount || 0
                )}
                size="sm"
                rounded={"sm"}
                textAlign={"end"}
                focusBorderColor="forestGreen.300"
                fontSize={"sm"}
                readOnly
              />
            </FormControl>

            <FormControl mb={"15px"} isInvalid={!!errors.IoCash}>
              <FormLabel as={"label"} fontSize={"sm"} fontWeight={500}>
                IO Cash
              </FormLabel>
              <Input
                type="text"
                value={formatCurrency(
                  (watch("Total_Amount") || 0) -
                    (IODetails?.ioTransactionRecords?.Pending?.[0]
                      ?.transactionAmount || 0)
                )}
                size="sm"
                rounded={"sm"}
                focusBorderColor="forestGreen.300"
                fontSize={"sm"}
                textAlign={"right"}
                readOnly
              />
            </FormControl>

            {!isMaker() && (
              <ModalFooter>
                <Box display={"flex"} justifyContent={"center"} gap={2}>
                  <Button
                    rounded={"sm"}
                    size={"xs"}
                    textTransform={"inherit"}
                    fontWeight={500}
                    px={3}
                    py={2}
                    onClick={() => {
                      setActionId(id); // Use the `id` variable from params
                      onConfirmOpen();
                    }}
                    colorScheme="forestGreen"
                    variant={"solid"}
                    cursor={"pointer"}
                  >
                    Approve
                  </Button>
                  <Button
                    rounded={"sm"}
                    size={"xs"}
                    textTransform={"inherit"}
                    fontWeight={500}
                    px={3}
                    py={2}
                    onClick={() => {
                      setActionId(id); // Use the `id` variable from params
                      onRejectOpen();
                    }}
                  >
                    Reject
                  </Button>
                </Box>
              </ModalFooter>
            )}
          </form>
        </ModalBody>
      </ModalContent>
      <ApproveInvestedModal
        isOpen={isConfirmOpen}
        onClose={onConfirmClose}
        onBigModalClose={onClose}
        id={investorId}
      />
      <RequestRejectModal
        isOpen={isRejectOpen}
        onClose={onRejectClose}
        onBigModalClose={onClose}
        id={investorId}
      />
    </Modal>
  );
};

export default ViewAmountInvested;
