import {
  Box,
  Button,
  FormControl,
  FormErrorMessage,
  FormLabel,
  Input,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Select,
  Stack,
  Text,
  Textarea,
  useToast,
} from "@chakra-ui/react";
import { useContext, useState } from "react";
import * as yup from "yup";
import GlobalStateContext from "../../../../Contexts/GlobalStateContext";
import { Controller, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import CurrencyInput from "../../../../Components/CurrencyInput";
import { useCreateIoNavMutation } from "../../../../Services/io.service";
import ToastBox from "../../../../Components/ToastBox";
import { useParams } from "react-router-dom";
import { formatDatee } from "../../../../Components/FormField";

const ioNav = yup.object().shape({
  transactionDate: yup.string().required("Artifact name is required"),
  // ioTransType_xid: yup.number().required("Artifact name is required"),
  transactionAmount: yup.number().required("Artifact name is required"),
  comments: yup.string().notRequired(),
});

const UpdateIONav = ({ isOpen, onClose }) => {
  const params = useParams()
  const toast = useToast();
  const id = params?.id
  const { IODetails } = useContext(GlobalStateContext);
  const [isLoading, setIsLoading] = useState(false)
  const {
    control,
    handleSubmit,
    watch,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(ioNav),
  });


  const [createIoNav] = useCreateIoNavMutation()


  const onSubmit = async (data) => {
    setIsLoading(true);
    try {
      const res = await createIoNav({ data, id })
      if (res?.data?.statusCode === 201) {
        setIsLoading(false);
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });
        handleClose()
      } else if (res?.error?.status === 400) {
        setIsLoading(false);
        toast({
          render: () => <ToastBox message={res?.error?.data?.message} status={"error"} />,
        });
      }
    } catch (error) {
      console.log(error);
    }
  }





  const handleClose = () => {
    onClose()
    reset()
  }


const today = formatDatee(new Date(), 'yyyy-MM-dd'); 


  return (
    <Modal isOpen={isOpen} onClose={onClose}>
      <ModalOverlay />
      <ModalContent as={'form'} onSubmit={handleSubmit(onSubmit)} >
        <ModalHeader fontSize={'md'}>Update iO NAV Transaction</ModalHeader>
        <ModalCloseButton />
        <ModalBody>

          <Stack spacing={4}>
            <FormControl isInvalid={errors.transactionDate} isRequired>
              <FormLabel fontSize={"sm"}>Date Selection</FormLabel>
              <Controller
                name="transactionDate"
                control={control}
                render={({ field }) => (
                  <Input {...field}
                    max={today} // Set max attribute to today’s date
                    fontSize={"sm"} type="date" size={"sm"} />
                )}
              />
              <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                {errors.transactionDate?.message}
              </FormErrorMessage>
            </FormControl>


            {/* <FormControl isInvalid={errors.ioTransType_xid} isRequired>
              <FormLabel fontSize={"sm"}>Cash transaction</FormLabel>
              <Controller
                name="ioTransType_xid"
                control={control}
                render={({ field }) => (
                  <Select
                    {...field}
                    placeholder="Select an option"
                    fontSize={"sm"}
                    size={"sm"}
                  >
                    {IODetails?.ioCashTransaction?.map(({ id, transactionName }) => (
                      <option key={id} value={id}>
                        {transactionName}
                      </option>
                    ))}
                  </Select>
                )}
              />
              <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                {errors.ioTransType_xid?.message}
              </FormErrorMessage>
            </FormControl> */}




            <FormControl isInvalid={errors.transactionAmount} isRequired>
              <FormLabel fontSize={"sm"}>Transaction Amount</FormLabel>
              <Controller
                name="transactionAmount"
                control={control}
                render={({ field }) => (
                  <CurrencyInput {...field} textAlign={'right'} fontSize={"sm"} type="number" size={"sm"} />
                )}
              />
              <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                {errors.transactionAmount?.message}
              </FormErrorMessage>
            </FormControl>



            <FormControl isInvalid={errors.comments}>
              <FormLabel fontSize={"sm"}>Comments</FormLabel>
              <Controller
                name="comments"
                control={control}
                render={({ field }) => (
                  <Textarea {...field} textAlign={'right'} fontSize={"sm"} type="text" size={"sm"} />
                )}
              />
              <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                {errors.comments?.message}
              </FormErrorMessage>
            </FormControl>
          </Stack>
        </ModalBody>
        <ModalFooter>
          <Button
            bg={"hsla(139, 100%, 14%, 1)"}
            mr={3}
            color={"#fff"}
            _hover={{
              bg: "hsl(139deg 98.99% 26.59%)",
            }}
            size={'sm'}
            rounded={"sm"}
            type="submit"
            isLoading={isLoading}
          >
            Save
          </Button>
          <Button
            size={'sm'}
            rounded={"sm"} mr={3} onClick={onClose}>
            Close
          </Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
};

export default UpdateIONav;
