import { useEffect, useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import {
  fetchParentAttendance,
  fetchParentEnrollments,
  fetchParentInvoices,
  fetchParentProfile,
} from '../../api/session'
import type { ParentAttendanceRow, ParentEnrollmentStudent, ParentInvoiceRow, ParentProfileRecord } from '../../api/types'
import { useAuth } from '../../auth/AuthProvider'

function displayName(p: ParentProfileRecord | null): string {
  if (!p) return ''
  const fn = (p.firstname ?? '').trim()
  const ln = (p.lastname ?? '').trim()
  const full = `${fn} ${ln}`.trim()
  return full || (p.email ?? '').trim()
}

export function ParentHomePage() {
  const { user } = useAuth()
  const [profile, setProfile] = useState<ParentProfileRecord | null>(null)
  const [students, setStudents] = useState<ParentEnrollmentStudent[]>([])
  const [attendance, setAttendance] = useState<ParentAttendanceRow[]>([])
  const [invoices, setInvoices] = useState<ParentInvoiceRow[]>([])
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      setLoading(true)
      try {
        const [data, enrollmentData, attendanceData, invoiceData] = await Promise.all([
          fetchParentProfile(),
          fetchParentEnrollments(null),
          fetchParentAttendance(null),
          fetchParentInvoices(null),
        ])
        if (cancelled) return
        setProfile(data.profile ?? null)
        setStudents(enrollmentData.students ?? [])
        setAttendance(attendanceData.attendance ?? [])
        setInvoices(invoiceData.invoices ?? [])
        setError(null)
      } catch (e) {
        if (!cancelled) {
          setProfile(null)
          setError(e instanceof Error ? e.message : 'Unable to load profile.')
        }
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [])

  const greeting = useMemo(() => {
    const fromApi = displayName(profile)
    if (fromApi) return fromApi
    return user?.name?.trim() || 'Parent'
  }, [profile, user?.name])

  const absentCount = attendance.filter((row) => row.status.toLowerCase() === 'absent').length
  const balance = invoices.reduce((sum, invoice) => sum + (Number(invoice.balance) || 0), 0)

  return (
    <div>
      <div className="text-center mb-4">
        <h2 className="h4 text-success" style={{ fontFamily: 'Arial, sans-serif' }}>
          Parent dashboard
        </h2>
      </div>

      {error ? (
        <div className="alert alert-warning">
          {error}{' '}
          <span className="text-muted">
            Parent-only APIs require a parent account. Use the general{' '}
            if you landed here by mistake.
          </span>
        </div>
      ) : null}

      {loading ? (
        <p className="text-muted">Loading…</p>
      ) : (
        <div className="parent-dashboard-circles row g-4 justify-content-center text-center mb-4">
          <div className="col-auto"><Link to="/parent_guide.pdf" className="parent-circle bg-info text-white"><strong>Your Quick Guide</strong></Link></div>
          <div className="col-auto"><div className="parent-circle bg-primary text-white"><strong>{greeting}</strong><small>{profile?.email ?? 'Parent account'}</small></div></div>
          <div className="col-auto"><Link to="/app/parent/register-student" className="parent-circle bg-success text-white"><strong>Students</strong><small>{students.length} total</small></Link></div>
          <div className="col-auto"><Link to="/app/parent/attendance" className="parent-circle bg-danger text-white"><strong>Absences</strong><small>{absentCount} absent</small></Link></div>
          <div className="col-auto"><Link to="/app/parent/report-attendance" className="parent-circle bg-secondary text-white"><strong>Report Absence</strong></Link></div>
          <div className="col-auto"><Link to="/app/parent/scores" className="parent-circle bg-warning text-dark"><strong>Scores</strong><small>View grades</small></Link></div>
          <div className="col-auto"><Link to="/app/parent/report-cards" className="parent-circle bg-dark text-white"><strong>Report Cards</strong></Link></div>
          <div className="col-auto"><Link to="/app/parent/enroll-classes" className="parent-circle bg-info text-white"><strong>Enrollment</strong><small>{students.filter((s) => s.enrollment_status).length} records</small></Link></div>
          <div className="col-auto"><Link to="/app/parent/payment" className="parent-circle bg-secondary text-white"><strong>Payment</strong><small>${balance.toFixed(2)}</small></Link></div>
        </div>
      )}
    </div>
  )
}
