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

function validateSupplier(v) {
  if (!v.supplierCode.trim()) return 'supplierCode is required'
  if (!v.supplierName.trim()) return 'supplierName is required'
  if (!v.telephone.trim()) return 'telephone is required'
  if (!v.address.trim()) return 'address is required'
  if (!v.email.trim()) return 'email is required'
  if (!/^\S+@\S+\.\S+$/.test(v.email.trim())) return 'email must be valid'
  return null
}

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

  const [form, setForm] = useState({ supplierCode: '', supplierName: '', telephone: '', address: '', email: '' })
  const [formError, setFormError] = useState(null)

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

  useEffect(() => {
    let mounted = true
    ;(async () => {
      if (!mounted) return
      await fetchAll()
    })()
    return () => {
      mounted = false
    }

  }, [])



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

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

    setSubmitting(true)
    try {
      await suppliersApi.create(form)
      toast.success('Supplier created')
      setForm({ supplierCode: '', supplierName: '', telephone: '', address: '', email: '' })
      await fetchAll()
    } catch (err) {
      setFormError(err?.message || 'Failed to create supplier')
    } finally {
      setSubmitting(false)
    }
  }

  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">Suppliers</h1>
          <p className="mt-1 text-sm text-slate-600">Add suppliers and view existing 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">Add Supplier</h2>
            <p className="mt-1 text-sm text-slate-600">Create a supplier profile.</p>

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

            <form className="mt-4 space-y-4" onSubmit={onCreate}>
              <Input label="Supplier Code" value={form.supplierCode} onChange={(v) => setForm((s) => ({ ...s, supplierCode: v }))} />
              <Input label="Supplier Name" value={form.supplierName} onChange={(v) => setForm((s) => ({ ...s, supplierName: v }))} />
              <Input label="Telephone" value={form.telephone} onChange={(v) => setForm((s) => ({ ...s, telephone: v }))} />
              <Input label="Address" value={form.address} onChange={(v) => setForm((s) => ({ ...s, address: v }))} />
              <Input label="Email" value={form.email} onChange={(v) => setForm((s) => ({ ...s, email: v }))} />

              <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" /> Creating…</span>
                ) : (
                  'Create'
                )}
              </Button>
            </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">Supplier List</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 suppliers" description="Create your first supplier to get started." 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">
                      {['supplierCode', 'supplierName', 'telephone', 'address', 'email'].map((h) => (
                        <th key={h} className="px-3 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
                          {h}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-200 bg-white">
                    {items.map((s) => (
                      <tr key={s.supplierCode}>
                        <td className="px-3 py-3 text-sm text-slate-900">{s.supplierCode}</td>
                        <td className="px-3 py-3 text-sm text-slate-900">{s.supplierName}</td>
                        <td className="px-3 py-3 text-sm text-slate-700">{s.telephone}</td>
                        <td className="px-3 py-3 text-sm text-slate-700">{s.address}</td>
                        <td className="px-3 py-3 text-sm text-slate-700">{s.email}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

