import React, { useState, useEffect } from 'react'
import { Form, Input, Button, Space, Select, InputNumber } from 'antd'
import axios from 'axios'
import PropTypes from 'prop-types'
import config from '../../../../config'

const NewPartStock = ({ onOk, reset }) => {
  const [form] = Form.useForm()
  const [parts, setParts] = useState([])
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    // Reset form when reset prop changes
    if (reset) {
      form.resetFields()
    }
  }, [reset, form])

  useEffect(() => {
    // Fetch parts for the select dropdown
    const fetchParts = async () => {
      try {
        const response = await axios.get(`${config.backendUrl}/parts`, {
          headers: {
            Accept: 'application/json'
          },
          withCredentials: true
        })
        setParts(response.data)
      } catch (error) {
        console.error('Error fetching parts:', error)
      }
    }

    fetchParts()
  }, [])

  const onFinish = async (values) => {
    setLoading(true)
    try {
      await axios.post(
        `${config.backendUrl}/partstocks`,
        {
          part: values.part,
          startingLots: values.startingLots,
          currentLots: values.startingLots, // Initially current lots equals starting lots
          notes: values.notes
        },
        {
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
          },
          withCredentials: true
        }
      )
      onOk()
    } catch (error) {
      console.error('Error creating part stock:', error)
    } finally {
      setLoading(false)
    }
  }

  return (
    <Form
      form={form}
      layout='vertical'
      onFinish={onFinish}
      style={{ maxWidth: '100%' }}
    >
      <Form.Item
        name='part'
        label='Part'
        rules={[{ required: true, message: 'Please select a part' }]}
      >
        <Select
          placeholder='Select a part'
          options={parts.map((part) => ({
            value: part._id,
            label: part.name
          }))}
        />
      </Form.Item>

      <Form.Item
        name='startingLots'
        label='Starting Lots'
        rules={[
          { required: true, message: 'Please enter the starting lots' },
          { type: 'number', min: 1, message: 'Lots must be at least 1' }
        ]}
      >
        <InputNumber
          style={{ width: '100%' }}
          placeholder='Enter starting lots'
          min={1}
        />
      </Form.Item>

      <Form.Item name='notes' label='Notes'>
        <Input.TextArea
          placeholder='Enter any additional notes'
          autoSize={{ minRows: 3, maxRows: 6 }}
        />
      </Form.Item>

      <Form.Item>
        <Space>
          <Button type='primary' htmlType='submit' loading={loading}>
            Create Part Stock
          </Button>
          <Button onClick={() => form.resetFields()}>Reset</Button>
        </Space>
      </Form.Item>
    </Form>
  )
}

NewPartStock.propTypes = {
  onOk: PropTypes.func.isRequired,
  reset: PropTypes.bool
}

NewPartStock.defaultProps = {
  reset: false
}

export default NewPartStock
