import { useEffect, useMemo, useState } from 'react'
import { toast } from 'react-hot-toast'
import { createProduct, getAllProducts, getProductById } from '../services/productsService'

import Modal from '../components/common/Modal'
import { validateProductForm } from '../utils/validators'
import TableShell from '../components/common/TableShell'

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

  const [form, setForm] = useState({
    productCode: '',
    productName: '',
    category: '',
    quantityInStock: 0,
    unitPrice: 0,
    supplierName: '',
    dateReceived: '',
  })
  const [formErrors, setFormErrors] = useState({})
  const [submitting, setSubmitting] = useState(false)

  const [detailsOpen, setDetailsOpen] = useState(false)
  const [details, setDetails] = useState(null)
  const [detailsLoading, setDetailsLoading] = useState(false)

  useEffect(() => {
    const run = async () => {
      try {
        setLoading(true)
        const data = await getAllProducts()
        setItems(Array.isArray(data) ? data : [])
      } catch (err) {
        setError(err?.message || 'Failed to load products')
        toast.error(err?.message || 'Failed to load products')
      } finally {
        setLoading(false)
      }
    }
    run()
  }, [])

  const columns = useMemo(
    () => [
      { header: 'Code', accessor: (p) => p.productCode },
      { header: 'Name', accessor: (p) => p.productName },
      { header: 'Category', accessor: (p) => p.category },
      { header: 'In Stock', accessor: (p) => p.quantityInStock },
      { header: 'Unit Price', accessor: (p) => p.unitPrice },
    ],
    [],
  )

  return (
    <div>
      <div className="flex items-start justify-between gap-4 mb-4">
        <div>
          <h2 className="text-2xl font-semibold">Products</h2>
          <p className="text-sm text-slate-400 mt-1">Add products, browse inventory and view details.</p>
        </div>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-5 gap-4">
        <div className="xl:col-span-2">
          <div className="rounded-2xl border border-white/10 bg-white/5 p-4 sticky top-4">
            <div className="text-sm font-semibold">Add Product</div>
            <div className="text-xs text-slate-400 mt-1 mb-4">All fields are required.</div>

            <form
              onSubmit={async (e) => {
                e.preventDefault()
                const nextErrors = validateProductForm(form)
                setFormErrors(nextErrors)
                if (Object.keys(nextErrors).length > 0) return

                setSubmitting(true)
                try {
                  await createProduct({
                    ...form,
                    quantityInStock: Number(form.quantityInStock),
                    unitPrice: Number(form.unitPrice),
                    dateReceived: form.dateReceived,
                  })
                  toast.success('Product created')

                  const data = await getAllProducts()
                  setItems(Array.isArray(data) ? data : [])

                  setForm({
                    productCode: '',
                    productName: '',
                    category: '',
                    quantityInStock: 0,
                    unitPrice: 0,
                    supplierName: '',
                    dateReceived: '',
                  })
                  setFormErrors({})
                } catch (err) {
                  toast.error(err?.message || 'Failed to create product')
                } finally {
                  setSubmitting(false)
                }
              }}
              className="space-y-3"
            >
              <Field label="Product Code" error={formErrors.productCode}>
                <input
                  className="w-full rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-sm outline-none focus:border-fuchsia-400/60"
                  value={form.productCode}
                  onChange={(e) => setForm((s) => ({ ...s, productCode: e.target.value }))}
                />
              </Field>

              <Field label="Product Name" error={formErrors.productName}>
                <input
                  className="w-full rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-sm outline-none focus:border-fuchsia-400/60"
                  value={form.productName}
                  onChange={(e) => setForm((s) => ({ ...s, productName: e.target.value }))}
                />
              </Field>

              <Field label="Category" error={formErrors.category}>
                <input
                  className="w-full rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-sm outline-none focus:border-fuchsia-400/60"
                  value={form.category}
                  onChange={(e) => setForm((s) => ({ ...s, category: e.target.value }))}
                />
              </Field>

              <div className="grid grid-cols-2 gap-3">
                <Field label="Qty In Stock" error={formErrors.quantityInStock}>
                  <input
                    type="number"
                    className="w-full rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-sm outline-none focus:border-fuchsia-400/60"
                    value={form.quantityInStock}
                    onChange={(e) => setForm((s) => ({ ...s, quantityInStock: e.target.value }))}
                  />
                </Field>
                <Field label="Unit Price" error={formErrors.unitPrice}>
                  <input
                    type="number"
                    className="w-full rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-sm outline-none focus:border-fuchsia-400/60"
                    value={form.unitPrice}
                    onChange={(e) => setForm((s) => ({ ...s, unitPrice: e.target.value }))}
                  />
                </Field>
              </div>

              <Field label="Supplier Name" error={formErrors.supplierName}>
                <input
                  className="w-full rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-sm outline-none focus:border-fuchsia-400/60"
                  value={form.supplierName}
                  onChange={(e) => setForm((s) => ({ ...s, supplierName: e.target.value }))}
                />
              </Field>

              <Field label="Date Received" error={formErrors.dateReceived}>
                <input
                  type="date"
                  className="w-full rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-sm outline-none focus:border-fuchsia-400/60"
                  value={form.dateReceived}
                  onChange={(e) => setForm((s) => ({ ...s, dateReceived: e.target.value }))}
                />
              </Field>

              <button
                type="submit"
                disabled={submitting}
                className="w-full rounded-xl bg-gradient-to-r from-purple-500 to-fuchsia-500 text-white py-2.5 text-sm font-semibold shadow-lg hover:opacity-95 disabled:opacity-60 disabled:cursor-not-allowed transition"
              >
                {submitting ? 'Creating...' : 'Create Product'}
              </button>

              {error ? <div className="text-xs text-red-300">{error}</div> : null}
            </form>
          </div>
        </div>

        <div className="xl:col-span-3">
          <div className="rounded-2xl border border-white/10 bg-white/5 p-4">
            <div className="flex items-center justify-between gap-3 mb-4">
              <div>
                <div className="text-sm font-semibold">Product List</div>
                <div className="text-xs text-slate-400 mt-1">Search, paginate and view details.</div>
              </div>
            </div>

            <TableShell
              items={items}
              loading={loading}
              columns={columns}
              searchKeys={['productCode', 'productName', 'category', 'supplierName']}
              rowAction={(row) => (
                <button
                  onClick={async () => {
                    setDetailsLoading(true)
                    try {
                      const full = await getProductById(row._id)
                      setDetails(full)
                      setDetailsOpen(true)
                    } catch (err) {
                      toast.error(err?.message || 'Failed to load product')
                    } finally {
                      setDetailsLoading(false)
                    }
                  }}
                  className="text-xs font-semibold px-3 py-1.5 rounded-full border border-white/10 bg-black/20 hover:bg-white/10 transition"
                >
                  Details
                </button>
              )}
            />
          </div>
        </div>
      </div>

      <Modal open={detailsOpen} onClose={() => setDetailsOpen(false)} title="Product Details">
        {detailsLoading ? (
          <div className="text-sm text-slate-300">Loading...</div>
        ) : details ? (
          <div className="space-y-3 text-sm">
            <div className="grid grid-cols-2 gap-3">
              <KeyValue k="Product Code" v={details.productCode} />
              <KeyValue k="Category" v={details.category} />
              <KeyValue k="Product Name" v={details.productName} />
              <KeyValue k="Supplier" v={details.supplierName} />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <KeyValue k="Quantity In Stock" v={details.quantityInStock} />
              <KeyValue k="Unit Price" v={details.unitPrice} />
            </div>
            <KeyValue k="Date Received" v={details.dateReceived ? new Date(details.dateReceived).toISOString().split('T')[0] : '—'} />
          </div>
        ) : (
          <div className="text-sm text-slate-400">No product selected.</div>
        )}
      </Modal>
    </div>
  )
}

function Field({ label, error, children }) {
  return (
    <div>
      <label className="block text-xs text-slate-300 font-medium mb-1">{label}</label>
      {children}
      {error ? <p className="text-xs text-red-300 mt-1">{error}</p> : null}
    </div>
  )
}

function KeyValue({ k, v }) {
  return (
    <div className="rounded-xl border border-white/10 bg-black/20 p-3">
      <div className="text-xs text-slate-400">{k}</div>
      <div className="text-sm font-semibold mt-1">{v ?? '—'}</div>
    </div>
  )
}

