import { useEffect, useState, type FormEvent } from 'react'
import { Link, useParams } from 'react-router-dom'
import {
  fetchClassProgressDetail,
  fetchParentEmergencyContacts,
  fetchParentRegistrationOverview,
  fetchReportCardAcknowledgement,
  fetchReportCardPdf,
  updateParentEmergencyContact,
  updateParentStudent,
} from '../../api/session'
import type {
  ClassProgressReportRow,
  ParentEmergencyContactRow,
  ParentEnrollmentStudent,
  ReportCardAcknowledgementRow,
} from '../../api/types'
import { CiEmergencyContactFormPartial, CiFlashMessages, CiStudentFormPartial } from '../../components/CiPartials'
import { ParentParityShell } from './ParentParityShell'

function fieldValue(value: unknown) {
  return value == null || value === '' ? '—' : String(value)
}

export function ParentProgressViewPage() {
  const { progressId } = useParams<{ progressId: string }>()
  const id = Number(progressId)
  const [reports, setReports] = useState<ClassProgressReportRow[]>([])
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!Number.isFinite(id) || id <= 0) return
    let cancelled = false
    ;(async () => {
      setLoading(true)
      try {
        const res = await fetchClassProgressDetail(id)
        if (cancelled) return
        const weekly = Object.values(res.data?.weekly_reports ?? {})
        const fallback = res.data?.report ? [res.data.report] : []
        setReports(weekly.length > 0 ? weekly : fallback)
        setError(null)
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load progress.')
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [id])

  return (
    <ParentParityShell
      title="Class progress detail"
      ciViewFile="class_progress_view.php"
      legacyCiRoutes={[`/parent/progress/view/${progressId ?? ''}`]}
    >
      {error ? <div className="alert alert-warning small">{error}</div> : null}
      {loading ? (
        <p className="text-muted small">Loading…</p>
      ) : (
        <div className="table-responsive">
          <table className="table table-sm table-bordered align-middle">
            <thead>
              <tr>
                <th>Subject</th>
                <th>Unit</th>
                <th>Covered</th>
                <th>Homework</th>
                <th>Status</th>
                <th>Support</th>
              </tr>
            </thead>
            <tbody>
              {reports.length === 0 ? (
                <tr><td colSpan={6} className="text-muted">No progress detail found.</td></tr>
              ) : reports.map((report) => (
                <tr key={report.id}>
                  <td>{fieldValue(report.subject)}</td>
                  <td>{fieldValue(report.unit_title)}</td>
                  <td>{fieldValue(report.covered)}</td>
                  <td>{fieldValue(report.homework)}</td>
                  <td>{fieldValue(report.status_label ?? report.status)}</td>
                  <td>{fieldValue(report.support_needed)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </ParentParityShell>
  )
}

export function ParentEmergencyContactEditPage() {
  const { contactId } = useParams<{ contactId: string }>()
  const id = Number(contactId)
  const [contact, setContact] = useState<ParentEmergencyContactRow | null>(null)
  const [status, setStatus] = useState<string | 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 fetchParentEmergencyContacts()
        if (cancelled) return
        setContact((res.contacts ?? []).find((row) => row.id === id) ?? null)
        setError(null)
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load contact.')
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [id])

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (!contact?.id) return
    setStatus(null)
    setError(null)
    const form = new FormData(e.currentTarget)
    try {
      await updateParentEmergencyContact(contact.id, {
        name: String(form.get('name') ?? ''),
        cellphone: String(form.get('cellphone') ?? ''),
        email: String(form.get('email') ?? ''),
        relation: String(form.get('relation') ?? ''),
      })
      setStatus('Emergency contact updated.')
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to update contact.')
    }
  }

  return (
    <ParentParityShell
      title="Emergency contact"
      ciViewFile="edit_emergency_contact.php"
      legacyCiRoutes={[
        '/parent/edit-emergency-contact',
        `/parent/edit_emergency_contact/${contactId ?? ''}`,
        `/parent/edit-emergency-contact/${contactId ?? ''}`,
      ]}
    >
      <CiFlashMessages
        messages={[
          ...(status ? [{ type: 'success' as const, message: status }] : []),
          ...(error ? [{ type: 'warning' as const, message: error }] : []),
        ]}
      />
      {loading ? <p className="text-muted small">Loading…</p> : null}
      {!loading && !contact ? <div className="alert alert-info small">Contact not found.</div> : null}
      {contact ? (
        <form onSubmit={onSubmit}>
          <CiEmergencyContactFormPartial defaultValues={contact} />
          <button className="btn btn-success" type="submit">Save contact</button>
        </form>
      ) : null}
    </ParentParityShell>
  )
}

/** Parity for CI student edit modal / edit_student flows (`edit_student_modal.php`). */
export function ParentStudentEditPage() {
  const { studentId } = useParams<{ studentId: string }>()
  const id = Number(studentId)
  const [student, setStudent] = useState<ParentEnrollmentStudent | null>(null)
  const [status, setStatus] = useState<string | 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 fetchParentRegistrationOverview()
        if (cancelled) return
        setStudent((res.existingKids ?? []).find((row) => row.id === id) ?? null)
        setError(null)
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load student.')
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [id])

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (!student?.id) return
    const form = new FormData(e.currentTarget)
    setStatus(null)
    setError(null)
    try {
      const allergies = form.getAll('allergies').map(String)
      const medicalConditions = form.getAll('medical_conditions').map(String)
      const allergyOther = String(form.get('allergies_other') ?? '').trim()
      const medicalOther = String(form.get('medical_conditions_other') ?? '').trim()
      if (allergyOther) allergies.push(allergyOther)
      if (medicalOther) medicalConditions.push(medicalOther)
      await updateParentStudent(student.id, {
        firstname: String(form.get('firstname') ?? ''),
        lastname: String(form.get('lastname') ?? ''),
        dob: String(form.get('dob') ?? ''),
        gender: String(form.get('gender') ?? ''),
        registration_grade: String(form.get('registration_grade') ?? ''),
        photo_consent: form.get('photo_consent') === 'Yes',
        allergies,
        medical_conditions: medicalConditions,
      })
      setStatus('Student updated.')
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to update student.')
    }
  }

  return (
    <ParentParityShell
      title="Edit student"
      ciViewFile="edit_student_modal.php"
      legacyCiRoutes={[
        `/parent/edit_student/${studentId ?? ''}`,
        `/parent/edit-student/${studentId ?? ''}`,
      ]}
    >
      <CiFlashMessages
        messages={[
          ...(status ? [{ type: 'success' as const, message: status }] : []),
          ...(error ? [{ type: 'warning' as const, message: error }] : []),
        ]}
      />
      {loading ? <p className="text-muted small">Loading…</p> : null}
      {!loading && !student ? <div className="alert alert-info small">Student not found.</div> : null}
      {student ? (
        <form onSubmit={onSubmit}>
          <CiStudentFormPartial defaultValues={student} />
          <button className="btn btn-success" type="submit">Save student</button>
        </form>
      ) : null}
    </ParentParityShell>
  )
}

/** CI `parent/report-cards/view/(:num)` — report card PDF / viewer. */
export function ParentReportCardsViewPage() {
  const { reportId } = useParams<{ reportId: string }>()
  const id = Number(reportId)
  const [url, setUrl] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!Number.isFinite(id) || id <= 0) return
    let objectUrl: string | null = null
    ;(async () => {
      try {
        const blob = await fetchReportCardPdf(id)
        objectUrl = URL.createObjectURL(blob)
        setUrl(objectUrl)
        setError(null)
      } catch (e) {
        setError(e instanceof Error ? e.message : 'Failed to load report card.')
      }
    })()
    return () => {
      if (objectUrl) URL.revokeObjectURL(objectUrl)
    }
  }, [id])

  return (
    <ParentParityShell
      title="Report card"
      ciViewFile="report_cards.php"
      legacyCiRoutes={[`/parent/report-cards/view/${reportId ?? ''}`]}
    >
      {error ? <div className="alert alert-warning small">{error}</div> : null}
      {!url && !error ? <p className="text-muted small">Loading report card…</p> : null}
      {url ? (
        <iframe title="Report card" src={url} className="w-100 border rounded" style={{ minHeight: '75vh' }} />
      ) : null}
    </ParentParityShell>
  )
}

