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

function Supplier() {
  const [suppliers, setSuppliers] = useState([]);
  const [supplierCode, setSupplierCode] = useState('');
  const [supplierName, setSupplierName] = useState('');
  const [address, setAddress] = useState('');
  const [telephone, setTelephone] = useState('');
  const [email, setEmail] = useState('');
  const [editId, setEditId] = useState(null);
  const [message, setMessage] = useState('');

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

  const clearForm = () => {
    setSupplierCode('');
    setSupplierName('');
    setAddress('');
    setTelephone('');
    setEmail('');
    setEditId(null);
  };

  const handleGet = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/supplier/getsupplier', { headers });
      setSuppliers(res.data);
    } catch (error) {
      console.log(error);
    }
  };

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

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      if (editId) {
        await axios.put(
          `http://localhost:5001/api/supplier/updatesupplier/${editId}`,
          { supplierCode, supplierName, address, telephone, email },
          { headers }
        );
        setMessage('Updated successfully');
      } else {
        await axios.post(
          'http://localhost:5001/api/supplier/addsupplier',
          { supplierCode, supplierName, address, telephone, email },
          { headers }
        );
        setMessage('Added successfully');
      }

      clearForm();
      handleGet();
    } catch (error) {
      console.log(error);
      setMessage('Something went wrong');
    }
  };

  const handleDelete = async (id) => {
    try {
      await axios.delete(`http://localhost:5001/api/supplier/deletesupplier/${id}`, { headers });
      handleGet();
    } catch (error) {
      console.log(error);
    }
  };

  const handleEdit = (supplier) => {
    setSupplierCode(supplier.supplierCode);
    setSupplierName(supplier.supplierName);
    setAddress(supplier.address);
    setTelephone(supplier.telephone);
    setEmail(supplier.email);
    setEditId(supplier._id);
  };

  return (
    <div className="page-content">
      <h1 className="page-title">Supplier Management</h1>
      <p className="page-subtitle">Add and manage supplier records</p>

      {message && <p className="alert-success">{message}</p>}

      <form onSubmit={handleSubmit} className="form-card">
        <input
          type="text"
          placeholder="Supplier Code"
          value={supplierCode}
          onChange={(e) => setSupplierCode(e.target.value)}
          className="input"
          required
        />
        <input
          type="text"
          placeholder="Supplier Name"
          value={supplierName}
          onChange={(e) => setSupplierName(e.target.value)}
          className="input"
          required
        />
        <input
          type="text"
          placeholder="Address"
          value={address}
          onChange={(e) => setAddress(e.target.value)}
          className="input"
          required
        />
        <input
          type="text"
          placeholder="Telephone"
          value={telephone}
          onChange={(e) => setTelephone(e.target.value)}
          className="input"
          required
        />
        <input
          type="email"
          placeholder="Email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          className="input"
          required
        />
        <button type="submit" className="btn-primary">
          {editId ? 'Update' : 'Add Supplier'}
        </button>
      </form>

      <div className="space-y-3">
        {suppliers.length === 0 ? (
          <p className="text-sm text-muted">No suppliers yet.</p>
        ) : (
          suppliers.map((supplier) => (
            <div key={supplier._id} className="list-card">
              <p className="text-sm font-medium text-brand-800">{supplier.supplierName}</p>
              <p className="text-sm text-muted">Code: {supplier.supplierCode}</p>
              <p className="text-sm text-muted">{supplier.address}</p>
              <p className="text-sm text-muted">{supplier.telephone} · {supplier.email}</p>
              <div className="flex gap-4 pt-2">
                <button type="button" onClick={() => handleEdit(supplier)} className="btn-ghost">
                  Edit
                </button>
                <button type="button" onClick={() => handleDelete(supplier._id)} className="btn-danger">
                  Delete
                </button>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

export default Supplier;
