import { useCallback, useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { useSchoolYearOptions } from '../../hooks/useSchoolYearOptions'
import { fetchInventorySummary } from '../../api/inventory'
import { AcademicFilterBar } from '../discounts/AcademicFilterBar'
import { INVENTORY_BOOK_BASE } from './inventoryPaths'

function num(v: unknown): number {
  const n = typeof v === 'number' ? v : Number(v ?? 0)
  return Number.isFinite(n) ? Math.floor(n) : 0
}

/** CI `inventory/summary.php` */
export function InventorySummaryPage() {
  const [searchParams, setSearchParams] = useSearchParams()
  const [rows, setRows] = useState<Record<string, unknown>[]>([])
  const [totals, setTotals] = useState<Record<string, number>>({})
  const [selectedYear, setSelectedYear] = useState('')
  const [currentYear, setCurrentYear] = useState('')
  const [schoolYears, setSchoolYears] = useState<string[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const { options, currentYear: canonicalCurrentYear } = useSchoolYearOptions({
    legacyYears: schoolYears,
    preferredYear: selectedYear,
  })

  const load = useCallback(() => {
    setLoading(true)
    fetchInventorySummary(searchParams)
      .then((data) => {
        if (data && typeof data === 'object') {
          const o = data as Record<string, unknown>
          setRows(Array.isArray(o.rows) ? (o.rows as Record<string, unknown>[]) : [])
          const t = o.totals
          if (t && typeof t === 'object') {
            const rec = t as Record<string, unknown>
            setTotals({
              opening: num(rec.opening),
              received: num(rec.received),
              distributed: num(rec.distributed),
              other_out: num(rec.other_out),
              adjust_net: num(rec.adjust_net),
              ending: num(rec.ending),
              onhand: num(rec.onhand),
              variance: num(rec.variance),
            })
          } else {
            setTotals({})
          }
          setSelectedYear(String(o.selectedYear ?? o.selected_year ?? ''))
          setCurrentYear(String(o.currentYear ?? o.current_year ?? ''))
          setSchoolYears(Array.isArray(o.schoolYears) ? (o.schoolYears as string[]) : [])
        }
        setError(null)
      })
      .catch((e: unknown) => {
        setError(e instanceof ApiHttpError ? e.message : 'Unable to load summary.')
      })
      .finally(() => setLoading(false))
  }, [searchParams])

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

  function onYearFilter(v: string) {
    const next = new URLSearchParams(searchParams)
    if (v === '__current__') next.delete('school_year')
    else next.set('school_year', v)
    setSearchParams(next)
  }

  const yearLabel =
    selectedYear.toLowerCase() === 'all' ? 'All Years' : selectedYear || '—'

  return (
    <div className="container-fluid px-0 mt-3">
      <div className="px-3 mb-2">
        <AcademicFilterBar schoolYears={schoolYears.length ? schoolYears : undefined} />
      </div>
      <div className="d-flex justify-content-between align-items-center mb-3 px-3 flex-wrap gap-2">
        <h3 className="mb-0">Inventory Summary — {yearLabel}</h3>
        <Link className="btn btn-outline-secondary" to={INVENTORY_BOOK_BASE}>
          Back to Items
        </Link>
      </div>

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

      <div className="card mb-3 mx-3">
        <div className="card-header d-flex gap-2 flex-wrap align-items-center justify-content-between">
          <div>Filter</div>
          <select
            id="yearFilter"
            className="form-select form-select-sm"
            style={{ minWidth: 220 }}
            value={
              selectedYear.toLowerCase() === 'all'
                ? 'all'
                : selectedYear === (currentYear || canonicalCurrentYear) && !searchParams.get('school_year')
                  ? '__current__'
                  : selectedYear
            }
            onChange={(e) => onYearFilter(e.target.value)}
          >
            <option value="__current__">Current ({currentYear || canonicalCurrentYear || '—'})</option>
            <option value="all">All Years</option>
            {options
              .filter((option) => option.value !== (currentYear || canonicalCurrentYear))
              .map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </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="summaryTable">
              <thead>
                <tr>
                  <th>Type</th>
                  <th>Category</th>
                  <th>Name</th>
                  <th className="text-end">Opening</th>
                  <th className="text-end">Received</th>
                  <th className="text-end">Distributed</th>
                  <th className="text-end">Other Out</th>
                  <th className="text-end">Adjust ±</th>
                  <th className="text-end">Ending</th>
                  <th className="text-end">On Hand (Now)</th>
                  <th className="text-end">Variance</th>
                </tr>
              </thead>
              <tbody>
                {rows.length === 0 ? (
                  <tr>
                    <td colSpan={11} className="text-center text-muted py-4">
                      No data to display for {yearLabel}.
                    </td>
                  </tr>
                ) : (
                  rows.map((r, i) => {
                    const variance = num(r.variance)
                    return (
                      <tr key={i}>
                        <td>{String(r.type ?? '')}</td>
                        <td>{String(r.category ?? '')}</td>
                        <td>{String(r.name ?? '')}</td>
                        <td className="text-end">{num(r.opening).toLocaleString()}</td>
                        <td className="text-end">{num(r.received).toLocaleString()}</td>
                        <td className="text-end">{num(r.distributed).toLocaleString()}</td>
                        <td className="text-end">{num(r.other_out).toLocaleString()}</td>
                        <td className="text-end">{num(r.adjust_net).toLocaleString()}</td>
                        <td className="text-end fw-semibold">{num(r.ending).toLocaleString()}</td>
                        <td className="text-end">{num(r.onhand).toLocaleString()}</td>
                        <td className="text-end">
                          {variance === 0 ? (
                            <span className="text-success">{variance.toLocaleString()}</span>
                          ) : (
                            <span className="text-danger fw-semibold">{variance.toLocaleString()}</span>
                          )}
                        </td>
                      </tr>
                    )
                  })
                )}
              </tbody>
              <tfoot>
                <tr className="table-light">
                  <th colSpan={3} className="text-end">
                    Totals
                  </th>
                  <th className="text-end">{(totals.opening ?? 0).toLocaleString()}</th>
                  <th className="text-end">{(totals.received ?? 0).toLocaleString()}</th>
                  <th className="text-end">{(totals.distributed ?? 0).toLocaleString()}</th>
                  <th className="text-end">{(totals.other_out ?? 0).toLocaleString()}</th>
                  <th className="text-end">{(totals.adjust_net ?? 0).toLocaleString()}</th>
                  <th className="text-end">{(totals.ending ?? 0).toLocaleString()}</th>
                  <th className="text-end">{(totals.onhand ?? 0).toLocaleString()}</th>
                  <th className="text-end">{(totals.variance ?? 0).toLocaleString()}</th>
                </tr>
              </tfoot>
            </table>
          ) : null}
        </div>
      </div>
    </div>
  )
}
