import { useEffect, useMemo, useState } from 'react'
import { toast } from 'react-hot-toast'
import { deliveriesApi } from '../services/deliveriesApi.js'
import { shipmentsApi } from '../services/shipmentsApi.js'
import { Button } from '../components/Button.jsx'
import { Input } from '../components/Input.jsx'
import { Select } from '../components/Select.jsx'
import { Alert } from '../components/Alert.jsx'
import { EmptyState } from '../components/EmptyState.jsx'

const DELIVERY_STATUSES = ['PENDING', 'IN_TRANSIT', 'DELIVERED', 'CANCELLED']

function validateDelivery(v) {
  if (!v.deliveryCode.trim()) return 'deliveryCode is required'
  if (!v.deliveryDate.trim()) return 'deliveryDate is required'
  if (v.quantityDelivered === '' || v.quantityDelivered === null) return 'quantityDelivered is required'
  if (!v.deliveryStatus.trim()) return 'deliveryStatus is required'
  if (!v.shipmentNumber.toString().trim()) return 'shipmentNumber is required'
  return null
}

export default function DeliveriesPage() {
  const [items, setItems] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  const [mode, setMode] = useState('create')
  const [form, setForm] = useState({ deliveryCode: '', deliveryDate: '', quantityDelivered: '', deliveryStatus: '', shipmentNumber: '' })
  const [formError, setFormError] = useState(null)
  const [submitting, setSubmitting] = useState(false)
  const [shipments, setShipments] = useState([])

  const fetchAll = async () => {
    setError(null)
    setLoading(true)
    try {
      const data = await deliveriesApi.getAll()
      setItems(Array.isArray(data) ? data : (data?.data ?? []))
    } catch (e) {
      setError(e?.message || 'Failed to load deliveries')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    let mounted = true
    ;(async () => {
      if (!mounted) return
      await fetchAll()
      try {
        const shpData = await shipmentsApi.getAll()
        const shpArray = Array.isArray(shpData) ? shpData : (shpData?.data ?? [])
        if (mounted) setShipments(shpArray)
      } catch {
        // ignore
      }
    })()
    return () => {
      mounted = false
    }

  }, [])



  const total = useMemo(() => items.length, [items])

  const onCreateOrUpdate = async (e) => {
    e.preventDefault()
    setFormError(null)
    const v = validateDelivery(form)
    if (v) {
      setFormError(v)
      return
    }

    setSubmitting(true)
    try {
      if (mode === 'create') {
        await deliveriesApi.create({ ...form, quantityDelivered: Number(form.quantityDelivered) })
        toast.success('Delivery created')
      } else {
        await deliveriesApi.update(form.deliveryCode, { ...form, quantityDelivered: Number(form.quantityDelivered) })
        toast.success('Delivery updated')
      }
      setMode('create')
      setForm({ deliveryCode: '', deliveryDate: '', quantityDelivered: '', deliveryStatus: '', shipmentNumber: '' })
      await fetchAll()
    } catch (err) {
      setFormError(err?.message || 'Operation failed')
    } finally {
      setSubmitting(false)
    }
  }

  const onEdit = (row) => {
    setMode('edit')
    setForm({
      deliveryCode: row.deliveryCode,
      deliveryDate: row.deliveryDate,
      quantityDelivered: row.quantityDelivered,
      deliveryStatus: row.deliveryStatus,
      shipmentNumber: row.shipmentNumber,
    })
    setFormError(null)
  }

  const onDelete = async (deliveryCode) => {
    if (!window.confirm('Delete this delivery?')) return
    try {
      await deliveriesApi.delete(deliveryCode)
      toast.success('Delivery deleted')
      if (mode === 'edit' && form.deliveryCode === deliveryCode) {
        setMode('create')
        setForm({ deliveryCode: '', deliveryDate: '', quantityDelivered: '', deliveryStatus: '', shipmentNumber: '' })
      }
      await fetchAll()
    } catch (err) {
      toast.error(err?.message || 'Delete failed')
    }
  }

  return (
    <div className="space-y-5">
      <div className="flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Deliveries</h1>
          <p className="mt-1 text-sm text-slate-600">Create, edit, delete and view delivery records.</p>
        </div>
        <div className="rounded-2xl bg-white border border-slate-200 px-4 py-3 text-sm text-slate-700 shadow-sm">
          Total: <span className="font-bold text-slate-900">{total}</span>
        </div>
      </div>

      {error ? <Alert type="error" message={error} /> : null}

      <div className="grid gap-5 lg:grid-cols-5">
        <div className="lg:col-span-2">
          <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
            <h2 className="text-base font-bold text-slate-900">{mode === 'create' ? 'Add Delivery' : 'Edit Delivery'}</h2>
            <p className="mt-1 text-sm text-slate-600">{mode === 'create' ? 'Create a new delivery.' : 'Update delivery details.'}</p>

            {formError ? (
              <div className="mt-4"><Alert type="error" message={formError} /></div>
            ) : null}

            <form className="mt-4 space-y-4" onSubmit={onCreateOrUpdate}>
              <Input label="Delivery Code" value={form.deliveryCode} onChange={(v) => setForm((s) => ({ ...s, deliveryCode: v }))} disabled={mode === 'edit'} />
              <Input label="Delivery Date" type="date" value={form.deliveryDate} onChange={(v) => setForm((s) => ({ ...s, deliveryDate: v }))} />
              <Input label="Quantity Delivered" value={form.quantityDelivered} onChange={(v) => setForm((s) => ({ ...s, quantityDelivered: v }))} placeholder="e.g. 150" />
              <Select label="Delivery Status" value={form.deliveryStatus} onChange={(v) => setForm((s) => ({ ...s, deliveryStatus: v }))} placeholder="Select status..." options={DELIVERY_STATUSES.map((s) => ({ value: s, label: s }))} />
              <Select label="Shipment Number" value={form.shipmentNumber} onChange={(v) => setForm((s) => ({ ...s, shipmentNumber: v }))} placeholder="Select shipment..." options={shipments.map((s) => ({ value: s.shipmentNumber, label: `${s.shipmentNumber} - ${s.destination}` }))} />

              <Button type="submit" disabled={submitting} className="w-full">
                {submitting ? (
                  <span className="inline-flex items-center gap-2"><span className="h-4 w-4 animate-spin rounded-full border-2 border-white/60 border-t-white" /> Saving…</span>
                ) : (
                  mode === 'create' ? 'Create' : 'Save'
                )}
              </Button>

              {mode === 'edit' ? (
                <Button
                  type="button"
                  onClick={() => {
                    setMode('create')
                    setForm({ deliveryCode: '', deliveryDate: '', quantityDelivered: '', deliveryStatus: '', shipmentNumber: '' })
                    setFormError(null)
                  }}
                  className="w-full bg-white text-slate-900 hover:bg-slate-100 border border-slate-200"
                >
                  Cancel
                </Button>
              ) : null}
            </form>
          </div>
        </div>

        <div className="lg:col-span-3">
          <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
            <h2 className="text-base font-bold text-slate-900">Delivery Table</h2>

            {loading ? (
              <div className="mt-6 flex items-center justify-center">
                <div className="h-8 w-8 animate-spin rounded-full border-2 border-slate-300 border-t-slate-900" />
              </div>
            ) : items.length === 0 ? (
              <div className="mt-6">
                <EmptyState title="No deliveries" description="Create a delivery to see it here." actionLabel="Refresh" onAction={fetchAll} />
              </div>
            ) : (
              <div className="mt-4 overflow-x-auto">
                <table className="min-w-full divide-y divide-slate-200">
                  <thead>
                    <tr className="bg-slate-50">
                      {['deliveryCode', 'deliveryDate', 'quantityDelivered', 'deliveryStatus', 'shipmentNumber'].map((h) => (
                        <th key={h} className="px-3 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
                          {h}
                        </th>
                      ))}
                      <th className="px-3 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-200">
                    {items.map((row) => (
                      <tr key={row.deliveryCode} className="hover:bg-slate-50">
                        <td className="px-3 py-3 text-sm font-medium text-slate-900">{row.deliveryCode}</td>
                        <td className="px-3 py-3 text-sm text-slate-700">{row.deliveryDate}</td>
                        <td className="px-3 py-3 text-sm text-slate-700">{row.quantityDelivered}</td>
                        <td className="px-3 py-3 text-sm text-slate-700">{row.deliveryStatus}</td>
                        <td className="px-3 py-3 text-sm text-slate-700">{row.shipmentNumber}</td>
                        <td className="px-3 py-3 text-sm">
                          <div className="flex flex-wrap gap-2">
                            <Button type="button" onClick={() => onEdit(row)} className="!bg-white !text-slate-900 !shadow-none !hover:bg-slate-100 !border !border-slate-200 !px-3 !py-1.5">
                              Edit
                            </Button>
                            <Button
                              type="button"
                              onClick={() => onDelete(row.deliveryCode)}
                              className="!bg-red-600 !text-white !shadow-none !hover:bg-red-500 !px-3 !py-1.5"
                            >
                              Delete
                            </Button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

