import { useEffect, useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import { fetchAdministratorDashboardMetrics, fetchLandingAdminDashboard } from '../../api/session'
import type { AdministratorDashboardMetricsResponse, LandingPageRecord } from '../../api/types'
import { useAuth } from '../../auth/AuthProvider'

export function AdminLandingDashboardPage() {
  const { user } = useAuth()
  const landingKind = user?.roles?.administrator ? 'administrator' : 'admin'
  const [landing, setLanding] = useState<LandingPageRecord | null>(null)
  const [metrics, setMetrics] = useState<AdministratorDashboardMetricsResponse | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      setLoading(true)
      try {
        const [landingResponse, metricsResponse] = await Promise.all([
          fetchLandingAdminDashboard(landingKind),
          fetchAdministratorDashboardMetrics(),
        ])
        if (cancelled) return
        setLanding(landingResponse.data?.landing ?? null)
        setMetrics(metricsResponse)
        setError(null)
      } catch (e) {
        if (!cancelled) {
          setError(e instanceof Error ? e.message : 'Unable to load admin landing dashboard.')
        }
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [landingKind])

  const counts = metrics?.counts ?? {}
  const cards = useMemo(
    () => [
      { label: 'Students', value: counts.students ?? 0, icon: 'bi bi-mortarboard-fill', tone: 'primary' },
      { label: 'Teachers', value: counts.teachers ?? 0, icon: 'bi bi-person-video3', tone: 'success' },
      { label: 'Teacher Assistants', value: counts.teacherAssistants ?? 0, icon: 'bi bi-people-fill', tone: 'warning' },
      { label: 'Admins', value: counts.admins ?? 0, icon: 'bi bi-person-badge-fill', tone: 'info' },
      { label: 'Parents', value: counts.parents ?? 0, icon: 'bi bi-people', tone: 'secondary' },
    ],
    [counts.admins, counts.parents, counts.students, counts.teacherAssistants, counts.teachers],
  )

  const shortcuts = [
    { label: 'Administrator Dashboard', to: '/app/administrator/dashboard', icon: 'bi bi-speedometer2' },
    { label: 'Manage Users', to: '/app/administrator/manage_users', icon: 'bi bi-people' },
    { label: 'Daily Attendance', to: '/app/administrator/daily_attendance', icon: 'bi bi-calendar-check' },
    { label: 'Teacher Submissions', to: '/app/administrator/teacher-submissions', icon: 'bi bi-journal-check' },
    { label: 'Calendar', to: '/app/administrator/calendar', icon: 'bi bi-calendar3' },
    { label: 'Support / Contact', to: '/app/administrator/communications', icon: 'bi bi-life-preserver' },
  ]

  return (
    <div className="container-fluid py-4">
      <section className="rounded-4 p-4 p-lg-5 mb-4 text-white" style={{ background: 'linear-gradient(135deg, #1f7a1f 0%, #3ca73c 55%, #91c84a 100%)' }}>
        <div className="row align-items-center g-4">
          <div className="col-lg-8">
            <div className="text-uppercase small fw-semibold opacity-75 mb-2">Landing Page</div>
            <h1 className="display-6 mb-3">Welcome to Al Rahma Sunday School</h1>
            <p className="lead mb-2">Welcome, {user?.name || 'Admin'}.</p>
            <p className="mb-0 opacity-75">
              This is the {landing?.role || landingKind} dashboard.
            </p>
          </div>
          <div className="col-lg-4">
            <div className="bg-white bg-opacity-10 rounded-4 p-4 border border-white border-opacity-25">
              <div className="small text-uppercase fw-semibold mb-2">API Status</div>
              <div className="fs-5 fw-semibold mb-1">{landing?.dashboard || 'admin'}</div>
              <div className="small opacity-75">
                Role: {landing?.role || 'admin'}
              </div>
            </div>
          </div>
        </div>
      </section>

      {error ? <div className="alert alert-danger">{error}</div> : null}
      {loading ? <p className="text-muted">Loading admin landing dashboard…</p> : null}

      <section className="mb-4">
        <div className="row g-3">
          {cards.map((card) => (
            <div key={card.label} className="col-6 col-xl">
              <div className={`card border-0 shadow-sm h-100 bg-${card.tone} bg-opacity-10`}>
                <div className="card-body">
                  <div className="d-flex align-items-center justify-content-between mb-3">
                    <div className={`text-${card.tone}`}><i className={card.icon} aria-hidden /></div>
                    <div className="fs-3 fw-bold">{card.value}</div>
                  </div>
                  <div className="text-muted small">{card.label}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </section>

      <section className="card border-0 shadow-sm">
        <div className="card-body">
          <div className="d-flex justify-content-between align-items-center mb-3">
            <h2 className="h5 mb-0">Quick Links</h2>
            <Link className="btn btn-outline-secondary btn-sm" to="/app/home">Open full dashboard</Link>
          </div>
          <div className="row g-3">
            {shortcuts.map((item) => (
              <div key={item.to} className="col-md-6 col-xl-4">
                <Link className="btn btn-outline-primary w-100 text-start d-flex align-items-center gap-2 py-3" to={item.to}>
                  <i className={item.icon} aria-hidden />
                  <span>{item.label}</span>
                </Link>
              </div>
            ))}
          </div>
        </div>
      </section>
    </div>
  )
}
