import { type FormEvent, useId, useState, type ChangeEvent } from 'react'
import { updateAdministratorAttendance } from '../../api/session'

export type AttendanceEditModalProps = {
  studentId: string | number
  studentFirst?: string | null
  studentLast?: string | null
  classId: number
  sectionId: number
  /** Called after successful save */
  onSaved?: () => void
}

/**
 * Port of `Views/attendance/edit_modal.php` — embedded in flows that need inline attendance edits.
 * Mount inside a Bootstrap modal wrapper or render with `show` pattern.
 */
export function AttendanceEditModalBody({
  studentId,
  studentFirst,
  studentLast,
  classId,
  sectionId,
  onSaved,
}: AttendanceEditModalProps) {
  const uid = useId()
  const statusId = `status-${uid}`
  const dateId = `date-${uid}`
  const reasonId = `reason-${uid}`
  const reportedId = `reported-${uid}`

  const [status, setStatus] = useState('present')
  const [date, setDate] = useState(() => new Date().toISOString().slice(0, 10))
  const [reason, setReason] = useState('')
  const [reported, setReported] = useState('0')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const name = `${studentFirst ?? ''} ${studentLast ?? ''}`.trim() || `Student #${studentId}`

  const reasonRequired = status === 'absent' || status === 'late'
  const showReported = status === 'absent'

  function onStatusChange(ev: ChangeEvent<HTMLSelectElement>) {
    const v = ev.target.value
    setStatus(v)
    if (v !== 'absent') setReported('0')
    if (v === 'present') setReason('')
  }

  async function onSubmit(e: FormEvent) {
    e.preventDefault()
    setSaving(true)
    setError(null)
    try {
      await updateAdministratorAttendance({
        class_section_id: sectionId,
        student_id: Number(studentId),
        class_id: classId,
        status: status as 'present' | 'absent' | 'late',
        date,
        reason: reasonRequired ? reason : '',
        is_reported: showReported ? (reported === '1' ? 'yes' : 'no') : undefined,
      })
      onSaved?.()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Save failed.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <form onSubmit={onSubmit}>
      {error ? <div className="alert alert-danger py-2">{error}</div> : null}
      <div className="mb-3">
        <label className="form-label" htmlFor={statusId}>
          Status
        </label>
        <select
          id={statusId}
          className="form-select attendance-status"
          required
          value={status}
          onChange={onStatusChange}
        >
          <option value="present">Present</option>
          <option value="late">Late</option>
          <option value="absent">Absent</option>
        </select>
      </div>

      <div className="mb-3">
        <label className="form-label" htmlFor={dateId}>
          Date
        </label>
        <input
          id={dateId}
          type="date"
          className="form-control"
          required
          value={date}
          onChange={(ev) => setDate(ev.target.value)}
        />
      </div>

      <div className="mb-3">
        <label className="form-label" htmlFor={reasonId}>
          Reason
        </label>
        <textarea
          id={reasonId}
          name="reason"
          className="form-control attendance-reason"
          rows={3}
          placeholder="Enter reason for absence or lateness"
          value={reason}
          disabled={!reasonRequired}
          required={reasonRequired}
          onChange={(ev) => setReason(ev.target.value)}
        />
      </div>

      <div className={`mb-3${showReported ? '' : ' d-none'}`}>
        <label className="form-label" htmlFor={reportedId}>
          Absence Reported?
        </label>
        <select
          id={reportedId}
          className="form-select"
          value={reported}
          onChange={(ev) => setReported(ev.target.value)}
        >
          <option value="0">No</option>
          <option value="1">Yes</option>
        </select>
        <div className="form-text">Select “Yes” if the parent/guardian reported this absence.</div>
      </div>

      <input type="hidden" name="student_id" value={String(studentId)} />

      <div className="modal-footer px-0 pb-0">
        <button type="button" className="btn btn-secondary" data-bs-dismiss="modal">
          Close
        </button>
        <button type="submit" className="btn btn-primary" disabled={saving}>
          {saving ? 'Saving…' : 'Save changes'}
        </button>
      </div>

      <p className="small text-muted mb-0 mt-2">{name}</p>
    </form>
  )
}
