import { useEffect, useMemo, useState } from 'react'
import { toast } from 'react-hot-toast'
import { createWarehouse, getAllWarehouses, getWarehouseById } from '../services/warehousesService'

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

export default function WarehousesPage() {
  const [items, setItems] = useState([])
  const [loading, setLoading] = useState(true)

  const [form, setForm] = useState({ warehouseCode: '', warehouseName: '', warehouseLocation: '' })
  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 getAllWarehouses()
        setItems(Array.isArray(data) ? data : [])
      } catch (err) {
        toast.error(err?.message || 'Failed to load warehouses')
      } finally {
        setLoading(false)
      }
    }
    run()
  }, [])

  const columns = useMemo(
    () => [
      { header: 'Code', accessor: (w) => w.warehouseCode },
      { header: 'Name', accessor: (w) => w.warehouseName },
      { header: 'Location', accessor: (w) => w.warehouseLocation },
    ],
    [],
  )

  return (
    <div>
      <div className="flex items-start justify-between gap-4 mb-4">
        <div>
          <h2 className="text-2xl font-semibold">Warehouses</h2>
          <p className="text-sm text-slate-400 mt-1">Add warehouse locations and browse inventory storage.</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 Warehouse</div>
            <div className="text-xs text-slate-400 mt-1 mb-4">Warehouse code must be unique.</div>

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

                setSubmitting(true)
                try {
                  await createWarehouse(form)
                  toast.success('Warehouse created')
                  const data = await getAllWarehouses()
                  setItems(Array.isArray(data) ? data : [])
                  setForm({ warehouseCode: '', warehouseName: '', warehouseLocation: '' })
                  setFormErrors({})
                } catch (err) {
                  toast.error(err?.message || 'Failed to create warehouse')
                } finally {
                  setSubmitting(false)
                }
              }}
              className="space-y-3"
            >
              <Field label="Warehouse Code" error={formErrors.warehouseCode}>
                <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.warehouseCode}
                  onChange={(e) => setForm((s) => ({ ...s, warehouseCode: e.target.value }))}
                />
              </Field>

              <Field label="Warehouse Name" error={formErrors.warehouseName}>
                <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.warehouseName}
                  onChange={(e) => setForm((s) => ({ ...s, warehouseName: e.target.value }))}
                />
              </Field>

              <Field label="Warehouse Location" error={formErrors.warehouseLocation}>
                <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.warehouseLocation}
                  onChange={(e) => setForm((s) => ({ ...s, warehouseLocation: 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 Warehouse'}
              </button>
            </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">Warehouse 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={['warehouseCode', 'warehouseName', 'warehouseLocation']}
              rowAction={(row) => (
                <button
                  onClick={async () => {
                    setDetailsLoading(true)
                    try {
                      const full = await getWarehouseById(row._id)
                      setDetails(full)
                      setDetailsOpen(true)
                    } catch (err) {
                      toast.error(err?.message || 'Failed to load warehouse')
                    } 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="Warehouse 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="Warehouse Code" v={details.warehouseCode} />
              <KeyValue k="Location" v={details.warehouseLocation} />
              <KeyValue k="Warehouse Name" v={details.warehouseName} />
            </div>
          </div>
        ) : (
          <div className="text-sm text-slate-400">No warehouse 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>
  )
}

