import { type FormEvent, useCallback, useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { useSchoolYearOptions } from '../../hooks/useSchoolYearOptions'
import { fetchTeacherBookDistribute, postTeacherBookDistribute } from '../../api/inventory'

type BookGroup = { label: string; items: Record<string, unknown>[] }

/** CI `inventory/teacher_distribute.php` (teacher main layout). */
export function TeacherBookDistributePage() {
  const [searchParams, setSearchParams] = useSearchParams()
  const classSectionId = searchParams.get('class_section_id') ?? ''
  const itemIdParam = searchParams.get('item_id') ?? ''

  const [booksGrouped, setBooksGrouped] = useState<BookGroup[]>([])
  const [students, setStudents] = useState<Record<string, unknown>[]>([])
  const [already, setAlready] = useState<Record<string, number>>({})
  const [onHand, setOnHand] = useState(0)
  const [schoolYear, setSchoolYear] = useState('')
  const [semester, setSemester] = useState('')
  const [itemId, setItemId] = useState(itemIdParam)
  const [note, setNote] = useState('')
  const [selected, setSelected] = useState<Record<string, boolean>>({})
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const { selectedYear } = useSchoolYearOptions({
    preferredYear: schoolYear,
  })

  const load = useCallback(() => {
    setLoading(true)
    fetchTeacherBookDistribute(searchParams)
      .then((data) => {
        if (data && typeof data === 'object') {
          const o = data as Record<string, unknown>
          const bg = o.booksGrouped
          setBooksGrouped(Array.isArray(bg) ? (bg as BookGroup[]) : [])
          setStudents(Array.isArray(o.students) ? (o.students as Record<string, unknown>[]) : [])
          const alRaw = o.already
          const alMap: Record<string, number> =
            alRaw && typeof alRaw === 'object' && !Array.isArray(alRaw)
              ? (alRaw as Record<string, number>)
              : {}
          setAlready(alMap)
          setOnHand(Number(o.onHand ?? o.on_hand ?? 0))
          setSchoolYear(String(o.schoolYear ?? o.school_year ?? ''))
          setSemester(String(o.semester ?? ''))
          const iid = o.item_id != null ? String(o.item_id) : itemIdParam
          setItemId(iid)
          const sel: Record<string, boolean> = {}
          if (Array.isArray(o.students)) {
            for (const st of o.students as Record<string, unknown>[]) {
              const sid = st.student_id ?? st.id ?? st.user_id
              if (sid != null && Number(alMap[String(sid)] ?? 0) > 0) sel[String(sid)] = true
            }
          }
          setSelected(sel)
        }
        setError(null)
      })
      .catch((e: unknown) => {
        setError(e instanceof ApiHttpError ? e.message : 'Unable to load distribution.')
      })
      .finally(() => setLoading(false))
  }, [searchParams, itemIdParam])

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

  function studentKey(st: Record<string, unknown>): string | null {
    const sid = st.student_id ?? st.id ?? st.user_id
    return sid != null ? String(sid) : null
  }

  function toggleStudent(k: string, checked: boolean) {
    setSelected((prev) => ({ ...prev, [k]: checked }))
  }

  const effectiveSchoolYear = schoolYear || selectedYear

  function checkAll(on: boolean) {
    const next: Record<string, boolean> = {}
    if (on) {
      for (const st of students) {
        const k = studentKey(st)
        if (k) next[k] = true
      }
    }
    setSelected(next)
  }

  function onFilterSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const fd = new FormData(e.currentTarget)
    const next = new URLSearchParams(searchParams)
    const cs = String(fd.get('class_section_id') ?? '')
    const it = String(fd.get('item_id') ?? '')
    if (cs) next.set('class_section_id', cs)
    else next.delete('class_section_id')
    if (it) next.set('item_id', it)
    else next.delete('item_id')
    setSearchParams(next)
  }

  async function onDistribute(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setSaving(true)
    setError(null)
    const ids = Object.entries(selected)
      .filter(([, v]) => v)
      .map(([k]) => Number(k))
      .filter((n) => Number.isFinite(n))
    try {
      await postTeacherBookDistribute({
        class_section_id: classSectionId || undefined,
        item_id: itemId === '' ? undefined : Number(itemId),
        student_ids: ids,
        note: note || undefined,
      })
      load()
    } catch (err: unknown) {
      setError(err instanceof ApiHttpError ? err.message : 'Save failed.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="container my-4">
      <h4 className="text-dark mb-3" style={{ fontFamily: 'Arial, sans-serif' }}>
        Distribute Books to Students
      </h4>

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

      <form id="filterForm" className="row g-3 mb-3" onSubmit={onFilterSubmit}>
        <input type="hidden" name="class_section_id" value={classSectionId} />

        <div className="col-md-5">
          <label className="form-label">Book</label>
          <select
            className="form-select"
            name="item_id"
            id="bookSelect"
            required
            value={itemId}
            onChange={(e) => {
              const v = e.target.value
              setItemId(v)
              const next = new URLSearchParams(searchParams)
              if (v) next.set('item_id', v)
              else next.delete('item_id')
              setSearchParams(next)
            }}
          >
            <option value="">— Select a book —</option>
            {booksGrouped.map((group) => (
              <optgroup key={group.label} label={group.label}>
                {group.items.map((b) => (
                  <option key={String(b.id)} value={String(b.id)}>
                    {String(b.display ?? b.name)} (On Hand: {Number(b.quantity ?? 0)})
                  </option>
                ))}
              </optgroup>
            ))}
          </select>
        </div>

        <div className="col-md-2 d-flex align-items-end">
          <button type="submit" className="btn btn-secondary w-100">
            Load
          </button>
        </div>
      </form>

      {loading ? <p className="text-muted">Loading…</p> : null}

      {!loading && itemId && students.length > 0 ? (
        <form onSubmit={(ev) => void onDistribute(ev)}>
          <input type="hidden" name="class_section_id" value={classSectionId} />
          <input type="hidden" name="item_id" value={itemId} />

          <div className="alert alert-info py-2">
            <div className="d-flex justify-content-between flex-wrap gap-2">
              <div>
                <strong>School Year:</strong> {effectiveSchoolYear || '—'}, <strong>Semester:</strong> {semester}
              </div>
              <div>
                <strong>On Hand:</strong> {onHand}
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
              <span>Students</span>
              <div className="d-flex gap-2">
                <button type="button" className="btn btn-sm btn-info" onClick={() => checkAll(true)}>
                  Check All
                </button>
                <button type="button" className="btn btn-sm btn-secondary" onClick={() => checkAll(false)}>
                  Uncheck All
                </button>
              </div>
            </div>

            <div className="card-body table-responsive">
              <table className="table table-bordered table-striped align-middle">
                <thead className="table-light">
                  <tr>
                    <th style={{ width: 48, textAlign: 'center' }}>#</th>
                    <th style={{ width: 56, textAlign: 'center' }}>Give</th>
                    <th>School ID</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th style={{ textAlign: 'center' }}>Age</th>
                    <th style={{ textAlign: 'center' }}>Semester</th>
                    <th style={{ textAlign: 'center' }}>School Year</th>
                    <th style={{ textAlign: 'center' }}>History</th>
                  </tr>
                </thead>
                <tbody>
                  {students.map((student, idx) => {
                    const sid = studentKey(student)
                    if (!sid) return null
                    const given = Number(already[sid] ?? 0) > 0
                    return (
                      <tr key={sid}>
                        <td style={{ textAlign: 'center' }}>{idx + 1}</td>
                        <td style={{ textAlign: 'center' }}>
                          <input
                            type="checkbox"
                            className="form-check-input"
                            checked={Boolean(selected[sid])}
                            onChange={(e) => toggleStudent(sid, e.target.checked)}
                          />
                        </td>
                        <td>{String(student.school_id ?? '-')}</td>
                        <td>{String(student.firstname ?? '')}</td>
                        <td>{String(student.lastname ?? '')}</td>
                        <td style={{ textAlign: 'center' }}>{String(student.age ?? '-')}</td>
                        <td style={{ textAlign: 'center' }}>
                          {String(student.semester ?? semester)}
                        </td>
                        <td style={{ textAlign: 'center' }}>
                          {String(student.school_year ?? effectiveSchoolYear)}
                        </td>
                        <td style={{ textAlign: 'center' }}>
                          {given ? (
                            <span className="badge bg-success">Given</span>
                          ) : (
                            <span className="text-muted">—</span>
                          )}
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>

            <div className="card-footer">
              <div className="mb-2">
                <label className="form-label">Note (optional)</label>
                <textarea
                  className="form-control"
                  rows={2}
                  name="note"
                  placeholder="e.g., Distributed in class today"
                  value={note}
                  onChange={(e) => setNote(e.target.value)}
                />
              </div>
              <div className="d-flex gap-2">
                <button type="submit" className="btn btn-success" disabled={saving}>
                  {saving ? 'Saving…' : 'Deduct & Save'}
                </button>
                <button
                  type="button"
                  className="btn btn-secondary"
                  onClick={() => checkAll(false)}
                >
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </form>
      ) : null}

      {!loading && itemId && students.length === 0 ? (
        <div className="alert alert-warning">No students found for this class.</div>
      ) : null}
    </div>
  )
}
