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

interface Seller {
  id: number;
  name: string;
  contact_email: string;
}

const SellerManagement: React.FC = () => {
  const [sellers, setSellers] = useState<Seller[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    fetchSellers();
  }, []);

  const fetchSellers = () => {
    axios.get('http://127.0.0.1:8000/sellers/')
      .then(response => {
        setSellers(response.data);
        setLoading(false);
      })
      .catch(error => {
        console.error('Error fetching sellers:', error);
        setLoading(false);
      });
  };

  const deleteSeller = (id: number) => {
    if (window.confirm('Are you sure you want to delete this seller?')) {
        axios.delete(`http://127.0.0.1:8000/sellers/${id}/`)
            .then(() => fetchSellers())
            .catch(error => console.error('Error deleting seller:', error));
    }
  };

  if (loading) return <div className="text-center p-4">Loading...</div>;

  return (
    <div className="p-4">
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-xl font-bold">Seller Management</h2>
        <Link to="/admin/sellers/create" className="bg-green-500 text-white px-4 py-2 rounded">Create Seller</Link>
      </div>
      <table className="min-w-full bg-white border border-gray-200">
        <thead>
          <tr>
            <th className="py-2 px-4 border-b">ID</th>
            <th className="py-2 px-4 border-b">Name</th>
            <th className="py-2 px-4 border-b">Contact</th>
            <th className="py-2 px-4 border-b">Actions</th>
          </tr>
        </thead>
        <tbody>
          {sellers.map(seller => (
            <tr key={seller.id}>
              <td className="py-2 px-4 border-b">{seller.id}</td>
              <td className="py-2 px-4 border-b">{seller.name}</td>
              <td className="py-2 px-4 border-b">{seller.contact_email}</td>
              <td className="py-2 px-4 border-b space-x-2">
                <Link to={`/admin/sellers/edit/${seller.id}`} className="bg-blue-500 text-white px-2 py-1 rounded">Edit</Link>
                <button 
                  onClick={() => deleteSeller(seller.id)}
                  className="bg-red-500 text-white px-2 py-1 rounded"
                >
                  Delete
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default SellerManagement;