import { type FormEvent, useEffect, useMemo, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { useSchoolYearOptions } from '../../hooks/useSchoolYearOptions'
import {
  fetchAdministratorAdminAttendance,
  saveAdministratorAdminAttendance,
} from '../../api/session'
import { TEACHER_ATTENDANCE_MONTH_PATH } from './attendancePaths'
import type { AdministratorAdminAttendanceRow } from '../../api/types'

function formatUsDate(ymd: string): string {
  if (!/^\d{4}-\d{2}-\d{2}$/.test(ymd)) return ymd
  const [y, m, d] = ymd.split('-')
  return `${m}-${d}-${y}`
}

/** Port of `Views/attendance/admins_attendance_form.php` — admin staff daily attendance. */
export function AdminsAttendanceFormPage() {
  const [searchParams, setSearchParams] = useSearchParams()
  const schoolYear = searchParams.get('school_year') ?? ''
  const semester = searchParams.get('semester') ?? ''
  const date =
    searchParams.get('date') ?? new Date().toISOString().slice(0, 10)

  const [rows, setRows] = useState<AdministratorAdminAttendanceRow[]>([])
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [message, setMessage] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const { options, selectedYear } = useSchoolYearOptions({
    preferredYear: schoolYear,
  })

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      setLoading(true)
      setError(null)
      try {
        const data = await fetchAdministratorAdminAttendance({
          date,
          semester: semester || null,
          schoolYear: schoolYear || null,
        })
        if (!cancelled) setRows(data.admins_grid ?? [])
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Unable to load admin attendance.')
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [date, semester, schoolYear])

  const dateLabel = useMemo(() => formatUsDate(date), [date])

  function setField(
    userId: number,
    patch: Partial<Pick<AdministratorAdminAttendanceRow, 'status' | 'reason'>>,
  ) {
    setRows((prev) =>
      prev.map((r) =>
        (r.user_id ?? 0) === userId ? { ...r, ...patch } : r,
      ),
    )
  }

  function markAllPresent() {
    setRows((prev) => prev.map((r) => ({ ...r, status: 'present' })))
  }

  function clearAll() {
    setRows((prev) => prev.map((r) => ({ ...r, status: '', reason: '' })))
  }

  async function onSubmit(e: FormEvent) {
    e.preventDefault()
    setSaving(true)
    setMessage(null)
    setError(null)
    try {
      const admins: Record<
        string,
        { status?: string | null; reason?: string | null; role_name?: string | null }
      > = {}
      for (const r of rows) {
        const uid = r.user_id ?? 0
        if (!uid) continue
        admins[String(uid)] = {
          status: r.status ?? '',
          reason: r.reason ?? '',
          role_name: r.role_name ?? 'Admin',
        }
      }
      await saveAdministratorAdminAttendance({
        date,
        semester,
        school_year: schoolYear,
        admins,
      })
      setMessage('Saved.')
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Save failed.')
    } finally {
      setSaving(false)
    }
  }

  function applyFilters(next: { school_year: string; semester: string; date: string }) {
    const p = new URLSearchParams()
    if (next.school_year) p.set('school_year', next.school_year)
    if (next.semester) p.set('semester', next.semester)
    if (next.date) p.set('date', next.date)
    setSearchParams(p)
  }

  return (
    <div className="container-xxl py-4">
      <div className="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
        <h2 className="mb-0">Admin Attendance</h2>
        <div className="d-flex gap-2">
          <Link
            className="btn btn-outline-secondary"
            to={`${TEACHER_ATTENDANCE_MONTH_PATH}?${new URLSearchParams({ date, semester, school_year: schoolYear }).toString()}`}
          >
            ← Back to Monthly Attendance
          </Link>
        </div>
      </div>

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

      <form
        className="row gy-2 gx-3 align-items-end mb-3"
        onSubmit={(e) => {
          e.preventDefault()
          const fd = new FormData(e.currentTarget)
          applyFilters({
            school_year: String(fd.get('school_year') ?? ''),
            semester: String(fd.get('semester') ?? ''),
            date: String(fd.get('date') ?? ''),
          })
        }}
      >
        <div className="col-sm-3">
          <label className="form-label">School Year</label>
          <select name="school_year" className="form-select" defaultValue={schoolYear || selectedYear}>
            {(options.length > 0 ? options : [{ value: selectedYear, label: selectedYear }]).map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </div>
        <div className="col-sm-2">
          <label className="form-label">Semester</label>
          <input
            type="text"
            name="semester"
            className="form-control"
            defaultValue={semester}
            placeholder="Fall"
          />
        </div>
        <div className="col-sm-3">
          <label className="form-label">Date</label>
          <input type="date" name="date" className="form-control" defaultValue={date} />
        </div>
        <div className="col-sm-4 d-flex gap-2">
          <button type="submit" className="btn btn-secondary">
            Load
          </button>
          <button
            type="button"
            className="btn btn-outline-secondary"
            onClick={() => setSearchParams(new URLSearchParams())}
          >
            Reset
          </button>
        </div>
      </form>

      <form onSubmit={onSubmit}>
        <div className="card shadow-sm">
          <div className="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
            <div>
              <strong>Admins on {dateLabel}</strong>
              <span className="badge bg-secondary ms-2">{rows.length}</span>
            </div>
            <div className="d-flex gap-2">
              <button type="button" className="btn btn-sm btn-outline-success" onClick={markAllPresent}>
                Mark All Present
              </button>
              <button type="button" className="btn btn-sm btn-outline-secondary" onClick={clearAll}>
                Clear All
              </button>
            </div>
          </div>

          <div className="card-body table-responsive">
            {loading ? (
              <p className="text-muted mb-0">Loading…</p>
            ) : rows.length === 0 ? (
              <div className="alert alert-info mb-0">No Admin users found for this day/term.</div>
            ) : (
              <table className="table table-bordered table-striped align-middle" id="adminsAttTable">
                <thead className="table-light">
                  <tr>
                    <th className="text-center" style={{ width: 70 }}>
                      #
                    </th>
                    <th>Name</th>
                    <th className="text-center" style={{ width: 180 }}>
                      Role
                    </th>
                    <th className="text-center" style={{ width: 220 }}>
                      Status
                    </th>
                    <th>Reason</th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map((row, idx) => {
                    const uid = row.user_id ?? 0
                    const name =
                      `${row.firstname ?? ''} ${row.lastname ?? ''}`.trim() || `User#${uid}`
                    const stat = String(row.status ?? '').toLowerCase()
                    return (
                      <tr key={uid || idx}>
                        <td className="text-center">{idx + 1}</td>
                        <td>{name}</td>
                        <td className="text-center">{row.role_name ?? 'Admin'}</td>
                        <td className="text-center">
                          <select
                            className="form-select form-select-sm"
                            value={stat === 'present' || stat === 'absent' || stat === 'late' ? stat : ''}
                            onChange={(ev) =>
                              setField(uid, { status: ev.target.value || null })
                            }
                          >
                            <option value="">—</option>
                            <option value="present">Present</option>
                            <option value="absent">Absent</option>
                            <option value="late">Late</option>
                          </select>
                        </td>
                        <td>
                          <input
                            type="text"
                            className="form-control form-control-sm"
                            placeholder="Optional reason"
                            value={row.reason ?? ''}
                            onChange={(ev) => setField(uid, { reason: ev.target.value })}
                          />
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            )}
          </div>

          <div className="card-footer d-flex justify-content-end">
            <button type="submit" className="btn btn-primary" disabled={saving || rows.length === 0}>
              {saving ? 'Saving…' : 'Save Admins Attendance'}
            </button>
          </div>
        </div>
      </form>
    </div>
  )
}
