import { useEffect, useState, type FormEvent } from 'react'
import { Link } from 'react-router-dom'
import {
  fetchParentAttendanceReportsList,
  fetchParentAuthorizedUsers,
  inviteParentAuthorizedUser,
} from '../../api/session'
import type { ParentAttendanceReportsListResponse, ParentAuthorizedUserRow } from '../../api/types'
import { CiFlashMessages } from '../../components/CiPartials'
import { ParentParityShell } from './ParentParityShell'

/** Secondary / authorized users — `GET /api/v1/parents/authorized-users`. */
export function ParentAuthorizedUsersPage() {
  const [rows, setRows] = useState<ParentAuthorizedUserRow[]>([])
  const [email, setEmail] = useState('')
  const [status, setStatus] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)

  async function load(cancelled?: () => boolean) {
    setLoading(true)
    try {
      const res = await fetchParentAuthorizedUsers()
      if (cancelled?.()) return
      setRows(res.data ?? [])
      setError(null)
    } catch (e) {
      if (!cancelled?.()) setError(e instanceof Error ? e.message : 'Unable to load.')
    } finally {
      if (!cancelled?.()) setLoading(false)
    }
  }

  useEffect(() => {
    let cancelled = false
    void load(() => cancelled)
    return () => {
      cancelled = true
    }
  }, [])

  async function onInvite(e: FormEvent) {
    e.preventDefault()
    setStatus(null)
    setError(null)
    try {
      const res = await inviteParentAuthorizedUser(email)
      setStatus(res.message ?? 'Authorized user added.')
      setEmail('')
      await load()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unable to add authorized user.')
    }
  }

  return (
    <ParentParityShell
      title="Authorized users"
      ciViewFile="add_second_parent.php"
      legacyCiRoutes={['GET /api/v1/parents/authorized-users']}
    >
      <CiFlashMessages
        messages={[
          ...(status ? [{ type: 'success' as const, message: status }] : []),
          ...(error ? [{ type: 'warning' as const, message: error }] : []),
        ]}
      />
      <form className="row g-2 align-items-end mb-3" onSubmit={onInvite}>
        <div className="col-md-8">
          <label className="form-label" htmlFor="authorized_user_email">
            Email
          </label>
          <input
            id="authorized_user_email"
            type="email"
            className="form-control"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
        </div>
        <div className="col-md-4">
          <button type="submit" className="btn btn-success w-100">
            Add authorized user
          </button>
        </div>
      </form>
      <div className="table-responsive">
        <table className="table table-sm table-striped align-middle">
          <thead>
            <tr>
              <th>ID</th>
              <th>Email</th>
              <th>Added</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={3} className="text-muted">Loading…</td>
              </tr>
            ) : rows.length === 0 ? (
              <tr>
                <td colSpan={3} className="text-muted">No authorized users.</td>
              </tr>
            ) : (
              rows.map((row) => (
                <tr key={row.id ?? row.email}>
                  <td>{row.id ?? '—'}</td>
                  <td>{row.email ?? '—'}</td>
                  <td>{row.created_at ?? '—'}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </ParentParityShell>
  )
}

/** Submitted reports — `GET /api/v1/parents/attendance-reports`. */
export function ParentAttendanceReportsHistoryPage() {
  const [payload, setPayload] = useState<ParentAttendanceReportsListResponse | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)

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

  return (
    <ParentParityShell
      title="My attendance reports"
      ciViewFile="report_attendance.php"
      legacyCiRoutes={['GET /api/v1/parents/attendance-reports']}
    >
      <CiFlashMessages messages={error ? [{ type: 'warning', message: error }] : []} />
      {loading ? (
        <p className="text-muted small">Loading…</p>
      ) : (
        <div className="table-responsive">
          <table className="table table-sm table-striped align-middle mb-0">
            <thead>
              <tr>
                <th>Student</th>
                <th>Date</th>
                <th>Type</th>
                <th>Status</th>
                <th>Reason</th>
              </tr>
            </thead>
            <tbody>
              {(payload?.reports ?? []).length === 0 ? (
                <tr>
                  <td colSpan={5} className="text-muted">No attendance reports.</td>
                </tr>
              ) : (
                (payload?.reports ?? []).map((report) => (
                  <tr key={String(report.id ?? `${report.student_id}-${report.report_date}`)}>
                    <td>{`${report.firstname ?? ''} ${report.lastname ?? ''}`.trim() || '—'}</td>
                    <td>{String(report.report_date ?? '—')}</td>
                    <td>{String(report.type ?? '—')}</td>
                    <td>{String(report.status ?? '—')}</td>
                    <td>{String(report.reason ?? '—')}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      )}
      <p className="small text-muted mt-2 mb-0">
        New submission:{' '}
        <Link to="/app/parent/report-attendance">Report attendance form</Link>
      </p>
    </ParentParityShell>
  )
}
