import { useEffect, useMemo, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { apiUrl } from '../../lib/apiOrigin'
import { fetchClassProgressDetail, fetchClassProgressMeta } from '../../api/session'
import type { ClassProgressReportRow } from '../../api/types'
import { ClassProgressUnitDisplay } from './ClassProgressUnitDisplay'
import { FLAG_LABELS, formatProgressDate } from './classProgressUtils'

function attachmentHref(att: {
  id?: number
  download_url?: string | null
  legacy?: boolean | number | null
}) {
  if (att.download_url) return att.download_url
  const id = att.id
  if (!id) return '#'
  const legacy = Boolean(att.legacy)
  return legacy
    ? apiUrl(`/admin/progress/attachment/${id}`)
    : apiUrl(`/admin/progress/attachment-file/${id}`)
}

/** CI `admin/class_progress_view.php` */
export function ClassProgressViewPage() {
  const { id } = useParams()
  const reportId = Number(id)
  const [report, setReport] = useState<ClassProgressReportRow | null>(null)
  const [weeklyReports, setWeeklyReports] = useState<ClassProgressReportRow[]>([])
  const [subjectSections, setSubjectSections] = useState<Record<string, { label?: string; db_subject?: string }>>({})
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!reportId) return
    ;(async () => {
      try {
        const [detail, meta] = await Promise.all([
          fetchClassProgressDetail(reportId),
          fetchClassProgressMeta(),
        ])
        setReport(detail.data?.report ?? null)
        setWeeklyReports(detail.data?.weekly_reports ?? [])
        setSubjectSections(meta.data?.subject_sections ?? {})
        setError(null)
      } catch (e) {
        setError(e instanceof Error ? e.message : 'Unable to load progress report.')
      }
    })()
  }, [reportId])

  const reportsBySubject = useMemo(
    () => Object.fromEntries(weeklyReports.map((entry) => [String(entry.subject ?? ''), entry])),
    [weeklyReports],
  )

  const attachments = weeklyReports.flatMap((entry) =>
    (entry.attachments ?? []).map((attachment) => ({
      subject: entry.subject ?? 'Attachment',
      attachment,
      report_id: entry.id,
    })),
  )

  return (
    <div className="container py-4">
      {error ? <div className="alert alert-danger">{error}</div> : null}
      {report ? (
        <>
          <div className="d-flex align-items-center justify-content-between mb-3">
            <div>
              <h3 className="mb-0">Progress Report</h3>
              <div className="text-muted">
                {report.class_section_name ?? '-'} • {formatProgressDate(report.week_start)} →{' '}
                {formatProgressDate(report.week_end)}
              </div>
            </div>
            <Link to="/app/admin/progress" className="btn btn-outline-secondary">
              Back
            </Link>
          </div>

          <div className="row g-3">
            <div className="col-lg-8">
              {Object.entries(subjectSections).map(([slug, section]) => {
                const subjectName = section.db_subject ?? section.label ?? slug
                const isQuran = subjectName === 'Quran/Arabic'
                const homeworkLabel = isQuran ? 'Arabic Practice / Homework' : 'Assigned Homework'
                const entry = reportsBySubject[subjectName]
                return (
                  <div className="card shadow-sm mb-3" key={slug}>
                    <div className="card-header bg-white d-flex align-items-center justify-content-between">
                      <strong className="mb-0">{section.label ?? subjectName}</strong>
                    </div>
                    <div className="card-body">
                      {!entry ? (
                        <div className="text-muted">No entry submitted for this subject this week.</div>
                      ) : (
                        <>
                          <div className="mb-2">
                            <ClassProgressUnitDisplay
                              unitTitle={entry.unit_title}
                              isQuran={isQuran}
                              compact={false}
                            />
                          </div>
                          {String(entry.materials ?? '').trim() ? (
                            <div className="mb-2">
                              <strong>Materials:</strong> {entry.materials}
                            </div>
                          ) : null}
                          <div className="mb-3">
                            <strong>Activities</strong>
                            <div className="mt-1" style={{ whiteSpace: 'pre-wrap' }}>
                              {entry.covered || '-'}
                            </div>
                          </div>
                          <div className="mb-3">
                            <strong>{homeworkLabel}:</strong>
                            <div className="mt-1" style={{ whiteSpace: 'pre-wrap' }}>
                              {entry.homework || '-'}
                            </div>
                          </div>
                          {(entry.attachments ?? []).length > 0 ? (
                            <div className="mt-3">
                              <strong>Attachments:</strong>
                              <div className="d-flex flex-column gap-2 mt-2">
                                {(entry.attachments ?? []).map((att) => {
                                  const linkId = att.id ?? entry.id
                                  return (
                                    <a
                                      key={String(att.id ?? att.name ?? '')}
                                      className="btn btn-sm btn-outline-secondary text-start"
                                      href={attachmentHref({ ...att, id: linkId })}
                                      target="_blank"
                                      rel="noreferrer"
                                    >
                                      {att.name ?? 'Attachment'}
                                    </a>
                                  )
                                })}
                              </div>
                            </div>
                          ) : null}
                        </>
                      )}
                    </div>
                  </div>
                )
              })}
            </div>

            <div className="col-lg-4">
              <div className="card shadow-sm mb-3">
                <div className="card-header bg-white">
                  <strong>Summary</strong>
                </div>
                <div className="card-body">
                  <div className="mb-2">
                    <strong>Teacher:</strong> {String(report.teacher_name ?? '').trim() || '-'}
                  </div>
                  <div className="mb-2">
                    <strong>Submitted:</strong> {formatProgressDate(report.created_at, true)}
                  </div>
                  <div>
                    <strong>Status:</strong> {report.status_label ?? 'Unknown'}
                  </div>
                </div>
              </div>

              {(report.flags ?? []).length > 0 ? (
                <div className="card shadow-sm mb-3">
                  <div className="card-header bg-white">
                    <strong>Checklist</strong>
                  </div>
                  <div className="card-body d-flex flex-wrap gap-2">
                    {(report.flags ?? []).map((flag) => (
                      <span key={flag} className="badge bg-light text-dark border">
                        {FLAG_LABELS[flag] ?? flag.replace(/_/g, ' ')}
                      </span>
                    ))}
                  </div>
                </div>
              ) : null}

              {attachments.length > 0 ? (
                <div className="card shadow-sm">
                  <div className="card-header bg-white">
                    <strong>Attachments</strong>
                  </div>
                  <div className="card-body">
                    {attachments.map((item, index) => {
                      const att = item.attachment
                      const linkId = att.id ?? item.report_id
                      if (!linkId) return null
                      const label = `${item.subject} • ${att.name ?? 'Attachment'}`
                      return (
                        <a
                          key={`${linkId}-${index}`}
                          className="btn btn-outline-primary w-100 text-start mb-2"
                          href={attachmentHref({ ...att, id: linkId })}
                          target="_blank"
                          rel="noreferrer"
                        >
                          {label}
                        </a>
                      )
                    })}
                  </div>
                </div>
              ) : null}
            </div>
          </div>
        </>
      ) : null}
    </div>
  )
}
