/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useEffect, useState } from "react";
import { Formik, Form } from "formik";
import * as Yup from "yup";
import InputFieldCustom from "../TextField/InputFieldCustom";
// import SelectField from "../TextField/ReactSelect";
import HourGlassLoader from "../Loader/Loader";
import {
  createCustomerBankDetail,
  getCustomerBankDetails,
  updateCustomerBankDetails,
} from "../../Api/CustomerApi";
import { getMasterList } from "../../Api/MastersApi";
import { toast } from "react-toastify";

interface BankFormData {
  account_holder_name: string;
  account_number: string;
  confirm_account_number: string;
  bank_name: string;
  branch_name: string;
  country_id: string;
  swift_code: string;
  iban: string;
  ifsc_code: string;
  upi_code: string;
  is_primary: string; // "yes" or "no"
}

interface Option {
  id: string;
  name: string;
}

const validationSchema = Yup.object().shape({
  account_holder_name: Yup.string().required("Account holder name is required"),
  account_number: Yup.string()
    .matches(/^[0-9]+$/, "Account number must be numeric")
    .required("Account number is required"),
  confirm_account_number: Yup.string()
    .oneOf([Yup.ref("account_number")], "Account numbers must match")
    .required("Please confirm account number"),
  bank_name: Yup.string().required("Bank name is required"),
  branch_name: Yup.string().optional(),
  country_id: Yup.string().optional(),
  swift_code: Yup.string().required("Swift code is required"),
  iban: Yup.string().required("IBAN is required"),
  ifsc_code: Yup.string().optional(),
  upi_code: Yup.string().optional(),
  is_primary: Yup.string().oneOf(["yes", "no"]),
});

