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

const SellerForm: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [formData, setFormData] = useState({ name: '', contact_email: '' });

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

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const action = id ? axios.put(`http://127.0.0.1:8000/sellers/${id}/`, formData) : axios.post('http://127.0.0.1:8000/sellers/', formData);
    action.then(() => navigate('/admin/sellers'));
  };

  return (
    <div className="p-4">
      <h2 className="text-xl font-bold mb-4">{id ? 'Edit' : 'Create'} Seller</h2>
      <form onSubmit={handleSubmit} className="space-y-4">
        <input className="block w-full p-2 border" placeholder="Name" value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} />
        <input className="block w-full p-2 border" placeholder="Contact Email" value={formData.contact_email} onChange={e => setFormData({...formData, contact_email: e.target.value})} />
        <button type="submit" className="bg-blue-500 text-white p-2 rounded">Save</button>
      </form>
    </div>
  );
};

export default SellerForm;
