import React, { useEffect, useState } from 'react';
import axios from 'axios';

function Product() {
  const [products, setProducts] = useState([]);
  const [productCode, setProductCode] = useState('');
  const [productName, setProductName] = useState('');
  const [quantitySold, setQuantitySold] = useState('');
  const [unitPrice, setUnitPrice] = useState('');
  const [message, setMessage] = useState('');

  const headers = {
    Authorization: `Bearer ${localStorage.getItem('token')}`,
  };

  const clearForm = () => {
    setProductCode('');
    setProductName('');
    setQuantitySold('');
    setUnitPrice('');
  };

  const getProducts = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/product/getproduct', { headers });
      setProducts(res.data);
    } catch (err) {
      console.log(err);
    }
  };

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await axios.post(
        'http://localhost:5001/api/product/addproduct',
        { productCode, productName, quantitySold: Number(quantitySold), unitPrice: Number(unitPrice) },
        { headers }
      );
      setMessage('Product added successfully');
      clearForm();
      getProducts();
    } catch (err) {
      console.error(err);
      setMessage(err.response?.data?.message || 'Failed to save product');
    }
  };

  return (
    <div className="max-w-2xl">
      <h1 className="text-xl font-semibold text-brand-900 mb-1">Products</h1>
      <p className="text-sm text-slate-500 mb-6">Add and manage product records.</p>

      {message && (
        <p className={`mb-4 text-sm ${message.includes('success') ? 'alert-success' : 'alert-error'}`}>
          {message}
        </p>
      )}

      <form onSubmit={handleSubmit} className="card p-5 space-y-3 mb-8">
        <input
          type="text"
          placeholder="Product Code"
          value={productCode}
          onChange={(e) => setProductCode(e.target.value)}
          className="input"
          required
        />
        <input
          type="text"
          placeholder="Product Name"
          value={productName}
          onChange={(e) => setProductName(e.target.value)}
          className="input"
          required
        />
        <div className="grid gap-3 sm:grid-cols-2">
          <input
            type="number"
            placeholder="Quantity Sold"
            value={quantitySold}
            onChange={(e) => setQuantitySold(e.target.value)}
            className="input"
            min="0"
            required
          />
          <input
            type="number"
            placeholder="Unit Price"
            value={unitPrice}
            onChange={(e) => setUnitPrice(e.target.value)}
            className="input"
            min="0"
            step="0.01"
            required
          />
        </div>
        <button type="submit" className="btn-primary">
          Add Product
        </button>
      </form>

      <h2 className="text-sm font-medium text-slate-600 mb-3">Current records</h2>
      {products.length === 0 ? (
        <p className="text-sm text-slate-500">No product records found.</p>
      ) : (
        <div className="space-y-3">
          {products.map((product) => (
            <div key={product._id} className="card p-4">
              <p className="text-xs text-slate-500">Code: {product.productCode}</p>
              <p className="font-medium text-brand-900">{product.productName}</p>
              <p className="text-sm text-slate-600 mt-1">Qty sold: {product.quantitySold}</p>
              <p className="text-sm text-slate-600">Unit price: RWF {product.unitPrice}</p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default Product;
