import { type FormEvent, useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { fetchEarlyDismissals, uploadEarlyDismissalSignature } from '../../api/session'
import { useSchoolYearOptions } from '../../hooks/useSchoolYearOptions'
import { apiUrl } from '../../lib/apiOrigin'
import { EARLY_DISMISSALS_NEW_PATH, EARLY_DISMISSALS_PATH } from './attendancePaths'

function badgeClass(status: string): string {
  if (status === 'processed') return 'success'
  if (status === 'seen') return 'info'
  return 'secondary'
}

/** Port of `Views/attendance/early_dismissals.php` */
export function EarlyDismissalsPage() {
  const [searchParams, setSearchParams] = useSearchParams()
  const schoolYear = searchParams.get('school_year') ?? ''
  const semester = searchParams.get('semester') ?? ''

  const [data, setData] = useState<Awaited<ReturnType<typeof fetchEarlyDismissals>> | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [flash, setFlash] = useState<string | null>(null)
  const { options, selectedYear } = useSchoolYearOptions({
    preferredYear: schoolYear,
  })

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      setLoading(true)
      setError(null)
      try {
        const res = await fetchEarlyDismissals({
          schoolYear: schoolYear || null,
          semester: semester || null,
        })
        if (!cancelled) setData(res)
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Unable to load early dismissals.')
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [schoolYear, semester])

  async function onSignatureSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const fd = new FormData(e.currentTarget)
    try {
      await uploadEarlyDismissalSignature(fd)
      setFlash('Signature uploaded.')
      const res = await fetchEarlyDismissals({
        schoolYear: schoolYear || null,
        semester: semester || null,
      })
      setData(res)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Upload failed.')
    }
  }

  const groups = data?.groups ?? {}
  const sigMap = data?.signatureByDate ?? {}

  return (
    <div className="container-xxl py-4">
      <div className="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
        <div>
          <h2 className="mb-0">Early Dismissals</h2>
          <small className="text-muted">Parent-submitted early dismissal requests</small>
        </div>
        <Link to={EARLY_DISMISSALS_NEW_PATH} className="btn btn-primary">
          <i className="bi bi-plus-circle me-1" aria-hidden />
          Add Early Dismissal
        </Link>
      </div>

      <form
        className="row gy-2 gx-3 align-items-end mb-4"
        onSubmit={(ev) => {
          ev.preventDefault()
          const fd = new FormData(ev.currentTarget)
          const p = new URLSearchParams()
          const sy = String(fd.get('school_year') ?? '')
          const sem = String(fd.get('semester') ?? '')
          if (sy) p.set('school_year', sy)
          if (sem) p.set('semester', sem)
          setSearchParams(p)
        }}
      >
        <div className="col-md-4">
          <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-md-3">
          <label className="form-label">Semester</label>
          <select name="semester" className="form-select" defaultValue={semester}>
            <option value="">All Semesters</option>
            <option value="Fall">Fall</option>
            <option value="Spring">Spring</option>
          </select>
        </div>
        <div className="col-md-3 d-flex gap-2">
          <button type="submit" className="btn btn-secondary mt-4">
            Apply
          </button>
          <Link className="btn btn-outline-secondary mt-4" to={EARLY_DISMISSALS_PATH}>
            Reset
          </Link>
        </div>
      </form>

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

      {loading ? (
        <p className="text-muted">Loading…</p>
      ) : Object.keys(groups).length === 0 ? (
        <div className="alert alert-info">
          No early dismissals found for the selected school year{semester ? ' and semester' : ''}.
        </div>
      ) : (
        Object.entries(groups).map(([date, rows]) => {
          const dateLabel =
            /^\d{4}-\d{2}-\d{2}$/.test(date) && date !== 'Unknown'
              ? formatMdY(date)
              : date
          const sig = sigMap[date]
          return (
            <div className="card shadow-sm mb-3" key={date}>
              <div className="card-body">
                <div className="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
                  <strong>{dateLabel}</strong>
                  {date !== 'Unknown' ? (
                    <div className="d-flex flex-wrap align-items-center gap-2">
                      {sig?.filename ? (
                        <>
                          <a
                            className="btn btn-sm btn-outline-primary"
                            href={apiUrl(`/api/v1/files/early-dismissal-signatures/${encodeURIComponent(sig.filename ?? '')}`)}
                            target="_blank"
                            rel="noopener noreferrer"
                          >
                            View Signature
                          </a>
                          {sig.original_name ? (
                            <span className="small text-muted">{sig.original_name}</span>
                          ) : null}
                        </>
                      ) : (
                        <span className="small text-muted">No signature uploaded</span>
                      )}
                      <form className="d-flex flex-wrap align-items-center gap-2" onSubmit={onSignatureSubmit}>
                        <input type="hidden" name="report_date" value={date} />
                        <input type="hidden" name="school_year" value={schoolYear} />
                        <input type="hidden" name="semester" value={semester} />
                        <input type="hidden" name="return_url" value={typeof window !== 'undefined' ? window.location.href : ''} />
                        <input
                          type="file"
                          name="signature_file"
                          className="form-control form-control-sm"
                          accept=".jpg,.jpeg,.png,.webp,.gif,.pdf"
                          required
                        />
                        <button type="submit" className="btn btn-sm btn-primary">
                          {sig?.filename ? 'Replace' : 'Upload'}
                        </button>
                      </form>
                    </div>
                  ) : null}
                </div>
                <div className="table-responsive">
                  <table className="table table-striped align-middle mb-0">
                    <thead>
                      <tr>
                        <th>Student</th>
                        <th>Class/Section</th>
                        <th>Dismissal Time</th>
                        <th>Reason</th>
                        <th>Status</th>
                      </tr>
                    </thead>
                    <tbody>
                      {(rows as Array<Record<string, unknown>>).map((r, i) => (
                        <tr key={i}>
                          <td>{`${r.firstname ?? ''} ${r.lastname ?? ''}`.trim()}</td>
                          <td>{String(r.class_section_name ?? '—')}</td>
                          <td>
                            {r.dismiss_time ? String(String(r.dismiss_time).slice(0, 5)) : '—'}
                          </td>
                          <td style={{ maxWidth: 420, whiteSpace: 'normal' }}>{String(r.reason ?? '')}</td>
                          <td>
                            <span className={`badge bg-${badgeClass(String(r.status ?? '').toLowerCase())}`}>
                              {String(r.status ?? 'new').replace(/^\w/, (c) => c.toUpperCase())}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )
        })
      )}
    </div>
  )
}

function formatMdY(ymd: string): string {
  const [y, m, d] = ymd.split('-')
  return `${m}-${d}-${y}`
}
