import {
  Badge,
  Box,
  Button,
  FormControl,
  FormErrorMessage,
  FormLabel,
  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 {
  useGetDepositRequestByIdQuery,
  useGetDepositRequestQuery,
  useUpdateDepositRequestMutation,
} from "../../../Services/deposit.request.service";
import FullscreenLoaders from "../../../Components/Loaders/FullscreenLoaders";
import ToastBox from "../../../Components/ToastBox";
import CurrencyInput, { formatCurrency } from "../../../Components/CurrencyInput";

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(),
  supporting_FileName: yup.mixed().required("File is required"),
  // .test("fileType", "Unsupported File Format", (value) => {
  //   return value && FILE_TYPES.includes(value.type);
  // }),
});

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

  const [updateDepositRequest] = useUpdateDepositRequestMutation();
  const { data, isLoading } = useGetDepositRequestByIdQuery(id, {
    skip: !id,
  });

  console.log(data?.data?.investorAmount);

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

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

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

    formData.append("investorAmount", data.investorAmount);
    formData.append("comment", data.comment);
    const file = data.supporting_FileName["0"];
    formData.append("supporting_FileName", file);

    try {
      const res = await updateDepositRequest({ id, data: formData });

      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 heandleOnClose = () => {
    reset();
    onClose();
  };

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

      <ModalContent pb={4}>
        <ModalHeader fontSize={"md"}>Confirm</ModalHeader>
        <ModalCloseButton />
        {isLoading ? (
          <FullscreenLoaders height={"50vh"} />
        ) : (
          <Box as="form" onSubmit={handleSubmit(onSubmit)}>
            <ModalBody>
              {/* <FormControl mb={4} isRequired>
                <FormLabel fontSize="sm">
                  Deposit Amount
                  <Badge colorScheme="green">{data?.data?.currencyCode}</Badge>
                </FormLabel>
                <Input
                  focusBorderColor="green.400"
                  name="investorAmount"
                  {...register("investorAmount")}
                  value={formatCurrency(watch("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> */}

              <FormControl mb={5} isRequired>
                <FormLabel fontSize={"sm"}>Deposit 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>

              <FormControl mb={4} isRequired>
                <FormLabel fontSize="sm">Upload Supporting</FormLabel>
                <Input
                  focusBorderColor="green.400"
                  name="supporting_FileName"
                  {...register("supporting_FileName")}
                  fontSize="sm"
                  type="file"
                  size="sm"
                  placeholder={"$100,000"}
                  className="form-control"
                  accept="image/*"
                />
                {errors.supporting_FileName && (
                  <Text fontSize="xs" color="red">
                    {errors.supporting_FileName.message}
                  </Text>
                )}
              </FormControl>
              <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"}
                />
                {errors.comment && (
                  <Text fontSize="xs" color="red">
                    {errors.comment.message}
                  </Text>
                )}
              </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 RequestApproveModal;
