import { convertToShorthand } from '@/utills/helper';
import { InputNumber, Modal, Form, Col } from 'antd';
import { useRef, useState } from 'react';

interface Props {
  maxValue: number;
  agreement_value: number;
}

export function AgreementAmountInput({ maxValue, agreement_value }: Props) {
  const inputRef = useRef<any>(null); // ref for focusing input
  const [showModal, setShowModal] = useState(false);
  const [lastValue, setLastValue] = useState<number | null>(null);
  const [shouldFocus, setShouldFocus] = useState(false);

  const handleBlur = () => {
    if (lastValue && (lastValue < 3000000 || lastValue > 50000000)) {
      setShowModal(true);
    }
  };

  const handleOk = () => {
    setShowModal(false);
    setShouldFocus(false); // Do not refocus
  };

  const handleCancel = () => {
    setShowModal(false);
    setShouldFocus(true); // Refocus
  };

  // Refocus when modal closes and Cancel was clicked
  if (shouldFocus && inputRef.current) {
    inputRef.current.focus();
    setShouldFocus(false); // avoid refocus loop
  }

  return (
    <>
      <Col span={24} sm={12} md={12} lg={12} xl={12}>
        <Form.Item
          key={'agreement_value'}
          label={'Agreement Value'}
          name={'agreement_value'}
          rules={[{ required: true, message: 'Please Enter a Agreement Amount' }]}
        >
          <InputNumber
            ref={inputRef}
            min={1}
            precision={2}
            max={maxValue}
            style={{ width: '100%' }}
            placeholder="Agreement value"
            addonAfter={convertToShorthand(Number(agreement_value) || 0)}
            onChange={(value) => setLastValue(value)}
            onBlur={handleBlur}
          />
        </Form.Item>
      </Col>

      <Modal
        title="Please Confirm The Agreement Amount"
        open={showModal}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="OK"
        cancelText="Cancel"
      >
        <p>
            You have entered Agreement amount
            <strong className="text-yellow-500 font-semibold">
                &nbsp;₹{convertToShorthand(lastValue!)?.toLocaleString()}
            </strong> Please Confirm!
        </p>
      </Modal>
    </>
  );
}
