import { useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { fetchWhatsappParentContacts } from '../../api/whatsapp'
import type { ParentContactRow } from '../../api/whatsapp'

function digitsOnly(phone: string): string {
  return phone.replace(/\D+/g, '')
}

export function WhatsappParentContactsPage() {
  const [searchParams] = useSearchParams()
  const schoolYear = searchParams.get('school_year') ?? undefined
  const semester = searchParams.get('semester') ?? undefined
  const [contacts, setContacts] = useState<ParentContactRow[]>([])
  const [termYear, setTermYear] = useState<string | null>(null)
  const [termSem, setTermSem] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      try {
        const data = await fetchWhatsappParentContacts({ school_year: schoolYear, semester })
        if (cancelled) return
        setContacts(data.contacts ?? [])
        setTermYear(data.schoolYear ?? schoolYear ?? null)
        setTermSem(data.semester ?? semester ?? null)
        setError(null)
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Unable to load contacts.')
      }
    })()
    return () => {
      cancelled = true
    }
  }, [schoolYear, semester])

  return (
    <div className="container my-4">
      <div className="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
        <h2 className="mb-0">Parent Contacts</h2>
        <div className="d-flex align-items-center gap-2">
          {termYear ? <span className="badge bg-primary">School Year: {termYear}</span> : null}
          {termSem ? (
            <span className="badge bg-info text-dark">
              Semester: {termSem}
            </span>
          ) : null}
          <Link className="btn btn-outline-secondary btn-sm" to="/app/whatsapp/manage-links">
            Back
          </Link>
        </div>
      </div>

      {error ? <div className="alert alert-danger">{error}</div> : null}

      {contacts.length === 0 && !error ? (
        <div className="alert alert-warning">No parent contacts found for the selected term.</div>
      ) : null}

      {contacts.length > 0 ? (
        <div className="card shadow-sm">
          <div className="card-body">
            <div className="table-responsive">
              <table className="table table-striped table-hover align-middle">
                <thead className="table-light">
                  <tr>
                    <th style={{ width: '14rem' }}>Name</th>
                    <th style={{ width: '10rem' }}>Type</th>
                    <th style={{ width: '14rem' }}>Phone</th>
                    <th style={{ width: '18rem' }}>Email</th>
                  </tr>
                </thead>
                <tbody>
                  {contacts.map((row, i) => {
                    const name = `${row.lastname ?? ''}, ${row.firstname ?? ''}`.trim()
                    const isSecond = row.type === 'Second Parent'
                    return (
                      <tr key={`${name}-${i}`}>
                        <td>{name}</td>
                        <td>
                          <span className={`badge ${isSecond ? 'bg-secondary' : 'bg-success'}`}>
                            {row.type ?? ''}
                          </span>
                        </td>
                        <td>
                          {row.phone ? (
                            <a href={`tel:${digitsOnly(row.phone)}`}>{row.phone}</a>
                          ) : (
                            <span className="text-muted">—</span>
                          )}
                        </td>
                        <td>
                          {row.email ? (
                            <a href={`mailto:${row.email}`}>{row.email}</a>
                          ) : (
                            <span className="text-muted">—</span>
                          )}
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>
            <div className="small text-muted mt-2">Tip: Click a phone to dial, email to compose.</div>
          </div>
        </div>
      ) : null}
    </div>
  )
}