/** CI `parent/progress/attachment/(:num)` — file download route. */
export function ParentProgressAttachmentPage() {
  const { attachmentId } = useParams<{ attachmentId: string }>()
  return (
    <ParentParityShell
      title="Class progress attachment"
      ciViewFile="class_progress_view.php"
      legacyCiRoutes={[`/parent/progress/attachment/${attachmentId ?? ''}`]}
    >
      <a className="btn btn-outline-primary" href={`/api/v1/class-progress/attachments/${attachmentId}`}>
        Download attachment
      </a>
    </ParentParityShell>
  )
}

/** CI `parent/progress/attachment-file/(:num)` — legacy file stream. */
export function ParentProgressAttachmentFilePage() {
  const { fileId } = useParams<{ fileId: string }>()
  return (
    <ParentParityShell
      title="Class progress attachment (legacy)"
      ciViewFile="class_progress_view.php"
      legacyCiRoutes={[`/parent/progress/attachment-file/${fileId ?? ''}`]}
    >
      <a className="btn btn-outline-primary" href={`/api/v1/class-progress/${fileId}/attachment`}>
        Download legacy attachment
      </a>
    </ParentParityShell>
  )
}

/** CI `POST parent/report-cards/sign/(:num)` — acknowledgement / signature flow. */
export function ParentReportCardsSignPage() {
  const { studentId } = useParams<{ studentId: string }>()
  const id = Number(studentId)
  const [ack, setAck] = useState<ReportCardAcknowledgementRow | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!Number.isFinite(id) || id <= 0) return
    let cancelled = false
    ;(async () => {
      try {
        const res = await fetchReportCardAcknowledgement(id)
        if (!cancelled) setAck(res.data ?? null)
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load acknowledgement.')
      }
    })()
    return () => {
      cancelled = true
    }
  }, [id])

  return (
    <ParentParityShell
      title="Sign report card"
      ciViewFile="report_cards.php"
      legacyCiRoutes={[`POST /parent/report-cards/sign/${studentId ?? ''}`]}
    >
      {error ? <div className="alert alert-warning small">{error}</div> : null}
      <dl className="row small">
        <dt className="col-sm-3">Student ID</dt><dd className="col-sm-9">{studentId}</dd>
        <dt className="col-sm-3">Viewed</dt><dd className="col-sm-9">{fieldValue(ack?.viewed_at)}</dd>
        <dt className="col-sm-3">Signed</dt><dd className="col-sm-9">{fieldValue(ack?.signed_at)}</dd>
        <dt className="col-sm-3">Signed name</dt><dd className="col-sm-9">{fieldValue(ack?.signed_name)}</dd>
      </dl>
      <Link className="btn btn-outline-primary" to={`/app/parent/report-cards/view/${studentId}`}>
        View report card
      </Link>
    </ParentParityShell>
  )
}
