import { useMemo } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { useAuth } from '../../auth/AuthProvider'
import { TeacherShell } from './TeacherShell'
import { useTeacherResource } from './useTeacherResource'
import './TeacherClassViewPage.css'

export type TeacherClassViewStudent = {
  student_id?: number
  firstname?: string
  lastname?: string
  school_id?: string | null
  is_new?: unknown
  photo_consent?: unknown
  age?: number | null
  medical_conditions?: string[]
  allergies?: string[]
  medical_conditions_text?: string
  allergies_text?: string
}

export type TeacherClassViewClassRow = {
  class_section_id?: number
  class_section_name?: string
  class_id?: number | null
  class_name?: string | null
}

export type TeacherClassViewAssignedNames = {
  mains?: string[]
  tas?: string[]
  others?: string[]
}

export type TeacherClassViewPayload = {
  ok?: boolean
  message?: string
  teacher?: Record<string, unknown> | null
  classes?: TeacherClassViewClassRow[]
  students?: TeacherClassViewStudent[]
  students_by_section?: Record<string, TeacherClassViewStudent[]>
  assigned_names?: Record<string, TeacherClassViewAssignedNames>
  active_class_section_id?: number | null
  /** Display name for `active_class_section_id` (from `classSection`). */
  class_section_name?: string | null
}

function unwrapTeacherClassView(raw: unknown): TeacherClassViewPayload | null {
  if (raw == null || typeof raw !== 'object') return null
  const o = raw as Record<string, unknown>
  const inner = o.data
  if (inner != null && typeof inner === 'object' && !Array.isArray(inner)) {
    return inner as TeacherClassViewPayload
  }
  return raw as TeacherClassViewPayload
}

function isTruthyOne(v: unknown): boolean {
  if (v === true || v === 1) return true
  const s = String(v).toLowerCase().trim()
  return s === '1' || s === 'true' || s === 'yes'
}

function formatList(names: string[] | undefined): string {
  if (!names || names.length === 0) return '—'
  return names.join(', ')
}

function NewStudentBadge({ isNew }: { isNew: boolean }) {
  return (
    <span className={`badge rounded-pill ${isNew ? 'text-bg-warning text-dark' : 'text-bg-success'}`}>
      {isNew ? 'Yes' : 'No'}
    </span>
  )
}

function PhotoConsentBadge({ consent }: { consent: boolean }) {
  return (
    <span className={`badge rounded-pill ${consent ? 'text-bg-success' : 'text-bg-danger'}`}>
      {consent ? 'Yes' : 'No'}
    </span>
  )
}

function AllergiesCell({ allergies }: { allergies: string[] }) {
  const list = (allergies ?? []).map((a) => String(a).trim()).filter(Boolean)
  if (list.length === 0) {
    return <span className="badge rounded-pill text-bg-success">None</span>
  }
  return (
    <div className="d-flex flex-wrap gap-1 justify-content-center">
      {list.map((a, i) => (
        <span key={`${a}-${i}`} className="badge rounded-pill text-bg-warning text-dark">
          {a}
        </span>
      ))}
    </div>
  )
}

function MedicalCell({ conditions }: { conditions: string[] }) {
  const list = (conditions ?? []).map((c) => String(c).trim()).filter(Boolean)
  if (list.length === 0) {
    return <span className="badge rounded-pill text-bg-success">None</span>
  }
  return (
    <div className="d-flex flex-wrap gap-1 justify-content-center">
      {list.map((c, i) => (
        <span
          key={`${c}-${i}`}
          className="badge rounded-pill text-bg-warning text-dark text-wrap text-start mw-100"
        >
          {c}
        </span>
      ))}
    </div>
  )
}

