import { type FormEvent, useEffect, useState } from 'react'
import { ApiHttpError } from '../../api/http'
import {
  adminUpdatePrintRequestStatus,
  fetchAdminPrintRequests,
  openPrintRequestFile,
  type PrintRequestRow,
} from '../../api/printRequests'
import { useAuth } from '../../auth/AuthProvider'

/** Admin print queue — `GET /api/v1/administrator/print-requests`, status `PATCH .../:id/status` (JWT). SPA: `/app/admin/print-requests`. */

function badgeForStatus(req: PrintRequestRow): { className: string; label: string } {
  const status = String(req.status ?? '')
  const fn = String(req.admin_firstname ?? '').trim()
  switch (status) {
    case 'not_assigned':
      return { className: 'bg-secondary', label: 'Not assigned' }
    case 'assigned':
      return { className: 'bg-warning', label: fn ? `Assigned to ${fn}` : 'Assigned' }
    case 'done':
      return { className: 'bg-primary', label: 'Done' }
    case 'delivered':
      return { className: 'bg-success', label: 'Delivered' }
    default:
      return { className: 'bg-light text-dark', label: status.replace(/_/g, ' ') }
  }
}

export function AdminPrintRequestsPage() {
  const { user } = useAuth()
  const [rows, setRows] = useState<PrintRequestRow[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  function load() {
    setLoading(true)
    setError(null)
    fetchAdminPrintRequests()
      .then((d) => setRows(d.print_requests ?? []))
      .catch((e: unknown) =>
        setError(e instanceof ApiHttpError ? e.message : 'Could not load requests.'),
      )
      .finally(() => setLoading(false))
  }

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

  async function onStatusSubmit(e: FormEvent<HTMLFormElement>, requestId: number | string) {
    e.preventDefault()
    const fd = new FormData(e.currentTarget)
    const status = String(fd.get('status') ?? '')
    try {
      await adminUpdatePrintRequestStatus(requestId, {
        status,
        admin_id: user?.id,
      })
      load()
    } catch (err: unknown) {
      setError(err instanceof ApiHttpError ? err.message : 'Update failed.')
    }
  }

  return (
    <div className="container-fluid py-5">
      <div className="card my-4">
        <div className="card-header">
          <h5 className="mb-0">Print Requests — Admin</h5>
        </div>
        <div className="card-body">
          {loading ? <p className="text-muted">Loading…</p> : null}
          {error ? <div className="alert alert-danger">{error}</div> : null}
          <div className="table-responsive">
            <table className="table table-bordered table-striped no-mgmt-sticky">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Submitted By</th>
                  <th>Class</th>
                  <th>File</th>
                  <th>Pages</th>
                  <th>Copies</th>
                  <th>Required By</th>
                  <th>Pickup Method</th>
                  <th>Status</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {rows.length === 0 && !loading ? (
                  <tr>
                    <td colSpan={10} className="text-center">
                      No print requests found.
                    </td>
                  </tr>
                ) : (
                  rows.map((request) => {
                    const id = request.id
                    const st = String(request.status ?? '')
                    const badge = badgeForStatus(request)
                    const fp = request.file_path ? String(request.file_path) : ''
                    const subName = [request.firstname, request.lastname].filter(Boolean).join(' ')
                    return (
                      <tr key={String(id)}>
                        <td>{String(id)}</td>
                        <td>{subName}</td>
                        <td>{String(request.class_section_name ?? '')}</td>
                        <td>
                          {fp ? (
                            <button
                              type="button"
                              className="btn btn-link btn-sm p-0"
                              onClick={() => openPrintRequestFile(encodeURIComponent(fp))}
                            >
                              {fp}
                            </button>
                          ) : (
                            <span className="text-muted">Physical copy request</span>
                          )}
                        </td>
                        <td>
                          {request.page_selection ? (
                            String(request.page_selection)
                          ) : (
                            <span className="text-muted">ALL</span>
                          )}
                        </td>
                        <td>{String(request.num_copies ?? '')}</td>
                        <td>{String(request.required_by ?? '')}</td>
                        <td>{String(request.pickup_method ?? '')}</td>
                        <td>
                          <span className={`badge ${badge.className}`}>{badge.label}</span>
                        </td>
                        <td>
                          {st !== 'delivered' ? (
                            <form className="d-flex flex-wrap gap-1" onSubmit={(e) => onStatusSubmit(e, id as string)}>
                              <select name="status" className="form-select form-select-sm" defaultValue={st} style={{ maxWidth: 160 }}>
                                {st === 'not_assigned' ? (
                                  <>
                                    <option value="not_assigned">Not Assigned</option>
                                    <option value="assigned">Assigned</option>
                                  </>
                                ) : null}
                                {st === 'assigned' ? (
                                  <>
                                    <option value="assigned">Assigned</option>
                                    <option value="not_assigned">Not Assigned</option>
                                    <option value="done">Done</option>
                                  </>
                                ) : null}
                                {st === 'done' ? (
                                  <>
                                    <option value="done">Done</option>
                                    <option value="delivered">Delivered</option>
                                  </>
                                ) : null}
                              </select>
                              <button type="submit" className="btn btn-primary btn-sm">
                                Update
                              </button>
                            </form>
                          ) : (
                            <span>—</span>
                          )}
                        </td>
                      </tr>
                    )
                  })
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  )
}
