import { type FormEvent, useCallback, useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import {
  deleteMovement,
  fetchMovements,
  postMovementsBulkDelete,
} from '../../api/inventory'
import { AcademicFilterBar } from '../discounts/AcademicFilterBar'

/** CI `inventory/movements/index.php` (DataTables replaced with static table). */
export function InventoryMovementsIndexPage() {
  const [searchParams] = useSearchParams()
  const [movements, setMovements] = useState<Record<string, unknown>[]>([])
  const [selected, setSelected] = useState<Record<number, boolean>>({})
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const load = useCallback(() => {
    setLoading(true)
    fetchMovements(searchParams)
      .then((data) => {
        if (data && typeof data === 'object') {
          const o = data as Record<string, unknown>
          setMovements(Array.isArray(o.movements) ? (o.movements as Record<string, unknown>[]) : [])
        } else {
          setMovements([])
        }
        setSelected({})
        setError(null)
      })
      .catch((e: unknown) => {
        setError(e instanceof ApiHttpError ? e.message : 'Unable to load movements.')
      })
      .finally(() => setLoading(false))
  }, [searchParams])

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

  const selectedIds = Object.entries(selected)
    .filter(([, v]) => v)
    .map(([k]) => Number(k))
    .filter((n) => Number.isFinite(n))

  function toggleRow(id: number, checked: boolean) {
    setSelected((prev) => ({ ...prev, [id]: checked }))
  }

  function toggleAll(checked: boolean) {
    const next: Record<number, boolean> = {}
    if (checked) {
      for (const m of movements) {
        const id = Number(m.id)
        if (Number.isFinite(id)) next[id] = true
      }
    }
    setSelected(next)
  }

  async function onBulkDelete(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (selectedIds.length === 0) return
    if (!confirm(`Delete ${selectedIds.length} selected movement(s)?`)) return
    try {
      await postMovementsBulkDelete(selectedIds)
      load()
    } catch (err: unknown) {
      setError(err instanceof ApiHttpError ? err.message : 'Bulk delete failed.')
    }
  }

  async function onDeleteOne(id: number) {
    if (!confirm('Delete this movement?')) return
    try {
      await deleteMovement(id)
      load()
    } catch (err: unknown) {
      setError(err instanceof ApiHttpError ? err.message : 'Delete failed.')
    }
  }

  return (
    <div className="container-fluid">
      <div className="d-flex justify-content-between align-items-center my-3 flex-wrap gap-2">
        <h2 className="mb-0">Inventory Movements</h2>
        <Link className="btn btn-success" to="/app/administrator/inventory/movements/create">
          New Movement
        </Link>
      </div>
      <div className="mb-2">
        <AcademicFilterBar />
      </div>

      {error ? <div className="alert alert-danger">{error}</div> : null}

      <form id="bulkDeleteForm" onSubmit={(ev) => void onBulkDelete(ev)}>
        <div className="d-flex gap-2 mb-2">
          <button type="submit" className="btn btn-danger btn-sm" disabled={selectedIds.length === 0}>
            Delete Selected
          </button>
        </div>

        <div className="table-responsive">
          <table className="table table-striped table-hover align-middle" id="movementsTable">
            <thead className="table-dark">
              <tr>
                <th style={{ width: 36 }}>
                  <input
                    type="checkbox"
                    title="Select all"
                    checked={(() => {
                      const ids = movements.map((m) => Number(m.id)).filter((n) => Number.isFinite(n))
                      return ids.length > 0 && ids.every((id) => selected[id])
                    })()}
                    onChange={(e) => toggleAll(e.target.checked)}
                  />
                </th>
                <th>ID</th>
                <th>Item</th>
                <th>Qty Change</th>
                <th>Movement Type</th>
                <th>Reason</th>
                <th>Semester</th>
                <th>School Year</th>
                <th>Teacher</th>
                <th>Student</th>
                <th>Class Section</th>
                <th>Performed By</th>
                <th>Created At</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr>
                  <td colSpan={14} className="text-muted">
                    Loading…
                  </td>
                </tr>
              ) : movements.length === 0 ? (
                <tr>
                  <td colSpan={14} className="text-muted">
                    No movements.
                  </td>
                </tr>
              ) : (
                movements.map((m) => {
                  const id = Number(m.id)
                  return (
                    <tr key={id}>
                      <td>
                        <input
                          type="checkbox"
                          checked={Boolean(selected[id])}
                          onChange={(e) => toggleRow(id, e.target.checked)}
                        />
                      </td>
                      <td>{String(m.id ?? '')}</td>
                      <td>{String(m.item_name ?? m.item_id ?? '')}</td>
                      <td>{String(m.qty_change ?? '')}</td>
                      <td>
                        <span className="badge bg-info">{String(m.movement_type ?? '')}</span>
                      </td>
                      <td>{String(m.reason ?? '')}</td>
                      <td>{String(m.semester ?? '')}</td>
                      <td>{String(m.school_year ?? '')}</td>
                      <td>{String(m.teacher_name ?? m.teacher_id ?? '')}</td>
                      <td>{String(m.student_name ?? m.student_id ?? '')}</td>
                      <td>{String(m.class_section_name ?? m.class_section_id ?? '')}</td>
                      <td>{String(m.performed_by_name ?? m.performed_by ?? '')}</td>
                      <td>{String(m.created_at ?? '')}</td>
                      <td className="text-nowrap">
                        <Link
                          className="btn btn-sm btn-primary me-1"
                          to={`/app/administrator/inventory/movements/${id}/edit`}
                        >
                          Edit
                        </Link>
                        <button
                          type="button"
                          className="btn btn-sm btn-danger"
                          onClick={() => void onDeleteOne(id)}
                        >
                          Delete
                        </button>
                      </td>
                    </tr>
                  )
                })
              )}
            </tbody>
          </table>
        </div>

        <div className="mt-2">
          <button type="submit" className="btn btn-danger btn-sm" disabled={selectedIds.length === 0}>
            Delete Selected
          </button>
        </div>
      </form>
    </div>
  )
}
