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

function Delivery() {
  const [deliveries, setDeliveries] = useState([]);
  const [shipments, setShipments] = useState([]);
  const [deliveryCode, setDeliveryCode] = useState('');
  const [deliveryDate, setDeliveryDate] = useState('');
  const [quantityDelivered, setQuantityDelivered] = useState('');
  const [deliveryStatus, setDeliveryStatus] = useState('Pending');
  const [shipmentId, setShipmentId] = useState('');
  const [editId, setEditId] = useState(null);
  const [message, setMessage] = useState('');

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

  const clearForm = () => {
    setDeliveryCode('');
    setDeliveryDate('');
    setQuantityDelivered('');
    setDeliveryStatus('Pending');
    setShipmentId('');
    setEditId(null);
  };

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

  const loadDeliveries = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/delivery/getdeliveries', { headers });
      setDeliveries(res.data);
    } catch (error) {
      console.error(error);
    }
  };

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editId) {
        await axios.put(
          `http://localhost:5001/api/delivery/updatedelivery/${editId}`,
          { deliveryCode, deliveryDate, quantityDelivered, deliveryStatus, shipmentId },
          { headers }
        );
        setMessage('Delivery updated successfully');
      } else {
        await axios.post(
          'http://localhost:5001/api/delivery/adddelivery',
          { deliveryCode, deliveryDate, quantityDelivered, deliveryStatus, shipmentId },
          { headers }
        );
        setMessage('Delivery added successfully');
      }
      clearForm();
      loadDeliveries();
    } catch (error) {
      console.error(error);
      setMessage('Failed to save delivery');
    }
  };

  const handleEdit = (delivery) => {
    setDeliveryCode(delivery.deliveryCode);
    setDeliveryDate(delivery.deliveryDate?.split('T')[0] || '');
    setQuantityDelivered(delivery.quantityDelivered);
    setDeliveryStatus(delivery.deliveryStatus);
    setShipmentId(delivery.shipment?._id || '');
    setEditId(delivery._id);
  };

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

  return (
    <div className="page-content">
      <h1 className="page-title">Delivery Management</h1>
      <p className="page-subtitle">Record and track deliveries</p>

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

      <form onSubmit={handleSubmit} className="form-card">
        <input
          type="text"
          placeholder="Delivery Code"
          value={deliveryCode}
          onChange={(e) => setDeliveryCode(e.target.value)}
          className="input"
          required
        />
        <input
          type="date"
          value={deliveryDate}
          onChange={(e) => setDeliveryDate(e.target.value)}
          className="input"
          required
        />
        <input
          type="number"
          placeholder="Quantity Delivered"
          value={quantityDelivered}
          onChange={(e) => setQuantityDelivered(e.target.value)}
          className="input"
          required
        />
        <select
          value={deliveryStatus}
          onChange={(e) => setDeliveryStatus(e.target.value)}
          className="input"
          required
        >
          <option value="Pending">Pending</option>
          <option value="Delivered">Delivered</option>
          <option value="Returned">Returned</option>
        </select>
        <select
          value={shipmentId}
          onChange={(e) => setShipmentId(e.target.value)}
          className="input"
          required
        >
          <option value="">Select shipment</option>
          {shipments.map((shipment) => (
            <option key={shipment._id} value={shipment._id}>
              {shipment.shipmentNumber} - {shipment.destination}
            </option>
          ))}
        </select>
        <button type="submit" className="btn-primary">
          {editId ? 'Update Delivery' : 'Add Delivery'}
        </button>
      </form>

      <div className="space-y-3">
        {deliveries.length === 0 ? (
          <p className="text-sm text-muted">No delivery records yet.</p>
        ) : (
          deliveries.map((delivery) => (
            <div key={delivery._id} className="list-card">
              <p className="text-sm font-medium text-brand-800">{delivery.deliveryCode}</p>
              <p className="text-sm text-muted">Date: {delivery.deliveryDate?.split('T')[0]}</p>
              <p className="text-sm text-muted">Quantity: {delivery.quantityDelivered}</p>
              <p className="text-sm text-muted">Status: {delivery.deliveryStatus}</p>
              <p className="text-sm text-muted">
                Shipment: {delivery.shipment ? delivery.shipment.shipmentNumber : 'Unassigned'}
              </p>
              <div className="flex gap-4 pt-2">
                <button type="button" onClick={() => handleEdit(delivery)} className="btn-ghost">
                  Edit
                </button>
                <button type="button" onClick={() => handleDelete(delivery._id)} className="btn-danger">
                  Delete
                </button>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

export default Delivery;
