import { useEffect, useState, type FormEvent } from 'react'
import { Link } from 'react-router-dom'
import {
  fetchParentProfile,
  fetchParentRegistrationOverview,
  storeParentEmergencyContact,
  storeParentRegistration,
  updateParentProfile,
} from '../../api/session'
import type { ParentEnrollmentStudent, ParentProfileRecord } from '../../api/types'
import { CiEmergencyContactFormPartial, CiFlashMessages, CiStandardStudentTable, CiStudentFormPartial } from '../../components/CiPartials'
import { ParentParityShell } from './ParentParityShell'

function Notice({ message, type = 'success' }: { message: string | null; type?: 'success' | 'warning' }) {
  return message ? <CiFlashMessages messages={[{ type, message }]} /> : null
}

export function ParentEditAllStudentsPage() {
  const [students, setStudents] = useState<ParentEnrollmentStudent[]>([])
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      try {
        const res = await fetchParentRegistrationOverview()
        if (!cancelled) setStudents(res.existingKids ?? [])
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load students.')
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [])

  return (
    <ParentParityShell title="Edit all students" ciViewFile="register_student.php" legacyCiRoutes={['/parent/edit-all-students']}>
      <Notice message={error} type="warning" />
      {loading ? (
        <p className="text-muted small">Loading...</p>
      ) : (
        <CiStandardStudentTable
          rows={students.map((student) => ({
            ...student,
            first_name: student.firstname,
            last_name: student.lastname,
            Grade: student.registration_grade,
          }))}
          customHeaders={['Class']}
          customKeys={['class_section']}
          emptyText="No students found."
        />
      )}
      {!loading && students.length > 0 ? (
        <div className="d-flex flex-wrap gap-2">
          {students.map((student) => (
            <Link key={student.id} className="btn btn-sm btn-outline-primary" to={`/app/parent/students/${student.id}/edit`}>
              Edit {student.firstname}
            </Link>
          ))}
        </div>
      ) : null}
    </ParentParityShell>
  )
}

export function ParentAddEmergencyFormPage() {
  const [status, setStatus] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

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

  return (
    <ParentParityShell title="Add emergency contact" ciViewFile="edit_emergency_contact.php" legacyCiRoutes={['/parent/add-emergency-form']}>
      <Notice message={status} />
      <Notice message={error} type="warning" />
      <form onSubmit={onSubmit}>
        <CiEmergencyContactFormPartial />
        <button className="btn btn-success" type="submit">Add contact</button>
      </form>
    </ParentParityShell>
  )
}

export function ParentAddStudentFormPage() {
  const [status, setStatus] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    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 storeParentRegistration({
        students: [{
          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',
          is_new: true,
          allergies,
          medical_conditions: medicalConditions,
        }],
      })
      setStatus('Student added.')
      e.currentTarget.reset()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to add student.')
    }
  }

  return (
    <ParentParityShell title="Add student" ciViewFile="register_student.php" legacyCiRoutes={['/parent/add-student-form']}>
      <Notice message={status} />
      <Notice message={error} type="warning" />
      <form onSubmit={onSubmit}>
        <CiStudentFormPartial />
        <button className="btn btn-success" type="submit">Add student</button>
      </form>
    </ParentParityShell>
  )
}

export function ParentUpdateProfileParityPage() {
  const [profile, setProfile] = useState<ParentProfileRecord | null>(null)
  const [status, setStatus] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      try {
        const res = await fetchParentProfile()
        if (!cancelled) setProfile(res.profile)
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load profile.')
      }
    })()
    return () => {
      cancelled = true
    }
  }, [])

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const form = new FormData(e.currentTarget)
    setStatus(null)
    setError(null)
    try {
      const res = await updateParentProfile({
        firstname: String(form.get('firstname') ?? ''),
        lastname: String(form.get('lastname') ?? ''),
        cellphone: String(form.get('cellphone') ?? ''),
        address_street: String(form.get('address_street') ?? ''),
        city: String(form.get('city') ?? ''),
        state: String(form.get('state') ?? ''),
        zip: String(form.get('zip') ?? ''),
      })
      setProfile(res.profile)
      setStatus('Profile updated.')
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to update profile.')
    }
  }

  return (
    <ParentParityShell title="Update profile" ciViewFile="register_student.php" legacyCiRoutes={['PATCH /api/v1/parents/profile']}>
      <Notice message={status} />
      <Notice message={error} type="warning" />
      <form className="row g-3" onSubmit={onSubmit}>
        <div className="col-md-6"><label className="form-label">First name</label><input name="firstname" className="form-control" defaultValue={profile?.firstname ?? ''} required /></div>
        <div className="col-md-6"><label className="form-label">Last name</label><input name="lastname" className="form-control" defaultValue={profile?.lastname ?? ''} required /></div>
        <div className="col-md-6"><label className="form-label">Cellphone</label><input name="cellphone" className="form-control" defaultValue={profile?.cellphone ?? ''} required /></div>
        <div className="col-md-6"><label className="form-label">Street</label><input name="address_street" className="form-control" defaultValue={profile?.address_street ?? ''} required /></div>
        <div className="col-md-4"><label className="form-label">City</label><input name="city" className="form-control" defaultValue={profile?.city ?? ''} required /></div>
        <div className="col-md-4"><label className="form-label">State</label><input name="state" className="form-control" defaultValue={profile?.state ?? ''} required /></div>
        <div className="col-md-4"><label className="form-label">Zip</label><input name="zip" className="form-control" defaultValue={profile?.zip ?? ''} required /></div>
        <div className="col-12"><button className="btn btn-success" type="submit">Save profile</button></div>
      </form>
    </ParentParityShell>
  )
}
