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

function Shipment() {
  const [shipments, setShipments] = useState([]);
  const [suppliers, setSuppliers] = useState([]);
  const [shipmentNumber, setShipmentNumber] = useState('');
  const [shipmentDate, setShipmentDate] = useState('');
  const [shipmentStatus, setShipmentStatus] = useState('Pending');
  const [destination, setDestination] = useState('');
  const [supplierId, setSupplierId] = useState('');
  const [editId, setEditId] = useState(null);
  const [message, setMessage] = useState('');

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

  const clearForm = () => {
    setShipmentNumber('');
    setShipmentDate('');
    setShipmentStatus('Pending');
    setDestination('');
    setSupplierId('');
    setEditId(null);
  };

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

  const loadShipments = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/shipment/getshipments', { headers });
      setShipments(res.data);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    loadSuppliers();
    loadShipments();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editId) {
        await axios.put(
          `http://localhost:5001/api/shipment/updateshipment/${editId}`,
          { shipmentNumber, shipmentDate, shipmentStatus, destination, supplierId },
          { headers }
        );
        setMessage('Shipment updated successfully');
      } else {
        await axios.post(
          'http://localhost:5001/api/shipment/addshipment',
          { shipmentNumber, shipmentDate, shipmentStatus, destination, supplierId },
          { headers }
        );
        setMessage('Shipment added successfully');
      }
      clearForm();
      loadShipments();
    } catch (error) {
      console.error(error);
      setMessage('Failed to save shipment');
    }
  };

  const handleEdit = (shipment) => {
    setShipmentNumber(shipment.shipmentNumber);
    setShipmentDate(shipment.shipmentDate?.split('T')[0] || '');
    setShipmentStatus(shipment.shipmentStatus);
    setDestination(shipment.destination);
    setSupplierId(shipment.supplier?._id || '');
    setEditId(shipment._id);
  };

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

  return (
    <div className="page-content">
      <h1 className="page-title">Shipment Management</h1>
      <p className="page-subtitle">Track and manage shipments</p>

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

      <form onSubmit={handleSubmit} className="form-card">
        <input
          type="text"
          placeholder="Shipment Number"
          value={shipmentNumber}
          onChange={(e) => setShipmentNumber(e.target.value)}
          className="input"
          required
        />
        <input
          type="date"
          value={shipmentDate}
          onChange={(e) => setShipmentDate(e.target.value)}
          className="input"
          required
        />
        <input
          type="text"
          placeholder="Destination"
          value={destination}
          onChange={(e) => setDestination(e.target.value)}
          className="input"
          required
        />
        <select
          value={shipmentStatus}
          onChange={(e) => setShipmentStatus(e.target.value)}
          className="input"
          required
        >
          <option value="Pending">Pending</option>
          <option value="In Transit">In Transit</option>
          <option value="Delivered">Delivered</option>
        </select>
        <select
          value={supplierId}
          onChange={(e) => setSupplierId(e.target.value)}
          className="input"
        >
          <option value="">Select supplier (optional)</option>
          {suppliers.map((supplier) => (
            <option key={supplier._id} value={supplier._id}>
              {supplier.supplierCode} - {supplier.supplierName}
            </option>
          ))}
        </select>
        <button type="submit" className="btn-primary">
          {editId ? 'Update Shipment' : 'Add Shipment'}
        </button>
      </form>

      <div className="space-y-3">
        {shipments.length === 0 ? (
          <p className="text-sm text-muted">No shipment records available.</p>
        ) : (
          shipments.map((shipment) => (
            <div key={shipment._id} className="list-card">
              <p className="text-sm font-medium text-brand-800">{shipment.shipmentNumber}</p>
              <p className="text-sm text-muted">Date: {shipment.shipmentDate?.split('T')[0]}</p>
              <p className="text-sm text-muted">Destination: {shipment.destination}</p>
              <p className="text-sm text-muted">Status: {shipment.shipmentStatus}</p>
              <p className="text-sm text-muted">
                Supplier: {shipment.supplier ? shipment.supplier.supplierName : 'Not assigned'}
              </p>
              <div className="flex gap-4 pt-2">
                <button type="button" onClick={() => handleEdit(shipment)} className="btn-ghost">
                  Edit
                </button>
                <button type="button" onClick={() => handleDelete(shipment._id)} className="btn-danger">
                  Delete
                </button>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

export default Shipment;
