import { useEffect, useMemo, useState } from 'react'
import { toast } from 'react-hot-toast'
import { shipmentsApi } from '../services/shipmentsApi.js'
import { suppliersApi } from '../services/suppliersApi.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 SHIPMENT_STATUSES = ['PENDING', 'IN_TRANSIT', 'DELIVERED', 'CANCELLED']

function validateShipment(v) {
  if (!v.shipmentNumber.toString().trim()) return 'shipmentNumber is required'
  if (!v.shipmentDate.trim()) return 'shipmentDate is required'
  if (!v.shipmentStatus.trim()) return 'shipmentStatus is required'
  if (!v.destination.trim()) return 'destination is required'
  if (!v.supplierCode.trim()) return 'supplierCode is required'
  return null
}

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

  const [mode, setMode] = useState('create')
  const [form, setForm] = useState({ shipmentNumber: '', shipmentDate: '', shipmentStatus: '', destination: '', supplierCode: '' })
  const [formError, setFormError] = useState(null)
  const [submitting, setSubmitting] = useState(false)
  const [suppliers, setSuppliers] = useState([])

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

  useEffect(() => {
    let mounted = true
    ;(async () => {
      if (!mounted) return
      await fetchAll()
      try {
        const supData = await suppliersApi.getAll()
        const supArray = (Array.isArray(supData) ? supData : (supData?.data ?? [])).filter(Boolean)
        if (mounted) setSuppliers(supArray)
      } catch {
        // ignore
      }
    })()
    return () => {
      mounted = false
    }

  }, [])



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

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

    setSubmitting(true)
    try {
      if (mode === 'create') {
        await shipmentsApi.create(form)
        toast.success('Shipment created')
      } else {
        await shipmentsApi.update(form.shipmentNumber, form)
        toast.success('Shipment updated')
      }
      setMode('create')
      setForm({ shipmentNumber: '', shipmentDate: '', shipmentStatus: '', destination: '', supplierCode: '' })
      await fetchAll()
    } catch (err) {
      setFormError(err?.message || 'Operation failed')
    } finally {
      setSubmitting(false)
    }
  }

  const onEdit = (row) => {
    setMode('edit')
    setForm({
      shipmentNumber: row.shipmentNumber,
      shipmentDate: row.shipmentDate,
      shipmentStatus: row.shipmentStatus,
      destination: row.destination,
      supplierCode: row.supplierCode,
    })
    setFormError(null)
  }

  const onDelete = async (shipmentNumber) => {
    if (!window.confirm('Delete this shipment?')) return
    try {
      await shipmentsApi.delete(shipmentNumber)
      toast.success('Shipment deleted')
      if (mode === 'edit' && form.shipmentNumber === shipmentNumber) {
        setMode('create')
        setForm({ shipmentNumber: '', shipmentDate: '', shipmentStatus: '', destination: '', supplierCode: '' })
      }
      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">Shipments</h1>
          <p className="mt-1 text-sm text-slate-600">Create, edit, delete and view shipment 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 Shipment' : 'Edit Shipment'}</h2>
            <p className="mt-1 text-sm text-slate-600">{mode === 'create' ? 'Create a new shipment.' : 'Update shipment 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="Shipment Number" value={form.shipmentNumber} onChange={(v) => setForm((s) => ({ ...s, shipmentNumber: v }))} disabled={mode === 'edit'} />
              <Input label="Shipment Date" type="date" value={form.shipmentDate} onChange={(v) => setForm((s) => ({ ...s, shipmentDate: v }))} />
              <Select label="Shipment Status" value={form.shipmentStatus} onChange={(v) => setForm((s) => ({ ...s, shipmentStatus: v }))} placeholder="Select status..." options={SHIPMENT_STATUSES.map((s) => ({ value: s, label: s }))} />
              <Input label="Destination" value={form.destination} onChange={(v) => setForm((s) => ({ ...s, destination: v }))} />
              <Select label="Supplier Code" value={form.supplierCode} onChange={(v) => setForm((s) => ({ ...s, supplierCode: v }))} placeholder="Select supplier..." options={suppliers.map((s) => ({ value: s.supplierCode, label: `${s.supplierCode} - ${s.supplierName}` }))} />

              <div className="flex items-center gap-3">
                <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>
              </div>

              {mode === 'edit' ? (
                <Button
                  type="button"
                  onClick={() => {
                    setMode('create')
                    setForm({ shipmentNumber: '', shipmentDate: '', shipmentStatus: '', destination: '', supplierCode: '' })
                    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">Shipment 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 shipments" description="Create a shipment 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">
                      {['shipmentNumber', 'shipmentDate', 'shipmentStatus', 'destination', 'supplierCode'].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.shipmentNumber} className="hover:bg-slate-50">
                        <td className="px-3 py-3 text-sm font-medium text-slate-900">{row.shipmentNumber}</td>
                        <td className="px-3 py-3 text-sm text-slate-700">{row.shipmentDate}</td>
                        <td className="px-3 py-3 text-sm text-slate-700">{row.shipmentStatus}</td>
                        <td className="px-3 py-3 text-sm text-slate-700">{row.destination}</td>
                        <td className="px-3 py-3 text-sm text-slate-700">{row.supplierCode}</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.shipmentNumber)}
                              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>
  )
}

