/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useEffect, useState, useRef } from 'react';
import { Field, ErrorMessage, useFormikContext } from 'formik';
import { getCustomerSettlementIntervals, updateCustomerSettlementIntervals } from '../../../../Api/CustomerApi';
import { toast } from 'react-toastify';

interface SettlementSectionProps {
  open: boolean;
  toggle: () => void;
  SettlementInterval: Record<string, string | number>;
  disabled: boolean;
}

const SettlementSection = ({ open, toggle, SettlementInterval, disabled }: SettlementSectionProps) => {
  const { values, setFieldValue } = useFormikContext<any>();
  const [loading, setLoading] = useState(false);
  const [updating, setUpdating] = useState(disabled);
  const [initial, setInitial] = useState<{ cod_settlement_interval: string; invoice_settlement_interval: string } | null>(null);
  const isFirstLoad = useRef(true);

  // Fetch default values on mount
  useEffect(() => {
    if (!open) return;
    setLoading(true);
    getCustomerSettlementIntervals()
      .then((res) => {
        if (res?.status && res.data) {
          setInitial(res.data);
          setFieldValue('cod_settlement_interval', res.data.cod_settlement_interval);
          setFieldValue('invoice_settlement_interval', res.data.invoice_settlement_interval);
        } else {
          toast.error(res?.message || 'Failed to fetch settlement intervals');
        }
      })
      .catch((err) => toast.error(err?.message || 'Failed to fetch settlement intervals'))
      .finally(() => {
        setLoading(false);
        isFirstLoad.current = false;
      });
    // eslint-disable-next-line
  }, [open]);

  // Update API call on change
  useEffect(() => {
    if (loading || isFirstLoad.current || !initial) return;
    // Only call if values are different from initial
    if (
      values.cod_settlement_interval !== initial.cod_settlement_interval ||
      values.invoice_settlement_interval !== initial.invoice_settlement_interval
    ) {
      setUpdating(true);
      updateCustomerSettlementIntervals({
        cod_settlement_interval: values.cod_settlement_interval,
        invoice_settlement_interval: values.invoice_settlement_interval,
      })
        .then((res) => {
          if (res?.status) {
            toast.success('Settlement intervals updated successfully.');
            // Fetch latest after update
            getCustomerSettlementIntervals()
              .then((res2) => {
                if (res2?.status && res2.data) {
                  setInitial(res2.data);
                  setFieldValue('cod_settlement_interval', res2.data.cod_settlement_interval);
                  setFieldValue('invoice_settlement_interval', res2.data.invoice_settlement_interval);
                } else {
                  toast.error(res2?.message || 'Failed to fetch updated settlement intervals');
                }
              })
              .catch((err) => toast.error(err?.message || 'Failed to fetch updated settlement intervals'));
          } else {
            toast.error(res?.message || 'Failed to update settlement intervals');
          }
        })
        .catch((err) => toast.error(err?.message || 'Failed to update settlement intervals'))
        .finally(() => setUpdating(false));
    }
    // eslint-disable-next-line
  }, [values.cod_settlement_interval, values.invoice_settlement_interval]);

  return (
    <>
      <style>
        {`
          .input-style.has-borders.input-style-always-active.input-style-select label { left: 14px !important; }
        `}
      </style>
      <div className="accordion-section">
        <div
          className="accordion-header"
          onClick={toggle}
          style={{
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            padding: '1rem',
            background: '#f8f9fa',
            borderRadius: '10px 10px 0 0',
            border: '1px solid #eee',
            borderBottom: open ? 'none' : '1px solid #eee',
            marginTop: '1rem',
          }}
        >
          <div className="d-float-center justify-content-start gap-lg-5">
            <h4>Settlement Intervals</h4>
          </div>
          <i className={`fa ${open ? 'fa-chevron-up' : 'fa-chevron-down'}`}></i>
        </div>
        {open && (
          <div className="card card-style ms-lg-0" id="settlement-intervals">
            <div className="content mb-3">
              {loading ? (
                <div className="text-center my-2">
                  <span className="spinner-border spinner-border-sm" /> Loading...
                </div>
              ) : (
                <>
                  <div className="row">
                    <div className="col-lg-6 mb-3">
                      <div className="input-style has-borders no-icon input-style-always-active validate-field input-style-select mb-4">
                        <label htmlFor="cod_settlement_interval" className="color-highlight">
                          COD Settlement Interval <b className="text-danger">*</b>
                        </label>
                        <Field as="select" name="cod_settlement_interval" className="form-select" disabled={updating}>
                          <option value="">Select Interval</option>
                          {Object.entries(SettlementInterval)
                            .filter(([, value]) => !isNaN(Number(value)))
                            .map(([key, value]) => (
                              <option key={String(value)} value={String(value)}>
                                {key.replace(/([A-Z])/g, ' $1').trim()}
                              </option>
                            ))}
                        </Field>                      
                      </div>
                      <ErrorMessage name="cod_settlement_interval" component="div" className="text-danger small" />
                    </div>
                    <div className="col-lg-6 mb-3">
                      <div className="input-style has-borders no-icon input-style-always-active validate-field input-style-select mb-4">
                        <label htmlFor="invoice_settlement_interval" className="color-highlight">
                          Invoice Settlement Interval <b className="text-danger">*</b>
                        </label>
                        <Field as="select" name="invoice_settlement_interval" className="form-select" disabled={updating}>
                          <option value="">Select Interval</option>
                          {Object.entries(SettlementInterval)
                            .filter(([, value]) => !isNaN(Number(value)))
                            .map(([key, value]) => (
                              <option key={String(value)} value={String(value)}>
                                {key.replace(/([A-Z])/g, ' $1').trim()}
                              </option>
                            ))}
                        </Field>
                      </div>
                      <ErrorMessage name="invoice_settlement_interval" component="div" className="text-danger small" />
                    </div>
                  </div>
                  {(updating && !disabled) && (
                    <div className="text-end mt-2">
                      <span className="spinner-border spinner-border-sm me-1" /> Updating...
                    </div>
                  )}
                </>
              )}
            </div>
          </div>
        )}
      </div>
    </>
  );
};

export default SettlementSection;