import React, { useContext, useEffect, useState } from "react";
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
import { Box, useToast } from "@chakra-ui/react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { useNavigate, useParams } from "react-router-dom";
import FormInputMain from "../../../Components/FormInputMain";
import ToastBox from "../../../Components/ToastBox";
import FullscreenLoaders from "../../../Components/Loaders/FullscreenLoaders";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import SwitchButton from "../../../Components/SwitchButton";
import * as yup from "yup";
import { useGetBankDetailsQuery,useUpdateBankDetailsMutation } from "../../../Services/bank.details.service";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
// import { useUpdateBankDetailsMutation, useGetBankQuery } from "../../../Services/investorDetails.service";

const editBankSchema = yup.object().shape({
  accountNumber: yup.string().required("Account number is required"),
  swiftCode: yup.string().required("SWIFT code is required"),
  bankName: yup.string().required("Bank name is required"),
  bankAddress: yup.string().required("Bank address is required"),
  IBANnumber: yup.string().required("IBAN number is required"),
});

const EditBankDetails = () => {
  const toast = useToast();
  const params = useParams();
  const navigate = useNavigate();
  const id = params?.id;

  const [isLoadingBtn, setIsLoadingBtn] = useState(false);
  const { InvestorDetails, setInvestorDetails, slideFromRight } =
  useContext(GlobalStateContext); 
  const [alert, setAlert] = useState(false);
  const [form, setForm] = useState({});
  const [isSwitchOn, setIsSwitchOn] = useState(false);

  const [updateBankDetails] = useUpdateBankDetailsMutation();
  const { data: bankDetails, error, isLoading, refetch } = useGetBankDetailsQuery({ id }, { skip: !id });

  console.log(bankDetails);
  

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

  useEffect(() => {
    setInvestorDetails({
      ...bankDetails?.data,
    });
    // refetch()
    if (bankDetails?.data) {
      reset({
        accountName: bankDetails?.data?.accountName,
        countryName: bankDetails?.data?.countryName,
        accountNumber: bankDetails?.data?.accountNumber,
        swiftCode: bankDetails?.data?.swiftCode,
        bankName: bankDetails?.data?.bankName,
        bankAddress: bankDetails?.data?.bankAddress,
        IBANnumber: bankDetails?.data?.IBANnumber,
      });
    }
  }, [bankDetails, reset,id]);

  if (isLoading) {
    return <FullscreenLoaders />;
  }

  const handleConfirm = async () => {
    setIsLoadingBtn(true);
    try {
      const formData = {
        ...form,
        isActive: isSwitchOn,
      };

      const response = await updateBankDetails({ data: formData, id });
      if (response?.data?.statusCode) {
        toast({
          render: () => <ToastBox message={response.data.message} />,
        });

        setIsLoadingBtn(false);
        setAlert(false);
        refetch()
        navigate("/bank-details");
      } else {
        throw new Error("Something went wrong");
      }
    } catch (error) {
      toast({
        render: () => <ToastBox message="Something went wrong" status="error" />,
      });

      setIsLoadingBtn(false);
      navigate("/bank-details");
    }
  };

  console.log(bankDetails?.accountNumber);
  

  const formEditFields = [
    // {
    //   label: "Country Name",
    //   placeHolder:"",
    //   name: "countryName",
    //   type: "text",
    //    isRequired: true,
    //   section: "Add Details",
    //   maxLength: 50,
    //   width: "32%",
    // },
    {
      label: "Account Name",
      // value:bankDetails?.accountName,
      name: "accountName",
      placeHolder: "",
      type: "text",
      isRequired: true,
      section: "Add Details",
      // maxLength: 255,
      width: "32%",
    },
    {
      label: "Account Number",
      name: "accountNumber",
      placeHolder: "",
      type: "text",
      section: "Add Details",
      width: "32%",
      isRequired: true,
    },
    {
      label: "IBAN Number",
      name: "IBANnumber",
      placeHolder: "",
      type: "text",
      section: "Add Details",
      width: "32%",
      isRequired: true,
    },
    {
      label: "SWIFT Code",
      value: bankDetails?.data?.swiftCode,
      name: "swiftCode",
      placeHolder: "",
      type: "text",
      section: "Add Details",
      width: "32%",
      isRequired: true,
    },
    {
      label: "Bank Name",
      name: "bankName",
      placeHolder: "",
      type: "text",
      section: "Add Details",
      width: "32%",
      isRequired: true,
    },
    {
      label: "Bank Address",
      name: "bankAddress",
      placeHolder: "",
      type: "text",
      section: "Add Details",
      width: "32%",
      isRequired: true,
    },
  ];

  const groupedEditFields = formEditFields.reduce((groups, field) => {
    const { section } = field;
    if (!groups[section]) {
      groups[section] = [];
    }
    groups[section].push(field);
    return groups;
  }, {});

  const onSubmit = async(data) => {
    if (!Object.keys(errors).length) {
      setForm(data);
      setAlert(true);
    }
  };

  return (
    <Box {...OPACITY_ON_LOAD} overflowY="scroll" height="100vh" pb={14}>
      <FormInputMain
        groupedFields={groupedEditFields}
        control={control}
        errors={errors}
        onSubmit={handleSubmit(onSubmit)}
        submitTitle={id ? "Update" : "Submit"}
      />

      <CustomAlertDialog
        isOpen={alert}
        onClose={() => setAlert(false)}
        alertHandler={handleConfirm}
        message="Are you sure you want to update these details?"
        isLoading={isLoadingBtn}
      />
    </Box>
  );
};

export default EditBankDetails;
