import React, { Component } from 'react';
import { createProduct } from '../../services/ApiProduct';
import { getCategories } from '../../services/ApiCategory';

class ProductForm extends Component {
  state = {
    name: '',
    description: '',
    categoryId: '',
    categories: [],
  };

  componentDidMount() {
    this.fetchCategories();
  }

  fetchCategories = async () => {
    const categories = await getCategories();
    this.setState({ categories });
  };

  handleChange = (event) => {
    this.setState({ [event.target.name]: event.target.value });
  };

  handleSubmit = async (event) => {
    event.preventDefault();
    const { name, description, categoryId } = this.state;
    await createProduct({ name, description, categoryId });
    this.setState({ name: '', description: '', categoryId: '' });
    this.props.fetchProducts();
  };

  render() {
    const { name, description, categoryId, categories } = this.state;

    return (
      <form onSubmit={this.handleSubmit}>
        <input 
          type="text" 
          name="name"
          value={name} 
          onChange={this.handleChange} 
          placeholder="Product Name" 
        />
        <input 
          type="text" 
          name="description"
          value={description} 
          onChange={this.handleChange} 
          placeholder="Product Description" 
        />
        <select name="categoryId" value={categoryId} onChange={this.handleChange}>
          <option value="">Select Category</option>
          {categories.map(category => (
            <option key={category.id} value={category.id}>
              {category.name}
            </option>
          ))}
        </select>
        <button type="submit">Add Product</button>
      </form>
    );
  }
}

export default ProductForm;
