import { Link } from 'react-router-dom'
import type { FamilyRow, FamilyStudentRow } from '../../api/types'
import {
  cardTitle,
  financeSummary,
  formatMdY,
  formatMoney,
  guardianAddress,
  relationLabel,
} from './familyUtils'
import './FamilyCardBody.css'

function gradeOf(s: FamilyStudentRow): string | undefined {
  const x = s as FamilyStudentRow & { grade?: string | null }
  return x.grade != null && String(x.grade).trim() !== '' ? String(x.grade) : undefined
}

type EcRow = {
  parent_id?: number
  parent_label?: string | null
  emergency_contact_name?: string | null
  relation?: string | null
  cellphone?: string | null
  email?: string | null
  updated_at?: string | null
  created_at?: string | null
}

/** Modal / embed port of CI `Views/family/card.php` (Students / Guardians / Emergency tabs). */
export function FamilyCardBody({
  family: f,
  returnUrl,
}: {
  family: FamilyRow
  returnUrl: string
}) {
  const title = cardTitle(f)
  const guardians = f.guardians ?? []
  const students = f.students ?? []
  const sum = financeSummary(f)
  const ecs = ((f as Record<string, unknown>).emergency_contacts as EcRow[] | undefined) ?? []

  return (
    <div className="family-card-root" data-family-title={title}>
      <div className="p-3 fc-header">
        <div className="d-flex flex-wrap justify-content-between align-items-center gap-2">
          <div className="me-3">
            <div className="fw-semibold fc-title">{title}</div>
          </div>
          <div className="d-flex flex-wrap gap-2 fc-badges">
            <span className="badge">Guardians: {guardians.length}</span>
            <span className="badge">Students: {students.length}</span>
            <span className="badge">Invoices: {sum.invoices_count}</span>
            <span className="badge">Balance: {formatMoney(sum.balance)}</span>
          </div>
        </div>
      </div>

      <ul className="nav nav-tabs small px-3 pt-2" role="tablist">
        <li className="nav-item" role="presentation">
          <button
            className="nav-link active"
            id="fc-tab-overview"
            data-bs-toggle="tab"
            data-bs-target="#fc-overview"
            type="button"
            role="tab"
          >
            Students
          </button>
        </li>
        <li className="nav-item" role="presentation">
          <button
            className="nav-link"
            id="fc-tab-guardians"
            data-bs-toggle="tab"
            data-bs-target="#fc-guardians"
            type="button"
            role="tab"
          >
            Parents/Guardians
          </button>
        </li>
        <li className="nav-item" role="presentation">
          <button
            className="nav-link"
            id="fc-tab-ec"
            data-bs-toggle="tab"
            data-bs-target="#fc-ec"
            type="button"
            role="tab"
          >
            Emergency
          </button>
        </li>
      </ul>

      <div className="tab-content">
        <div className="tab-pane fade show active" id="fc-overview" role="tabpanel">
          <div className="p-3">
            <div className="row g-3">
              <div className="col-12">
                <h6 className="mb-2">Students</h6>
                {students.length === 0 ? (
                  <div className="text-muted small">No students linked.</div>
                ) : (
                  <ul className="list-group">
                    {students.map((s) => (
                      <li
                        key={String(s.id ?? `${s.firstname}-${s.lastname}`)}
                        className="list-group-item d-flex justify-content-between align-items-center"
                      >
                        <div>
                          <span className="fc-name">
                            {String(s.firstname ?? '').trim()} {String(s.lastname ?? '').trim()}
                          </span>
                        </div>
                        {gradeOf(s) ? (
                          <span className="badge text-bg-secondary">{gradeOf(s)}</span>
                        ) : null}
                      </li>
                    ))}
                  </ul>
                )}
              </div>
            </div>
          </div>
        </div>

        <div className="tab-pane fade" id="fc-guardians" role="tabpanel">
          <div className="p-3">
            <div className="d-flex justify-content-between align-items-center mb-2">
              <h6 className="mb-0">Guardians</h6>
              <span className="text-muted small">Total: {guardians.length}</span>
            </div>
            {guardians.length === 0 ? (
              <div className="alert alert-light border">No guardians yet.</div>
            ) : (
              <div className="table-responsive">
                <table className="table table-sm align-middle guardians-table fc-table-stack">
                  <thead className="table-light">
                    <tr>
                      <th style={{ minWidth: 220 }}>Guardian</th>
                      <th style={{ minWidth: 220 }}>Contact</th>
                      <th style={{ minWidth: 260 }}>Address</th>
                    </tr>
                  </thead>
                  <tbody>
                    {guardians.map((g) => {
                      const gEmail = String(g.email ?? '').trim()
                      const gName = `${String(g.firstname ?? '').trim()} ${String(g.lastname ?? '').trim()}`.trim()
                      const composeParams = new URLSearchParams()
                      if (gEmail) {
                        composeParams.set('to', gEmail)
                        composeParams.set('name', gName)
                        composeParams.set('return_url', returnUrl)
                      }
                      const composeTo = `/app/administrator/family/compose-email?${composeParams.toString()}`
                      return (
                        <tr key={String(g.user_id ?? gName)}>
                          <td data-label="Guardian">
                            <div>
                              <strong>
                                <span className="fc-name">{gName}</span>
                              </strong>
                              {g.is_primary ? (
                                <span className="badge text-bg-primary ms-1">
                                  <i className="bi bi-star-fill" aria-hidden /> Primary
                                </span>
                              ) : null}
                            </div>
                            <div className="text-muted small">
                              Relation: {relationLabel(g.relation ?? '')}
                            </div>
                          </td>
                          <td className="small" data-label="Contact">
                            <div>
                              <i className="bi bi-envelope me-1 text-muted" aria-hidden />
                              {gEmail ? (
                                <Link to={composeTo} target="_blank" rel="noopener noreferrer">
                                  {gEmail}
                                </Link>
                              ) : (
                                <span className="text-muted">—</span>
                              )}
                            </div>
                            <div className="mt-1">
                              <i className="bi bi-telephone me-1 text-muted" aria-hidden />
                              {g.cellphone ? (
                                <a href={`tel:${g.cellphone}`}>{g.cellphone}</a>
                              ) : (
                                <span className="text-muted">—</span>
                              )}
                            </div>
                          </td>
                          <td className="small" data-label="Address">
                            <i className="bi bi-geo-alt me-1 text-muted" aria-hidden />
                            {guardianAddress(g)}
                          </td>
                        </tr>
                      )
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>

        <div className="tab-pane fade" id="fc-ec" role="tabpanel">
          <div className="p-3">
            <div className="d-flex justify-content-between align-items-center mb-2">
              <h6 className="mb-0">Emergency Contacts</h6>
              <span className="text-muted small">Linked to parents/guardians</span>
            </div>
            {ecs.length === 0 ? (
              <div className="alert alert-light border">No emergency contacts on file.</div>
            ) : (
              <div className="table-responsive">
                <table className="table table-sm table-striped table-hover align-middle fc-table-stack">
                  <thead className="table-light">
                    <tr>
                      <th>Parent</th>
                      <th>Contact Name</th>
                      <th>Relation</th>
                      <th>Phone</th>
                      <th>Email</th>
                      <th>Updated</th>
                    </tr>
                  </thead>
                  <tbody>
                    {ecs.map((ec, idx) => {
                      const pid = Number(ec.parent_id ?? 0)
                      const pl = String(ec.parent_label ?? '').trim()
                      const ph = String(ec.cellphone ?? '').trim()
                      const em = String(ec.email ?? '').trim()
                      const ud = ec.updated_at ?? ec.created_at ?? ''
                      return (
                        <tr key={`${pid}-${idx}`}>
                          <td data-label="Parent">
                            <span className="fc-name">{pl || (pid ? `Parent #${pid}` : '—')}</span>
                          </td>
                          <td data-label="Contact Name">
                            <span>{ec.emergency_contact_name ?? ''}</span>
                          </td>
                          <td data-label="Relation">{ec.relation ?? ''}</td>
                          <td data-label="Phone">
                            {ph ? (
                              <a href={`tel:${ph}`}>{ph}</a>
                            ) : (
                              <span className="text-muted">—</span>
                            )}
                          </td>
                          <td data-label="Email">
                            {em ? (
                              <a href={`mailto:${em}`}>{em}</a>
                            ) : (
                              <span className="text-muted">—</span>
                            )}
                          </td>
                          <td data-label="Updated">{ud ? formatMdY(ud) : '—'}</td>
                        </tr>
                      )
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
