import { useCallback, useEffect, useMemo, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { deleteInventoryItem, fetchInventoryIndex } from '../../api/inventory'
import { AcademicFilterBar } from '../discounts/AcademicFilterBar'
import { CategoryAddModal } from './CategoryAddModal'
import {
  catLabelBook,
  gradeLabel,
  parseInventoryList,
  userDisplay,
} from './inventoryHelpers'
import { INVENTORY_BOOK_BASE } from './inventoryPaths'

/** CI `inventory/book/index.php` */
export function InventoryBookIndexPage() {
  const [searchParams] = useSearchParams()
  const [categoryFilter, setCategoryFilter] = useState('')
  const [payload, setPayload] = useState<ReturnType<typeof parseInventoryList>>({
    items: [],
    categories: [],
    userNames: {},
  })
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const load = useCallback(() => {
    setLoading(true)
    fetchInventoryIndex('book', searchParams)
      .then((data) => {
        setPayload(parseInventoryList(data))
        setError(null)
      })
      .catch((e: unknown) => {
        setError(e instanceof ApiHttpError ? e.message : 'Unable to load books.')
      })
      .finally(() => setLoading(false))
  }, [searchParams])

  useEffect(() => {
    load()
  }, [load])

  const catById = useMemo(() => {
    const m = new Map<number, Record<string, unknown>>()
    for (const c of payload.categories) {
      const id = Number(c.id ?? 0)
      if (id) m.set(id, c)
    }
    return m
  }, [payload.categories])

  async function onDelete(id: number) {
    if (!confirm('Delete this item?')) return
    try {
      await deleteInventoryItem(id)
      load()
    } catch (e: unknown) {
      setError(e instanceof ApiHttpError ? e.message : 'Delete failed.')
    }
  }

  return (
    <div className="container-fluid px-0 mt-3">
      <div className="d-flex justify-content-between align-items-center mb-3 px-3">
        <h3 className="mb-0">Books</h3>
        <div className="btn-group">
          <Link className="btn btn-primary" to={`${INVENTORY_BOOK_BASE}/create`}>
            Add Book
          </Link>
          <button
            type="button"
            className="btn btn-outline-secondary"
            data-bs-toggle="modal"
            data-bs-target="#addCategoryModalBook"
          >
            Add Category
          </button>
        </div>
      </div>

      {error ? <div className="alert alert-danger mx-3">{error}</div> : null}
      <div className="px-3 mb-2">
        <AcademicFilterBar />
      </div>

      <div className="card mb-4 mx-3">
        <div className="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
          <span>Books</span>
          <select
            className="form-select form-select-sm"
            style={{ minWidth: 260 }}
            value={categoryFilter}
            onChange={(e) => setCategoryFilter(e.target.value)}
          >
            <option value="">All Categories</option>
            {payload.categories.map((c) => (
              <option key={String(c.id)} value={String(c.id)}>
                {catLabelBook(c)}
              </option>
            ))}
          </select>
        </div>
        <div className="card-body table-responsive">
          {loading ? <p className="text-muted mb-0">Loading…</p> : null}
          {!loading ? (
            <table className="table table-striped align-middle" id="inventoryTableBook">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>ISBN</th>
                  <th>Edition</th>
                  <th>Category</th>
                  <th>Grade Range</th>
                  <th>Qty</th>
                  <th>Unit</th>
                  <th>Updated By</th>
                  <th>Updated Date</th>
                  <th>SKU</th>
                  <th style={{ width: 110 }}>Actions</th>
                </tr>
              </thead>
              <tbody>
                {payload.items.map((i) => {
                  const cid = i.category_id != null ? Number(i.category_id) : NaN
                  const cat = Number.isFinite(cid) ? catById.get(cid) : undefined
                  const show =
                    !categoryFilter ||
                    String(i.category_id ?? '') === categoryFilter
                  if (!show) return null
                  return (
                    <tr key={String(i.id)} data-category={String(i.category_id ?? '')}>
                      <td>{String(i.name ?? '')}</td>
                      <td>{String(i.isbn ?? '')}</td>
                      <td>{String(i.edition ?? '')}</td>
                      <td>{String(cat?.name ?? '—')}</td>
                      <td>{gradeLabel(cat)}</td>
                      <td>{String(i.quantity ?? '')}</td>
                      <td>{String(i.unit ?? '')}</td>
                      <td>{userDisplay(payload.userNames, i.updated_by)}</td>
                      <td>{String(i.updated_at ?? '—')}</td>
                      <td>{String(i.sku ?? '')}</td>
                      <td>
                        <Link
                          className="btn btn-sm btn-outline-primary me-1"
                          to={`${INVENTORY_BOOK_BASE}/${String(i.id)}/edit`}
                        >
                          Edit
                        </Link>
                        <button
                          type="button"
                          className="btn btn-sm btn-outline-danger"
                          onClick={() => void onDelete(Number(i.id))}
                        >
                          Del
                        </button>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          ) : null}
        </div>
      </div>

      <CategoryAddModal
        modalId="addCategoryModalBook"
        inventoryType="book"
        title="Add Category (Books)"
        includeGradeRange
        onSaved={load}
      />
    </div>
  )
}
