import { type FormEvent, useEffect, useState } from 'react'
import { ApiHttpError, apiFetch } from '../../api/http'
import { PicturePolicyPartial } from './PicturePolicyPartial'

/**
 * Full media consent page from CI `picture_policy.php`.
 * Submit targets Laravel JSON endpoint (adjust path if your API differs).
 */
export function PicturePolicyPage() {
  useEffect(() => {
    const id = 'picture-policy-font-awesome'
    if (document.getElementById(id)) return
    const l = document.createElement('link')
    l.id = id
    l.rel = 'stylesheet'
    l.href = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css'
    document.head.appendChild(l)
    return () => document.getElementById(id)?.remove()
  }, [])

  const [msg, setMsg] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const fd = new FormData(e.currentTarget)
    const payload = {
      parent_name: String(fd.get('parent_name') ?? ''),
      student_names: String(fd.get('student_names') ?? ''),
      signature_date: String(fd.get('signature_date') ?? ''),
      contact_email: String(fd.get('contact_email') ?? ''),
      consent: fd.get('consent') === 'on',
    }
    if (!payload.consent) {
      setMsg('Please confirm you have read the policy.')
      return
    }
    setBusy(true)
    setMsg(null)
    try {
      await apiFetch('/api/v1/parent/policy/media-consent', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      })
      setMsg('Thank you — your consent has been recorded.')
    } catch (err: unknown) {
      setMsg(err instanceof ApiHttpError ? err.message : 'Submit failed.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="bg-light min-vh-100 py-4">
      <div
        className="mx-auto bg-white rounded-3 shadow overflow-hidden"
        style={{ maxWidth: 800 }}
      >
        <div
          className="text-white text-center py-4 px-3"
          style={{ background: 'linear-gradient(135deg, #4e73df 0%, #224abe 100%)' }}
        >
          <h1 className="h3 mb-0">Media Permission Policy</h1>
          <p className="mb-0 small">Al Rahma Sunday School</p>
        </div>

        <div className="p-4 p-md-5">
          <div className="alert alert-info d-flex align-items-center gap-3">
            <i className="fas fa-info-circle fa-2x" aria-hidden />
            <div>This policy allows the school to photograph students for educational and promotional purposes</div>
          </div>

          <h2 className="h4 mb-4">Parent/Guardian Media Consent Form</h2>

          <PicturePolicyPartial />

          <form className="mt-4 border-top pt-4" onSubmit={onSubmit}>
            <h5 className="mb-3">Parent/Guardian Consent</h5>
            <div className="row g-3 mb-3">
              <div className="col-md-6">
                <label className="form-label" htmlFor="parent_name">
                  Parent/Guardian Name *
                </label>
                <input type="text" className="form-control" id="parent_name" name="parent_name" required />
              </div>
              <div className="col-md-6">
                <label className="form-label" htmlFor="student_names">
                  Student Name(s) *
                </label>
                <input type="text" className="form-control" id="student_names" name="student_names" required />
              </div>
              <div className="col-md-6">
                <label className="form-label" htmlFor="signature_date">
                  Date *
                </label>
                <input type="date" className="form-control" id="signature_date" name="signature_date" required />
              </div>
              <div className="col-md-6">
                <label className="form-label" htmlFor="contact_email">
                  Email Address *
                </label>
                <input type="email" className="form-control" id="contact_email" name="contact_email" required />
              </div>
            </div>

            <div className="form-check mb-3">
              <input className="form-check-input" type="checkbox" id="consent" name="consent" required />
              <label className="form-check-label" htmlFor="consent">
                I have read and agree to the media permission policy stated above
              </label>
            </div>

            {msg ? (
              <div className={`alert ${msg.includes('fail') || msg.includes('Please') ? 'alert-warning' : 'alert-success'}`}>
                {msg}
              </div>
            ) : null}

            <div className="d-flex justify-content-between align-items-center mt-4 flex-wrap gap-2">
              <span className="badge bg-success">Permission Granted</span>
              <button type="submit" className="btn btn-primary" disabled={busy}>
                <i className="fas fa-check-circle me-1" aria-hidden /> Submit Consent
              </button>
            </div>
          </form>

          <div className="mt-4 pt-3 border-top">
            <h5>Need to update your preferences?</h5>
            <p className="mb-1">
              Contact the school office:{' '}
              <a href="mailto:alrahma.isgl@gmail.com">alrahma.isgl@gmail.com</a> · +1 978-364-0219
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}
