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

const initialForm = {
  deliveryCode: '',
  deliveryDate: '',
  quantityDelivered: '',
  deliveryStatus: 'Scheduled',
  shipmentNumber: '',
};

const statusOptions = ['Scheduled', 'In Progress', 'Completed', 'Failed'];

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

  const fetchData = async () => {
    try {
      const [delRes, shipRes] = await Promise.all([api.get('/deliveries'), api.get('/shipments')]);
      setDeliveries(delRes.data);
      setShipments(shipRes.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: '' });
    const payload = { ...form, quantityDelivered: Number(form.quantityDelivered) };
    try {
      if (editMode) {
        await api.put(`/deliveries/${form.deliveryCode}`, payload);
        setMessage({ type: 'success', text: 'Delivery updated' });
      } else {
        await api.post('/deliveries', payload);
        setMessage({ type: 'success', text: 'Delivery added' });
      }
      setForm(initialForm);
      setEditMode(false);
      fetchData();
    } catch (err) {
      setMessage({ type: 'error', text: err.response?.data?.message || 'Operation failed' });
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (d) => {
    setForm({
      deliveryCode: d.deliveryCode,
      deliveryDate: d.deliveryDate.split('T')[0],
      quantityDelivered: d.quantityDelivered,
      deliveryStatus: d.deliveryStatus,
      shipmentNumber: d.shipmentNumber,
    });
    setEditMode(true);
  };

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

  return (
    <>
      <PageHeader description="Record deliveries linked to shipments." />
      <div className="grid gap-5 xl:grid-cols-5">
        <div className="xl:col-span-2">
          <FormCard
            title={editMode ? 'Update Delivery' : 'Add Delivery'}
            editMode={editMode}
            onSubmit={handleSubmit}
            footer={
              <>
                <button type="submit" disabled={loading} className="btn-primary">
                  {loading ? 'Saving...' : editMode ? 'Update' : 'Add Delivery'}
                </button>
                {editMode && (
                  <button type="button" onClick={() => { setForm(initialForm); setEditMode(false); }} className="btn-secondary">Cancel</button>
                )}
              </>
            }
          >
            <Field label="Delivery Code">
              <input name="deliveryCode" value={form.deliveryCode} onChange={handleChange} className="input-field" required readOnly={editMode} />
            </Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="Date">
                <input type="date" name="deliveryDate" value={form.deliveryDate} onChange={handleChange} className="input-field" required />
              </Field>
              <Field label="Quantity">
                <input type="number" name="quantityDelivered" value={form.quantityDelivered} onChange={handleChange} className="input-field" min="1" required />
              </Field>
            </div>
            <Field label="Status">
              <select name="deliveryStatus" value={form.deliveryStatus} onChange={handleChange} className="input-field" required>
                {statusOptions.map((s) => <option key={s} value={s}>{s}</option>)}
              </select>
            </Field>
            <Field label="Shipment">
              <select name="shipmentNumber" value={form.shipmentNumber} onChange={handleChange} className="input-field" required>
                <option value="">Select shipment</option>
                {shipments.map((s) => (
                  <option key={s._id} value={s.shipmentNumber}>{s.shipmentNumber} - {s.destination}</option>
                ))}
              </select>
            </Field>
            <Alert type={message.type} message={message.text} />
          </FormCard>
        </div>

        <div className="xl:col-span-3">
          <DataTable
            title="All Deliveries"
            count={deliveries.length}
            columns={[
              { key: 'deliveryCode', label: 'Code', bold: true },
              { key: 'deliveryDate', label: 'Date', format: (v) => new Date(v).toLocaleDateString() },
              { key: 'quantityDelivered', label: 'Qty' },
              { key: 'deliveryStatus', label: 'Status', format: (v) => <StatusPill status={v} /> },
            ]}
            data={deliveries}
            onEdit={handleEdit}
            onDelete={handleDelete}
          />
        </div>
      </div>
    </>
  );
}