const AddBankDetailsModal: React.FC<any> = ({ onHide, data }) => {
  const [isLoading, setIsLoading] = useState(false);
  const [isPrimaryAvailable, setIsPrimaryAvailable] = useState(false);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [countries, setCountries] = useState<Option[]>([]);

  const initialValues: BankFormData = {
    account_holder_name: data?.accountHolderName || "",
    account_number: data?.accountNumber || "",
    confirm_account_number: data?.accountNumber || "",
    bank_name: data?.bankName || "",
    branch_name: data?.branchName || "",
    country_id: data?.countryId || "",
    swift_code: data?.swiftCode || "",
    iban: data?.iban || "",
    ifsc_code: data?.ifscCode || "",
    upi_code: data?.upiCode || "",
    is_primary: data?.isPrimary
      ? "yes"
      : !isPrimaryAvailable
      ? "yes"
      : "no",
  };

  useEffect(() => {
    const fetchInit = async () => {
      setIsLoading(true);
      try {
        const [primaryRes, countriesRes] = await Promise.all([
          getCustomerBankDetails({ is_primary: true }),
          getMasterList("country"),
        ]);

        const primary = primaryRes?.data?.length > 0;
        setIsPrimaryAvailable(primary);
        setCountries(countriesRes?.data || []);
      } catch (err) {
        console.error("Initialization failed", err);
      } finally {
        setIsLoading(false);
      }
    };
    fetchInit();
  }, []);

  const handleSubmit = async (values: BankFormData) => {
    const payload = {
      ...values,
      is_primary: values.is_primary === "yes",
      country_id: Number(values.country_id),
    };

    try {
      setIsLoading(true);
      const response = data?.id
        ? await updateCustomerBankDetails(data.id, payload)
        : await createCustomerBankDetail(payload);

      if (response?.status) {
        toast.success("Bank account details saved successfully.");
        onHide();
      } else {
        toast.error(response.message || "Something went wrong.");
      }
    } catch (err) {
      console.error("Submission error", err);
      toast.error("Unexpected error occurred.");
      onHide();
    } finally {
      setIsLoading(false);
    }
  };
  return (
    <>
      <style>{`
        @media only screen and (min-device-width : 990px) and (max-device-width : 2000px) {
          .modal-dialog {
            display: flex;
            align-items: center;
            min-height: calc(100% - var(--bs-modal-margin) * 2);
            position: relative;
            margin: var(--bs-modal-margin);
            width: 960px;
            max-width: 960px;
            margin-right: auto;
            margin-left: auto;
          }
          .bottom-sheet-modal .modal-content {
            border-radius: 1.5rem;
          }
        }
        .react-select__control, .css-2ubb82-control { border-radius: 10px; position: unset; }
        .css-b62m3t-container { position: unset; }
        .input-style input, .input-style select, .input-style textarea {
          border-top-width: 1px;
          border-right-width: 1px;
          border-left-width: 1px;            
          border-radius: 10px;            
        }
        .modal-body { padding: 0px; }
        .input-style.mb-0 { margin-bottom: 0!important; }
        .text-danger { color: red; font-size: 0.8rem; margin-top: 4px; }
      `}</style>

      {isLoading && <HourGlassLoader />}

      <div id="add-address" data-menu-effect="menu-over" style={{ maxHeight: 555 }}>
        <Formik
          initialValues={initialValues}
          enableReinitialize
          validationSchema={validationSchema}
          onSubmit={handleSubmit}
        >
          {({ values, handleChange, handleSubmit, setFieldValue, errors }) => (
            <Form onSubmit={handleSubmit}>
              <div className="menu-title">
                <h1 className="font-24">
                  {data?.id ? "Edit Bank Details" : "Add Bank Details"}
                </h1>
              </div>
              <div className="content mb-0 mt-0">
                <div className="row mb-0 add-address-box">
                  <div className="col-lg-4">
                    <div className="input-outer-box mb-3">
                      <div className="input-style input-style-always-active has-borders has-icon validate-field mb-0">
                        <i className="ri ri-id-card-line color-blue-dark" aria-hidden="true"></i>
                        <label className="color-red2">
                          This account has to be primary
                        </label>
                        <select
                          value={values.is_primary}
                          onChange={(e) => setFieldValue("is_primary", e.target.value)}
                        >
                          <option value="yes" disabled={isPrimaryAvailable}>
                            Yes
                          </option>
                          <option value="no">No</option>
                        </select>
                      </div>
                    </div>
                  </div>

                  <InputFieldCustom
                    label="Account Holder Name"
                    value={values.account_holder_name}
                    onChange={handleChange("account_holder_name")}
                    name="account_holder_name"
                    page="my-profile"
                    icon="ri-user-line"
                    placeholder="Acc. Holder Name"
                    errors={errors}
                  />

                  <InputFieldCustom
                    label="Account Number"
                    value={values.account_number}
                    onChange={handleChange("account_number")}
                    name="account_number"
                    page="my-profile"
                    icon="ri-bank-card-line"
                    placeholder="Acc. No."
                    errors={errors}
                  />

                  <InputFieldCustom
                    label="Confirm Account Number"
                    value={values.confirm_account_number}
                    onChange={handleChange("confirm_account_number")}
                    name="confirm_account_number"
                    page="my-profile"
                    icon="ri-bank-card-line"
                    placeholder="Confirm Acc. No."
                    errors={errors}
                  />

                  <InputFieldCustom
                    label="Bank Name"
                    value={values.bank_name}
                    onChange={handleChange("bank_name")}
                    name="bank_name"
                    page="my-profile"
                    icon="ri-bank-line"
                    placeholder="Bank Name"
                    errors={errors}
                  />

                  {/* <InputFieldCustom
                    label="Branch Name"
                    value={values.branch_name}
                    onChange={handleChange("branch_name")}
                    name="branch_name"
                    page="bank"
                    icon="ri-building-line"
                    placeholder="Branch Name"
                    errors={errors}
                  /> */}

                  {/* <SelectField
                    options={countries}
                    title="Country"
                    value={countries.find((c) => c.id === values.country_id) || null}
                    onChange={(opt) => setFieldValue("country_id", opt?.id || "")}
                    placeholder="Select Country"
                    usageType={1}
                    page="bank"
                    name="country_id"
                    icon="ri-earth-line"
                  />
                  {touched.country_id && errors.country_id && (
                    <div className="text-danger col-12">{errors.country_id}</div>
                  )} */}

                  <InputFieldCustom
                    label="SWIFT Code"
                    value={values.swift_code}
                    onChange={handleChange("swift_code")}
                    name="swift_code"
                    page="my-profile"
                    icon="ri-lock-password-line"
                    placeholder="Swift Code"
                    errors={errors}
                  />

                  <InputFieldCustom
                    label="IBAN"
                    value={values.iban}
                    onChange={handleChange("iban")}
                    name="iban"
                    page="my-profile"
                    icon="ri-shield-keyhole-line"
                    placeholder="IBAN"
                    errors={errors}
                  />

                  {/* <InputFieldCustom
                    label="IFSC Code"
                    value={values.ifsc_code}
                    onChange={handleChange("ifsc_code")}
                    name="ifsc_code"
                    page="bank"
                    icon="ri-barcode-line"
                    placeholder="IFSC Code"
                    errors={errors}
                  /> */}
{/* 
                  <InputFieldCustom
                    label="UPI Code"
                    value={values.upi_code}
                    onChange={handleChange("upi_code")}
                    name="upi_code"
                    page="bank"
                    icon="ri-qr-code-line"
                    placeholder="UPI Code"
                    errors={errors}
                  /> */}
                </div>

                <div className="col-12">
                  <button
                    type="submit"
                    className="btn btn-full w-100 btn-l font-600 font-13 bg-blue-dark mt-0 mb-4 rounded-s"
                  >
                    Submit
                  </button>
                </div>
              </div>
            </Form>
          )}
        </Formik>
      </div>
    </>
  );
};

export default AddBankDetailsModal;