/** `GET /api/v1/teacher/class-view` — roster with badges (parity with legacy class view). */
export function TeacherClassViewPage() {
  const { user } = useAuth()
  const [search] = useSearchParams()
  const sectionQ = search.get('class_section_id')?.trim() ?? ''
  const authSectionId = user?.class_section_id != null ? String(user.class_section_id).trim() : ''
  const effectiveSectionId = sectionQ || authSectionId
  const path = useMemo(() => {
    const q = effectiveSectionId ? `?class_section_id=${encodeURIComponent(effectiveSectionId)}` : ''
    return `/class-view${q}`
  }, [effectiveSectionId])

  const { data: raw, loading, error, reload } = useTeacherResource<unknown>(path)
  const payload = useMemo(() => unwrapTeacherClassView(raw), [raw])

  const activeSectionId = payload?.active_class_section_id ?? null
  const classes = payload?.classes ?? []
  const students = payload?.students ?? []
  const assigned = payload?.assigned_names ?? {}

  const activeMeta = useMemo(() => {
    const id = activeSectionId
    if (id == null) return null
    return classes.find((c) => Number(c.class_section_id) === Number(id)) ?? null
  }, [classes, activeSectionId])

  const namesForSection = useMemo(() => {
    if (activeSectionId == null) return { mains: [] as string[], tas: [] as string[] }
    const key = String(activeSectionId)
    const block = assigned[key] ?? assigned[Number(activeSectionId)]
    return {
      mains: block?.mains ?? [],
      tas: block?.tas ?? [],
    }
  }, [assigned, activeSectionId])

  const apiSectionName = payload?.class_section_name

  const gradeSectionLabel = useMemo(() => {
    const sectionName =
      (apiSectionName != null && String(apiSectionName).trim() !== ''
        ? String(apiSectionName).trim()
        : null) ?? (activeMeta?.class_section_name ? String(activeMeta.class_section_name).trim() : null)
    if (sectionName) return sectionName
    if (activeSectionId != null) return String(activeSectionId)
    return '—'
  }, [activeMeta, activeSectionId, apiSectionName])

  return (
    <TeacherShell
      title="Students Class List"
      titleClassName="text-center fw-bold"
      loading={loading}
      error={error}
    >
      <div className="d-flex flex-wrap justify-content-end gap-2 mb-3">
        {activeSectionId != null ? (
          <Link to="/app/teacher/exam-drafts" className="btn btn-success btn-sm">
            Exam Drafts
          </Link>
        ) : null}
        <button type="button" className="btn btn-outline-secondary btn-sm" onClick={() => reload()}>
          Refresh
        </button>
      </div>

      {!loading && raw != null && payload == null ? (
        <div className="alert alert-warning">
          Unexpected response shape.
          <pre className="small mb-0 mt-2 bg-light p-2 rounded overflow-auto" style={{ maxHeight: 200 }}>
            {JSON.stringify(raw, null, 2)}
          </pre>
        </div>
      ) : null}

      {payload && payload.ok === false ? (
        <div className="alert alert-danger">{String(payload.message ?? 'Unable to load class view.')}</div>
      ) : null}

      {payload && payload.ok !== false ? (
        <div className="teacher-class-view">
          {classes.length === 0 ? (
            <div className="alert alert-info">No classes are assigned to you for the current term.</div>
          ) : (
            <>
              <div className="text-center text-muted small mb-3 teacher-class-view__meta">
                <div>
                  <span className="fw-semibold text-body">Teachers:</span> {formatList(namesForSection.mains)}
                </div>
                <div>
                  <span className="fw-semibold text-body">Teacher Assistants:</span>{' '}
                  {formatList(namesForSection.tas)}
                </div>
                <div>
                  <span className="fw-semibold text-body">Grade-Section:</span> {gradeSectionLabel}
                </div>
              </div>

              {classes.length > 1 ? (
                <div className="d-flex flex-wrap justify-content-center gap-2 mb-3">
                  {classes.map((c) => {
                    const id = Number(c.class_section_id ?? 0)
                    if (!id) return null
                    const active = activeSectionId != null && Number(activeSectionId) === id
                    return (
                      <Link
                        key={id}
                        to={`/app/teacher/class-view?class_section_id=${encodeURIComponent(String(id))}`}
                        className={`btn btn-sm ${active ? 'btn-primary' : 'btn-outline-primary'}`}
                      >
                        {c.class_section_name || `Section ${id}`}
                      </Link>
                    )
                  })}
                </div>
              ) : null}

              {students.length === 0 ? (
                <p className="text-muted text-center mb-0">No students in this class for the current term.</p>
              ) : (
                <div className="table-responsive shadow-sm rounded border bg-white">
                  <table className="table table-bordered table-sm align-middle mb-0 teacher-class-view__table">
                    <thead>
                      <tr>
                        <th scope="col" className="text-center text-nowrap">
                          #
                        </th>
                        <th scope="col">School ID</th>
                        <th scope="col">First Name</th>
                        <th scope="col">Last Name</th>
                        <th scope="col" className="text-center text-nowrap">
                          Age
                        </th>
                        <th scope="col" className="text-center">
                          New Student
                        </th>
                        <th scope="col" className="text-center">
                          Take Photo
                        </th>
                        <th scope="col" className="text-center">
                          Allergies
                        </th>
                        <th scope="col" className="text-center">
                          Medical Conditions
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {students.map((row, idx) => {
                        const sid = row.student_id ?? idx
                        const allergies =
                          Array.isArray(row.allergies) && row.allergies.length > 0
                            ? row.allergies
                            : row.allergies_text
                              ? row.allergies_text.split(',').map((s) => s.trim())
                              : []
                        const medical =
                          Array.isArray(row.medical_conditions) && row.medical_conditions.length > 0
                            ? row.medical_conditions
                            : row.medical_conditions_text
                              ? row.medical_conditions_text.split(',').map((s) => s.trim())
                              : []
                        return (
                          <tr key={sid}>
                            <td className="text-center text-muted">{idx + 1}</td>
                            <td>{row.school_id != null && row.school_id !== '' ? String(row.school_id) : '—'}</td>
                            <td>{row.firstname ?? '—'}</td>
                            <td>{row.lastname ?? '—'}</td>
                            <td className="text-center">{row.age != null ? String(row.age) : '—'}</td>
                            <td className="text-center">
                              <NewStudentBadge isNew={isTruthyOne(row.is_new)} />
                            </td>
                            <td className="text-center">
                              <PhotoConsentBadge consent={isTruthyOne(row.photo_consent)} />
                            </td>
                            <td className="text-center">
                              <AllergiesCell allergies={allergies} />
                            </td>
                            <td className="text-center">
                              <MedicalCell conditions={medical} />
                            </td>
                          </tr>
                        )
                      })}
                    </tbody>
                  </table>
                </div>
              )}
            </>
          )}
        </div>
      ) : null}
    </TeacherShell>
  )
}
