import { useEffect, useMemo, useState, type FormEvent } from 'react'
import { Link } from 'react-router-dom'
import {
  completeAttendanceFollowUp,
  fetchAttendanceManagementDashboard,
  recordAttendanceBadgeScan,
  recordManualAttendanceEntry,
  reprintAttendanceLateSlip,
  type AttendanceManagementDashboard,
  type AttendanceManagementEvent,
} from '../../api/attendanceManagement'
import { ApiHttpError } from '../../api/http'

type FormState = {
  badge_scan: string
  person_name: string
  person_type: string
  role_grade: string
  entry_time: string
  manual_reason: string
  report_status: string
  reason: string
}

const today = new Date().toISOString().slice(0, 10)

const emptyForm: FormState = {
  badge_scan: '',
  person_name: '',
  person_type: 'student',
  role_grade: '',
  entry_time: '',
  manual_reason: 'badge missing',
  report_status: 'pending_clarification',
  reason: '',
}

function nice(value: string | null | undefined): string {
  if (!value) return '—'
  return value.replace(/_/g, ' ')
}

function boolish(value: boolean | number): boolean {
  return value === true || value === 1
}

export function AttendanceManagementPage() {
  const [date, setDate] = useState(today)
  const [status, setStatus] = useState('')
  const [reportStatus, setReportStatus] = useState('')
  const [q, setQ] = useState('')
  const [dashboard, setDashboard] = useState<AttendanceManagementDashboard | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [message, setMessage] = useState<string | null>(null)
  const [form, setForm] = useState<FormState>(emptyForm)

  const params = useMemo(() => ({ date, attendance_status: status, report_status: reportStatus, q }), [date, status, reportStatus, q])

  async function load() {
    setLoading(true)
    setError(null)
    try {
      setDashboard(await fetchAttendanceManagementDashboard(params))
    } catch (e) {
      setError(e instanceof ApiHttpError ? e.message : 'Unable to load attendance management dashboard.')
    } finally {
      setLoading(false)
    }
  }

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

  async function submitScan(event: FormEvent) {
    event.preventDefault()
    setMessage(null)
    setError(null)
    try {
      await recordAttendanceBadgeScan({
        badge_scan: form.badge_scan,
        scan_type: 'entry',
        report_status: form.report_status,
        reason: form.reason,
      })
      setMessage('Badge scan classified. Late students were automatically added to late-slip workflow.')
      setForm((f) => ({ ...f, badge_scan: '', reason: '' }))
      await load()
    } catch (e) {
      setError(e instanceof ApiHttpError ? e.message : 'Unable to record badge scan.')
    }
  }

  async function submitManual(event: FormEvent) {
    event.preventDefault()
    setMessage(null)
    setError(null)
    try {
      await recordManualAttendanceEntry({
        person_type: form.person_type,
        person_name: form.person_name,
        role_grade: form.role_grade,
        entry_time: form.entry_time || undefined,
        manual_reason: form.manual_reason,
        report_status: form.report_status,
        reason: form.reason,
      })
      setMessage('Manual entry recorded and counted as a badge exception. Yes, accountability survived another checkbox.')
      setForm(emptyForm)
      await load()
    } catch (e) {
      setError(e instanceof ApiHttpError ? e.message : 'Unable to record manual entry.')
    }
  }

  async function complete(row: AttendanceManagementEvent) {
    setMessage(null)
    setError(null)
    try {
      await completeAttendanceFollowUp(row.id, {
        report_status: row.report_status === 'not_reported' ? 'pending_clarification' : row.report_status,
        final_decision: row.final_decision || 'Resolved after contact attempt',
        notes: row.notes || 'Follow-up completed from management dashboard.',
      })
      setMessage('Follow-up marked completed.')
      await load()
    } catch (e) {
      setError(e instanceof ApiHttpError ? e.message : 'Unable to complete follow-up.')
    }
  }

  async function reprint(row: AttendanceManagementEvent) {
    setMessage(null)
    setError(null)
    try {
      await reprintAttendanceLateSlip(row.id, { reason: 'Dashboard reprint' })
      setMessage('Late slip reprint logged.')
      await load()
    } catch (e) {
      setError(e instanceof ApiHttpError ? e.message : 'Unable to log late-slip reprint.')
    }
  }

  const summary = dashboard?.summary

  return (
    <div className="container-fluid py-4">
      <div className="d-flex flex-wrap justify-content-between gap-3 align-items-start mb-4">
        <div>
          <h1 className="h3 mb-1">School Attendance Management</h1>
          <p className="text-muted mb-0">Badge scans, manual entries, not-reported follow-up, late slips, early dismissal risk, and badge exceptions in one place.</p>
        </div>
        <div className="d-flex flex-wrap gap-2">
          <Link className="btn btn-outline-primary" to="/app/administrator/attendance/badge-scans">
            Badge Scanning List
          </Link>
          <button className="btn btn-outline-secondary" type="button" onClick={() => void load()} disabled={loading}>Refresh</button>
        </div>
      </div>

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

      <div className="row g-3 mb-4">
        {summary ? Object.entries(summary).map(([key, value]) => (
          <div className="col-6 col-md-3 col-xl-2" key={key}>
            <div className="card h-100 shadow-sm">
              <div className="card-body">
                <div className="small text-muted text-uppercase">{nice(key)}</div>
                <div className="display-6">{value}</div>
              </div>
            </div>
          </div>
        )) : null}
      </div>

      <div className="card mb-4 shadow-sm">
        <div className="card-body">
          <div className="row g-3 align-items-end">
            <div className="col-md-3">
              <label className="form-label">Date</label>
              <input className="form-control" type="date" value={date} onChange={(e) => setDate(e.target.value)} />
            </div>
            <div className="col-md-3">
              <label className="form-label">Attendance status</label>
              <select className="form-select" value={status} onChange={(e) => setStatus(e.target.value)}>
                <option value="">All</option>
                {(dashboard?.filters.attendance_status ?? []).map((x) => <option key={x} value={x}>{nice(x)}</option>)}
              </select>
            </div>
            <div className="col-md-3">
              <label className="form-label">Report status</label>
              <select className="form-select" value={reportStatus} onChange={(e) => setReportStatus(e.target.value)}>
                <option value="">All</option>
                {(dashboard?.filters.report_status ?? []).map((x) => <option key={x} value={x}>{nice(x)}</option>)}
              </select>
            </div>
            <div className="col-md-3">
              <label className="form-label">Search</label>
              <input className="form-control" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Name, badge, grade, combination" />
            </div>
          </div>
        </div>
      </div>

      <div className="row g-4 mb-4">
        <div className="col-lg-6">
          <form className="card shadow-sm h-100" onSubmit={submitScan}>
            <div className="card-body">
              <h2 className="h5">Badge entry scan</h2>
              <p className="text-muted small">Classifies present/late and creates late-slip records for late students.</p>
              <label className="form-label">Badge scan</label>
              <input className="form-control mb-3" value={form.badge_scan} onChange={(e) => setForm({ ...form, badge_scan: e.target.value })} required />
              <label className="form-label">Report status</label>
              <select className="form-select mb-3" value={form.report_status} onChange={(e) => setForm({ ...form, report_status: e.target.value })}>
                <option value="reported">Reported</option>
                <option value="not_reported">Not reported</option>
                <option value="pending_clarification">Pending clarification</option>
              </select>
              <label className="form-label">Reason</label>
              <input className="form-control mb-3" value={form.reason} onChange={(e) => setForm({ ...form, reason: e.target.value })} />
              <button className="btn btn-primary" type="submit">Record badge scan</button>
            </div>
          </form>
        </div>
        <div className="col-lg-6">
          <form className="card shadow-sm h-100" onSubmit={submitManual}>
            <div className="card-body">
              <h2 className="h5">Manual verified entry</h2>
              <p className="text-muted small">Used for missing, lost, damaged, not-issued badges, or scanner failure.</p>
              <div className="row g-3">
                <div className="col-md-6"><label className="form-label">Name</label><input className="form-control" value={form.person_name} onChange={(e) => setForm({ ...form, person_name: e.target.value })} required /></div>
                <div className="col-md-3"><label className="form-label">Type</label><select className="form-select" value={form.person_type} onChange={(e) => setForm({ ...form, person_type: e.target.value })}><option value="student">Student</option><option value="staff">Staff</option><option value="contractor">Contractor</option><option value="visitor">Visitor</option></select></div>
                <div className="col-md-3"><label className="form-label">Grade/Dept</label><input className="form-control" value={form.role_grade} onChange={(e) => setForm({ ...form, role_grade: e.target.value })} /></div>
                <div className="col-md-6"><label className="form-label">Entry time</label><input className="form-control" type="datetime-local" value={form.entry_time} onChange={(e) => setForm({ ...form, entry_time: e.target.value })} /></div>
                <div className="col-md-6"><label className="form-label">Manual reason</label><input className="form-control" value={form.manual_reason} onChange={(e) => setForm({ ...form, manual_reason: e.target.value })} /></div>
                <div className="col-md-6"><label className="form-label">Report status</label><select className="form-select" value={form.report_status} onChange={(e) => setForm({ ...form, report_status: e.target.value })}><option value="reported">Reported</option><option value="not_reported">Not reported</option><option value="pending_clarification">Pending clarification</option></select></div>
                <div className="col-md-6"><label className="form-label">Reason</label><input className="form-control" value={form.reason} onChange={(e) => setForm({ ...form, reason: e.target.value })} /></div>
              </div>
              <button className="btn btn-primary mt-3" type="submit">Record manual entry</button>
            </div>
          </form>
        </div>
      </div>

      <div className="card shadow-sm">
        <div className="card-body">
          <h2 className="h5">Admin follow-up dashboard</h2>
          <div className="table-responsive">
            <table className="table table-sm align-middle">
              <thead>
                <tr>
                  <th>Name</th><th>Role/Grade</th><th>Status</th><th>Scan/manual time</th><th>Reported</th><th>Counts</th><th>Combination</th><th>Action</th><th>Decision</th><th></th>
                </tr>
              </thead>
              <tbody>
                {(dashboard?.rows ?? []).map((row) => (
                  <tr key={row.id} className={boolish(row.follow_up_required) && !boolish(row.follow_up_completed) ? 'table-warning' : ''}>
                    <td>{row.person_name || '—'}</td>
                    <td>{row.role_grade || row.person_type}</td>
                    <td>{nice(row.attendance_status)}<div className="small text-muted">Risk: {nice(row.risk_level)}</div></td>
                    <td>{row.official_entry_time || row.official_exit_time || '—'}<div className="small text-muted">{nice(row.entry_method || row.exit_method)}</div></td>
                    <td>{nice(row.report_status)}</td>
                    <td>{row.absence_count}ABS / {row.late_count}Late / {row.early_dismissal_count}ED / {row.badge_exception_count}Badge</td>
                    <td>{row.combination_code || 'Clear'}</td>
                    <td>{row.action_needed || 'Record and monitor'}</td>
                    <td>{row.final_decision || '—'}</td>
                    <td className="text-nowrap">
                      {boolish(row.follow_up_required) && !boolish(row.follow_up_completed) ? <button className="btn btn-sm btn-outline-success me-2" onClick={() => void complete(row)}>Complete</button> : null}
                      {row.attendance_status === 'late' ? <button className="btn btn-sm btn-outline-secondary" onClick={() => void reprint(row)}>Reprint slip</button> : null}
                    </td>
                  </tr>
                ))}
                {!loading && (dashboard?.rows.length ?? 0) === 0 ? <tr><td colSpan={10} className="text-center text-muted py-4">No attendance management rows for these filters.</td></tr> : null}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  )
}
