import {
  Badge,
  Box,
  Button,
  FormControl,
  FormHelperText,
  FormLabel,
  Heading,
  HStack,
  Input,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Text,
  Textarea,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import React, { useEffect, useState } from "react";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { Controller, useForm } from "react-hook-form";
import FullscreenLoaders from "../../../Components/Loaders/FullscreenLoaders";
import ToastBox from "../../../Components/ToastBox";
import {
  useGetDrawalRequestByIdQuery,
  useUpdateDrawalRequestMutation,
} from "../../../Services/drawal.request.service";
import CurrencyInput from "../../../Components/CurrencyInput";
import { GrClose } from "react-icons/gr";

const FILE_TYPES = ["image/jpeg", "image/png", "image/gif"];

export const conformModalSchema = yup.object().shape({
  investorAmount: yup.string().required("Investor amount is required"),
  comment: yup.string().notRequired()
  .max(200, "Approve Comment cannot be more than 200 characters"),
});

const DrawalRequestApprove = ({
  isOpen,
  onClose,
  firstField,
  id,
  data: requestData,
}) => {
  const toast = useToast();
  const [file, setFile] = useState();
  const [isBtnLoading, setIsBtnLoading] = useState(false);

  const [updateDrawalRequest] = useUpdateDrawalRequestMutation();
  const { data, isLoading } = useGetDrawalRequestByIdQuery(id, {
    skip: !id,
  });

  const filteredData = data?.dat;
  const {
    control,
    register,
    watch,
    reset,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(conformModalSchema),
  });

  useEffect(() => {
    if (data) {
      const investorAmount = parseFloat(data?.data?.investorAmount);
      reset({
        investorAmount: Math.abs(investorAmount),
        accountName: data?.data?.accountName,
      });
    }
  }, [id, data, reset]);

  const onSubmit = async (data) => {
    setIsBtnLoading(true);

    try {
      const res = await updateDrawalRequest({ id, data });

      if (res?.error) {
        toast({
          render: () => (
            <ToastBox message={res?.error?.data?.message} status={"error"} />
          ),
        });
        setIsBtnLoading(false);
      } else if (res?.data?.statusCode === 200) {
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });
        setIsBtnLoading(false);
      }
    } catch (error) {}

    heandleOnClose();
  };

  const handleFileChange = (event) => {
    const selectedFile = event.target.files[0];
    setFile(selectedFile);
  };

  // useEffect(() => {
  //   if (data) {
  //     reset({
  //       investorAmount: data?.data?.dataValues?.investorAmount,
  //     });
  //   }
  // }, [data, reset]);

  const heandleOnClose = () => {
    reset({
      investorAmount: "",
    });
    onClose();
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={heandleOnClose}
      initialFocusRef={firstField}
    >
      <ModalOverlay />

      <ModalContent pb={4}>
        <HStack justifyContent={"space-between"}>
          <ModalHeader fontSize={"md"}>Confirm</ModalHeader>
          <Button onClick={onClose} bg={"transparent"} _hover={{backgroundColor:"transparent"}}>
            <GrClose />
          </Button>
        </HStack>
        {/* <ModalCloseButton  /> */}
        {isLoading ? (
          <FullscreenLoaders height={"50vh"} />
        ) : (
          <Box as="form" onSubmit={handleSubmit(onSubmit)}>
            <ModalBody>
              {/* <FormControl mb={5} isRequired>
                <FormLabel fontSize="sm">
                  Withdrawal Amount{" "}
                  <Badge colorScheme="green">
                    {filteredData?.currencyCode}
                  </Badge>
                </FormLabel>
                <Input
                  focusBorderColor="green.400"
                  name="investorAmount"
                  {...register("investorAmount")}
                  fontSize="sm"
                  type="number"
                  size="sm"
                  placeholder={"100,000"}
                  textAlign={"right"}
                  // readOnly
                />
                {errors.investorAmount && (
                  <Text fontSize="xs" color="red">
                    {errors.investorAmount.message}
                  </Text>
                )}
              </FormControl> */}
{/* =======================[ Coma is acchived using Controller ]================================ */}
              <FormControl mb={5} isRequired>
                <FormLabel fontSize={"sm"}>Withdrawal Amount</FormLabel>
                <Controller
                  name="investorAmount"
                  control={control}
                  render={({ field }) => (
                    <CurrencyInput
                      {...field}
                      textAlign={"right"}
                      fontSize={"sm"}
                      type="number"
                      size={"sm"}
                    />
                  )}
                />
                {errors.investorAmount && (
                  <Text fontSize="xs" color="red">
                    {errors.investorAmount.message}
                  </Text>
                )}
              </FormControl>

              <Heading fontSize="sm" fontWeight={600} mb={4}>
                Investor Account Details
              </Heading>
              <Box display={"flex"} mb={3}>
                <Text fontSize="xs" mb={0} fontWeight={500} me={2} w={"110px"}>
                  IBAN:
                </Text>
                <Text fontSize="xs" mb={0}>
                  {data?.data?.bank_payouts?.IBANnumber}
                </Text>
              </Box>
              <Box display={"flex"} mb={3}>
                <Text fontSize="xs" mb={0} fontWeight={500} me={2} w={"110px"}>
                  Account No:
                </Text>
                <Text fontSize="xs" mb={0}>
                  {data?.data?.bank_payouts?.accountNumber}
                </Text>
              </Box>
              <Box display={"flex"} mb={3}>
                <Text fontSize="xs" mb={0} fontWeight={500} me={2} w={"110px"}>
                  Bank Name:
                </Text>
                <Text fontSize="xs" mb={0}>
                  {data?.data?.bank_payouts?.bankName}
                </Text>
              </Box>
              <Box display={"flex"} mb={3}>
                <Text fontSize="xs" mb={0} fontWeight={500} me={2} w={"110px"}>
                  Account Name:
                </Text>
                <Text fontSize="xs" mb={0}>
                  {data?.data?.bank_payouts?.accountName}
                </Text>
              </Box>
              <Box display={"flex"} mb={3}>
                <Text fontSize="xs" mb={0} fontWeight={500} me={2} w={"110px"}>
                  SWIFT Code:
                </Text>
                <Text fontSize="xs" mb={0}>
                  {data?.data?.bank_payouts?.swiftCode}
                </Text>
              </Box>
              <Box display={"flex"} mb={5}>
                <Text fontSize="xs" mb={0} fontWeight={500} me={2} w={"110px"}>
                  Bank Address:
                </Text>
                <Text fontSize="xs" mb={0}>
                  {data?.data?.bank_payouts?.bankAddress}
                </Text>
              </Box>
              <Box display={"flex"} mb={5}>
                <Text fontSize="xs" mb={0} fontWeight={500} me={2} w={"110px"}>
                  Bank Nick Name:
                </Text>
                <Text fontSize="xs" mb={0}>
                  {data?.data?.bank_payouts?.bankNickName}
                </Text>
              </Box>
              <FormControl mb={4}>
                <FormLabel fontSize="sm">Comments</FormLabel>
                <Textarea
                  rows={5}
                  focusBorderColor="green.400"
                  name="comment"
                  {...register("comment")}
                  fontSize="sm"
                  type="textarea"
                  size="sm"
                  placeholder={"Enter your comments...."}
                  resize={"none"}
                  maxLength={200}
                />
                {errors.comment && (
                  <Text fontSize="xs" color="red">
                    {errors.comment.message}
                  </Text>
                )}
                <FormHelperText fontSize="xs" color="gray.500">
                  <Text as={"span"} me={1}>Maximum length should be 200 characters. You have entered</Text>
                  {watch("checkerComment")?.length || 0} characters.
                </FormHelperText>
              </FormControl>
            </ModalBody>
            <ModalFooter>
              <Button
                colorScheme="gray"
                mr={3}
                onClick={onClose}
                size={"sm"}
                rounded={"sm"}
              >
                Cancel
              </Button>
              <Button
                colorScheme="forestGreen"
                variant="solid"
                size={"sm"}
                rounded={"sm"}
                isLoading={isBtnLoading}
                type="submit"
              >
                Confirm
              </Button>
            </ModalFooter>
          </Box>
        )}
      </ModalContent>
    </Modal>
  );
};

export default DrawalRequestApprove;
