import { useEffect, useMemo, useRef, useState } from 'react'
import { useParams, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchClassPrepPrintPayload } from '../../api/session'
import './ClassPrepPrintPage.css'

const PREFERRED_ORDER = [
  'Grade Box',
  'Large Table',
  'Regular Chair',
  'Small Chair',
  'Small Table',
  'Teacher Chair',
  'Trash Bin',
  'White Board',
]

function orderPrepItems(prepItems: Record<string, number>): [string, number][] {
  const ordered: [string, number][] = []
  for (const k of PREFERRED_ORDER) {
    if (Object.prototype.hasOwnProperty.call(prepItems, k)) {
      ordered.push([k, prepItems[k]!])
    }
  }
  for (const [k, v] of Object.entries(prepItems)) {
    if (!ordered.some(([ok]) => ok === k)) ordered.push([k, v])
  }
  return ordered
}

export function ClassPrepPrintPage() {
  const { sectionId, schoolYear } = useParams<{ sectionId: string; schoolYear: string }>()
  const [searchParams] = useSearchParams()
  const semester = searchParams.get('semester') ?? undefined

  const [title, setTitle] = useState<string>('Class')
  const [items, setItems] = useState<Record<string, number>>({})
  const [error, setError] = useState<string | null>(null)
  const [ready, setReady] = useState(false)
  const printedRef = useRef(false)

  const decoded = useMemo(
    () => ({
      sectionId: sectionId ? decodeURIComponent(sectionId) : '',
      schoolYear: schoolYear ? decodeURIComponent(schoolYear) : '',
    }),
    [sectionId, schoolYear],
  )

  useEffect(() => {
    printedRef.current = false
  }, [decoded.sectionId, decoded.schoolYear, semester])

  useEffect(() => {
    if (!decoded.sectionId || !decoded.schoolYear) return
    let cancelled = false
    setReady(false)
    fetchClassPrepPrintPayload({
      sectionId: decoded.sectionId,
      schoolYear: decoded.schoolYear,
      semester,
    })
      .then((res) => {
        if (cancelled) return
        setTitle(res.class_section?.trim() || `Section ${decoded.sectionId}`)
        setItems(res.prep_items ?? {})
        setReady(true)
      })
      .catch((e: unknown) => {
        if (!cancelled) {
          setError(e instanceof ApiHttpError ? e.message : 'Could not load print data.')
          setReady(false)
        }
      })
    return () => {
      cancelled = true
    }
  }, [decoded.sectionId, decoded.schoolYear, semester])

  useEffect(() => {
    if (!ready || error || printedRef.current) return
    printedRef.current = true
    const t = window.setTimeout(() => window.print(), 400)
    return () => window.clearTimeout(t)
  }, [ready, error])

  const rows = orderPrepItems(items).filter(([, q]) => Number(q) > 0)

  return (
    <div className="classprep-print-root">
      {error ? (
        <p className="text-danger p-4">{error}</p>
      ) : (
        <div className="prep-label">
          <h2>Grade {title}</h2>
          <ul>
            {rows.length === 0 ? (
              <li>No items needed</li>
            ) : (
              rows.map(([name, qty]) => (
                <li key={name}>
                  <strong>{qty}</strong> {name}
                </li>
              ))
            )}
          </ul>
        </div>
      )}
    </div>
  )
}
