import { useState, useEffect, useRef } from 'react';
import { InputField } from '../../../../../Components/Forms/InputField.jsx';
import { Form } from 'antd';
import Buttons from '../../../../../Components/Forms/Buttons.jsx';
import { ArrowRightOutlined } from '@ant-design/icons';

const WeightCalculatePrice = ({ itemData, CartOrderDetails, onSubmit }) => {
  const [enteredPrice, setEnteredPrice] = useState('');
  const [calculatedQty, setCalculatedQty] = useState(0);
  const priceInputRef = useRef(null);
  const [form] = Form.useForm();

  const basePrice = parseFloat(itemData?.OrderRate || itemData?.SellingPrice || 0);

  useEffect(() => {
    setTimeout(() => {
      const inputElement = priceInputRef.current?.querySelector('input');
      if (inputElement) {
        inputElement.focus();
      }
    }, 100);
  }, []);

  // Calculate quantity based on entered price
  const handlePriceChange = (e) => {
    const value = e.target.value;
    setEnteredPrice(value);

    if (value && basePrice > 0) {
      const price = parseFloat(value);
      const qty = price / basePrice;
      setCalculatedQty(qty);
    } else {
      setCalculatedQty(0);
    }
  };

  const handleSubmit = (e) => {
    if (e && e.preventDefault) {
      e.preventDefault();
    }

    if (enteredPrice && calculatedQty > 0) {
      console.log('Submitting weight calculation:', {
        price: parseFloat(enteredPrice),
        quantity: calculatedQty,
      });

      // Pass the calculated values back to parent component
      if (onSubmit) {
        onSubmit({
          price: parseFloat(enteredPrice),
          quantity: calculatedQty,
        });
      }
    }
  };

  return (
    <div className="weight-calculate-price">
      <Form 
        form={form} 
        onFinish={handleSubmit}
        onSubmitCapture={(e) => e.preventDefault()}
      >
        <div className="weight-info">
          <div className="product-details">
            <p><strong>Product:</strong> {itemData?.ProdName}</p>
            <p><strong>Variant:</strong> {itemData?.ProdVariantName}</p>
            <p><strong>Base Price:</strong> ₹{basePrice.toFixed(2)} per {itemData?.UomName || 'unit'}</p>
          </div>
        </div>

        <Form.Item
          name="enteredPrice"
          rules={[
            {
              required: true,
              message: 'Please enter the price',
            },
            {
              pattern: /^[1-9]\d*(\.\d+)?$/,
              message: 'Please enter a valid price',
            },
          ]}
        >
          <InputField
            ref={priceInputRef}
            label="Enter Amount (₹)"
            value={enteredPrice}
            onChange={handlePriceChange}
            autocomplete="off"
            inputMode="decimal"
            placeholder="Enter price amount"
            onInput={(e) => {
              const cleanedValue = e.target.value.replace(/[^0-9.]/g, '');
              const parts = cleanedValue.split('.');
              e.target.value =
                parts.length > 2
                  ? `${parts[0]}.${parts.slice(1).join('')}`
                  : cleanedValue;
            }}
          />
        </Form.Item>

        <div className="calculated-quantity-display">
          <div className="quantity-row">
            <label className="quantity-label">Calculated Quantity:</label>
            <span className="quantity-value">
              {calculatedQty > 0 ? calculatedQty.toFixed(3) : '0.000'} {itemData?.UomName || 'units'}
            </span>
          </div>
          {calculatedQty > 0 && (
            <div className="total-display">
              <label>Total Amount:</label>
              <span>₹{parseFloat(enteredPrice || 0).toFixed(2)}</span>
            </div>
          )}
        </div>
        <div className="submit-button-container">
          <Buttons
            buttonText="Apply"
            color="901D77"
            htmlType="button"
            handleSubmit={handleSubmit}
            icon={<ArrowRightOutlined />}
          />
        </div>
      </Form>
    </div>
  );
};

export default WeightCalculatePrice; 