import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useNavigate, useParams } from 'react-router-dom';

const ProductForm: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [formData, setFormData] = useState({ name: '', price: '', description: '', category: '', image: null as File | null });
  const [categories, setCategories] = useState<{ id: number; name: string }[]>([]);

  useEffect(() => {
    axios.get('http://127.0.0.1:8000/categories/')
      .then(res => setCategories(res.data));

    if (id) {
      axios.get(`http://127.0.0.1:8000/products/${id}/`)
        .then(res => setFormData(res.data));
    }
  }, [id]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const data = new FormData();
    data.append('name', formData.name);
    data.append('price', formData.price);
    data.append('description', formData.description);
    data.append('category', formData.category);
    if (formData.image) data.append('image', formData.image);

    const action = id ? axios.put(`http://127.0.0.1:8000/products/${id}/`, data, { headers: { 'Content-Type': 'multipart/form-data' } }) 
                      : axios.post('http://127.0.0.1:8000/products/', data, { headers: { 'Content-Type': 'multipart/form-data' } });
    
    action.then(() => navigate('/admin/products'));
  };

  return (
    <div className="p-4 bg-white rounded shadow-md">
      <h2 className="text-2xl font-bold mb-4">{id ? 'Edit' : 'Create'} Product</h2>
      <form onSubmit={handleSubmit} className="space-y-4">
        <input className="block w-full p-2 border rounded" placeholder="Name" value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} />
        <input className="block w-full p-2 border rounded" placeholder="Price" value={formData.price} onChange={e => setFormData({...formData, price: e.target.value})} />
        <textarea className="block w-full p-2 border rounded" placeholder="Description" value={formData.description} onChange={e => setFormData({...formData, description: e.target.value})} />
        <select className="block w-full p-2 border rounded" value={formData.category} onChange={e => setFormData({...formData, category: e.target.value})}>
          <option value="">Select Category</option>
          {categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
        </select>
        <input type="file" onChange={e => setFormData({...formData, image: e.target.files ? e.target.files[0] : null})} className="block w-full p-2 border rounded" />
        <button type="submit" className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 transition">Save Product</button>
      </form>
    </div>
  );
};

export default ProductForm;