import { useEffect, useState } from 'react';
import api from '../api/axios';
import PageHeader, { FormCard, Field, Alert, DataTable, StatusPill } from '../components/PageUI';

const initialForm = {
  shipmentNumber: '',
  shipmentDate: '',
  shipmentStatus: 'Pending',
  destination: '',
  supplierCode: '',
};

const statusOptions = ['Pending', 'In Transit', 'Delivered', 'Cancelled'];

export default function Shipment() {
  const [form, setForm] = useState(initialForm);
  const [shipments, setShipments] = useState([]);
  const [suppliers, setSuppliers] = useState([]);
  const [editMode, setEditMode] = useState(false);
  const [message, setMessage] = useState({ type: '', text: '' });
  const [loading, setLoading] = useState(false);

  const fetchData = async () => {
    try {
      const [shipRes, supRes] = await Promise.all([api.get('/shipments'), api.get('/suppliers')]);
      setShipments(shipRes.data);
      setSuppliers(supRes.data);
    } catch {
      setMessage({ type: 'error', text: 'Failed to load data' });
    }
  };

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

  const handleChange = (e) => setForm({ ...form, [e.target.name]: e.target.value });

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setMessage({ type: '', text: '' });
    try {
      if (editMode) {
        await api.put(`/shipments/${form.shipmentNumber}`, form);
        setMessage({ type: 'success', text: 'Shipment updated' });
      } else {
        await api.post('/shipments', form);
        setMessage({ type: 'success', text: 'Shipment added' });
      }
      setForm(initialForm);
      setEditMode(false);
      fetchData();
    } catch (err) {
      setMessage({ type: 'error', text: err.response?.data?.message || 'Operation failed' });
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (s) => {
    setForm({
      shipmentNumber: s.shipmentNumber,
      shipmentDate: s.shipmentDate.split('T')[0],
      shipmentStatus: s.shipmentStatus,
      destination: s.destination,
      supplierCode: s.supplierCode,
    });
    setEditMode(true);
  };

  const handleDelete = async (row) => {
    if (!window.confirm('Delete this shipment?')) return;
    try {
      await api.delete(`/shipments/${row.shipmentNumber}`);
      setMessage({ type: 'success', text: 'Shipment deleted' });
      fetchData();
    } catch (err) {
      setMessage({ type: 'error', text: err.response?.data?.message || 'Delete failed' });
    }
  };

  return (
    <>
      <PageHeader description="Track shipments linked to suppliers." />
      <div className="grid gap-5 xl:grid-cols-5">
        <div className="xl:col-span-2">
          <FormCard
            title={editMode ? 'Update Shipment' : 'Add Shipment'}
            editMode={editMode}
            onSubmit={handleSubmit}
            footer={
              <>
                <button type="submit" disabled={loading} className="btn-primary">
                  {loading ? 'Saving...' : editMode ? 'Update' : 'Add Shipment'}
                </button>
                {editMode && (
                  <button type="button" onClick={() => { setForm(initialForm); setEditMode(false); }} className="btn-secondary">Cancel</button>
                )}
              </>
            }
          >
            <Field label="Shipment Number">
              <input name="shipmentNumber" value={form.shipmentNumber} onChange={handleChange} className="input-field" required readOnly={editMode} />
            </Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="Date">
                <input type="date" name="shipmentDate" value={form.shipmentDate} onChange={handleChange} className="input-field" required />
              </Field>
              <Field label="Status">
                <select name="shipmentStatus" value={form.shipmentStatus} onChange={handleChange} className="input-field" required>
                  {statusOptions.map((s) => <option key={s} value={s}>{s}</option>)}
                </select>
              </Field>
            </div>
            <Field label="Destination">
              <input name="destination" value={form.destination} onChange={handleChange} className="input-field" required />
            </Field>
            <Field label="Supplier">
              <select name="supplierCode" value={form.supplierCode} onChange={handleChange} className="input-field" required>
                <option value="">Select supplier</option>
                {suppliers.map((s) => (
                  <option key={s._id} value={s.supplierCode}>{s.supplierCode} - {s.supplierName}</option>
                ))}
              </select>
            </Field>
            <Alert type={message.type} message={message.text} />
          </FormCard>
        </div>

        <div className="xl:col-span-3">
          <DataTable
            title="All Shipments"
            count={shipments.length}
            columns={[
              { key: 'shipmentNumber', label: 'Number', bold: true },
              { key: 'shipmentDate', label: 'Date', format: (v) => new Date(v).toLocaleDateString() },
              { key: 'shipmentStatus', label: 'Status', format: (v) => <StatusPill status={v} /> },
              { key: 'destination', label: 'Destination' },
            ]}
            data={shipments}
            onEdit={handleEdit}
            onDelete={handleDelete}
          />
        </div>
      </div>
    </>
  );
}
