import {
  Box,
  Button,
  Drawer,
  DrawerBody,
  DrawerCloseButton,
  DrawerContent,
  DrawerFooter,
  DrawerHeader,
  DrawerOverlay,
  FormControl,
  FormErrorMessage,
  FormLabel,
  Input,
  Select,
  Stack,
  Textarea,
  useToast,
} from "@chakra-ui/react";
import * as yup from "yup";
import React, { useState, useEffect, useContext } from "react";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import { v4 as uuidv4 } from "uuid";
import { useCreateIoCashMutation, useCreateVideoArtifactsMutation, useUpdateVideoArtifactsMutation } from "../../../Services/io.service";
import { useParams } from "react-router-dom";
import ToastBox from "../../../Components/ToastBox";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import CurrencyInput from "../../../Components/CurrencyInput";

const cashDetails = yup.object().shape({
  transactionDate: yup.string().required("Date is required"),
  ioTransType_xid: yup.number().required("Cash transaction is required"),
  transactionAmount: yup.number().required("Transaction Amount is required"),
  comments: yup.string().notRequired(),
});

const AddCashDetails = ({ isOpen, onClose, firstField, actionId, setActionId, data }) => {
  const params = useParams() 
  const id = params?.id
  const [file, setFile] = useState("");
  const [fileName, setFileName] = useState("");
  const [isLoading, setIsLoading] = useState(false)
  const [alert, setAlert] = useState(false);
  const toast = useToast();



  // ======================[ Cotext Api ]
  const { IODetails } = useContext(GlobalStateContext);
  const found = data?.find((item) => item?.id === actionId);


  const [createArtifactsVideo] = useCreateVideoArtifactsMutation()
  const [updateVideoArtifacts] = useUpdateVideoArtifactsMutation()
  // const {
  //   data
  // } = useGetArtifactsQuery(id) 

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


  const [createIoCash] = useCreateIoCashMutation()


  const onSubmit = async (data) => {

    setIsLoading(true)

    try {

      const res = await createIoCash({ data, id })
      if (res?.data?.statusCode === 200) {
        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);
      setIsLoading(false);
    }

  };



  const handleConfirm = () => {
    handleSubmit(onSubmit)();
  };

  const handleSave = () => {
    handleSubmit(onSubmit)();
  };

  const handleClose = () => {
    setAlert(false)
    onClose()
    reset({
      transactionAmount:""
    })
  }

  return (
    <>
      <Drawer
        size={"md"}
        isOpen={isOpen}
        placement="right"
        initialFocusRef={firstField}
        onClose={handleClose}
      >
        <DrawerOverlay />
        <DrawerContent>
          <DrawerCloseButton />
          <DrawerHeader fontSize={"sm"}>IO Cash Details</DrawerHeader>

          <DrawerBody>
            <Stack spacing={4}>
              <FormControl isInvalid={errors.transactionDate} isRequired> 
                <FormLabel fontSize={"sm"}>Date Selection</FormLabel>
                <Controller
                  name="transactionDate"
                  control={control}
                  render={({ field }) => (
                    <Input 
                    focusBorderColor="forestGreen.300" {...field} 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"}
                      focusBorderColor="forestGreen.300"
                    >
                      {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={'left'} 
                    focusBorderColor="forestGreen.300" fontSize={"sm"} type="text" size={"sm"} />
                  )}
                />
                <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                  {errors.comments?.message}
                </FormErrorMessage>
              </FormControl>

            </Stack>
          </DrawerBody>

          <DrawerFooter>
            <Button
              variant="outline"
              colorScheme={"forestGreen"}
              rounded={"sm"}
              size={"sm"}
              mr={3}
              onClick={handleClose}
            >
              Cancel
            </Button>

            <Button
              colorScheme={"forestGreen"}
              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 add cash details?"}
        isLoading={isLoading}
      />
    </>
  );
};

export default AddCashDetails;
