import {
  Button,
  Drawer,
  DrawerBody,
  DrawerCloseButton,
  DrawerContent,
  DrawerFooter,
  DrawerHeader,
  FormControl,
  FormLabel,
  Input,
  Box,
  Text,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useState, useRef } from "react";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
import * as yup from "yup";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";

const InvestmentDetailsEdit = ({ isOpen, onClose, thirdField, id }) => {
  const { InvestorDetails, setInvestorDetails } = useContext(GlobalStateContext);
  const [file, setFile] = useState(null);

  const filteredObject = InvestorDetails?.find((item) => item?.id === id);

  const investmentDocSchema = yup.object().shape({
    fileName: yup.string().required("File name is required"),
    lastName: yup.string().required("Last name is required"),
    phoneNumber: yup.string().required("Phone number is required"),
    emailID: yup.string().required("Email ID is required"),
  });

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

  useEffect(() => {
    if (filteredObject) {
      reset({
        firstName: filteredObject?.firstName,
        lastName: filteredObject?.lastName,
        phoneNumber: filteredObject?.phoneNumber,
        emailID: filteredObject?.emailID,
      });
    }
  }, [id, InvestorDetails, reset]);

  const onSubmit = (data) => {
    const updatedInvestorDetails = InvestorDetails.map((item) =>
      item.id === id ? { ...item, ...data } : item
    );
    setInvestorDetails(updatedInvestorDetails);
    onClose();
  };

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

  return (
    <Drawer isOpen={isOpen} placement="right" onClose={onClose} initialFocusRef={thirdField}>
      <DrawerContent>
        <DrawerCloseButton />
        <DrawerHeader fontSize={"md"}>Investment Limit Update</DrawerHeader>
        <Box as="form" onSubmit={handleSubmit(onSubmit)}>
          <DrawerBody>
            <FormControl mb={4} isInvalid={errors.firstName}>
              <FormLabel fontSize="sm">File Name</FormLabel>
              <Input
                fontSize="sm"
                type="text"
                size="sm"
                {...register("firstName")}
              />
              {errors.firstName && (
                <Text color="red.500" fontSize="sm">
                  {errors.firstName.message}
                </Text>
              )}
            </FormControl>
            <FormControl mb={4} isInvalid={errors.lastName}>
              <FormLabel fontSize="sm">Last Name</FormLabel>
              <Input
                fontSize="sm"
                type="text"
                size="sm"
                {...register("lastName")}
              />
              {errors.lastName && (
                <Text color="red.500" fontSize="sm">
                  {errors.lastName.message}
                </Text>
              )}
            </FormControl>
            <FormControl mb={4} isInvalid={errors.phoneNumber}>
              <FormLabel fontSize="sm">Phone Number</FormLabel>
              <Input
                fontSize="sm"
                type="text"
                size="sm"
                {...register("phoneNumber")}
              />
              {errors.phoneNumber && (
                <Text color="red.500" fontSize="sm">
                  {errors.phoneNumber.message}
                </Text>
              )}
            </FormControl>
            <FormControl mb={4} isInvalid={errors.emailID}>
              <FormLabel fontSize="sm">E-mail ID</FormLabel>
              <Input
                fontSize="sm"
                type="text"
                size="sm"
                {...register("emailID")}
              />
              {errors.emailID && (
                <Text color="red.500" fontSize="sm">
                  {errors.emailID.message}
                </Text>
              )}
            </FormControl>
          </DrawerBody>
          <DrawerFooter>
            <Button
              variant="outline"
              colorScheme="forestGreen"
              rounded="sm"
              size="sm"
              mr={3}
              onClick={onClose}
            >
              Cancel
            </Button>
            <Button colorScheme="forestGreen" rounded="sm" size="sm" type="submit">
              Save
            </Button>
          </DrawerFooter>
        </Box>
      </DrawerContent>
    </Drawer>
  );
};

export default InvestmentDetailsEdit;
