import React, { useState } from 'react';
import api from '../api';
import { useNavigate } from 'react-router-dom';

const RecipeForm: React.FC = () => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [ingredients, setIngredients] = useState('');
  const [steps, setSteps] = useState('');
  const [error, setError] = useState('');
  const navigate = useNavigate();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await api.post('/recipes/', { title, description, ingredients, steps });
      navigate('/');
    } catch (err: any) {
      setError(err.response?.data?.detail || 'Failed to create recipe');
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <h2>Create Recipe</h2>
      {error && <p style={{ color: 'red' }}>{error}</p>}
      <div>
        <label>Title:</label>
        <input value={title} onChange={e => setTitle(e.target.value)} required />
      </div>
      <div>
        <label>Description:</label>
        <textarea value={description} onChange={e => setDescription(e.target.value)} />
      </div>
      <div>
        <label>Ingredients:</label>
        <textarea value={ingredients} onChange={e => setIngredients(e.target.value)} required />
      </div>
      <div>
        <label>Steps:</label>
        <textarea value={steps} onChange={e => setSteps(e.target.value)} required />
      </div>
      <button type="submit">Create</button>
    </form>
  );
};

export default RecipeForm;
