import type { FamilyGuardianRow, FamilyRow, FamilyStudentRow } from '../../api/types'
import {
  financeSummary,
  formatMdY,
  formatMoney,
  guardianAddress,
  relationLabel,
} from './familyUtils'

type InvoiceRow = {
  invoice_number?: string | null
  status?: string | null
  total_amount?: number | string | null
  paid_amount?: number | string | null
  balance?: number | string | null
  issue_date?: string | null
}

type PaymentRow = {
  invoice_id?: number | string | null
  paid_amount?: number | string | null
  balance?: number | string | null
  payment_method?: string | null
  payment_date?: string | null
  status?: string | null
}

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
}

export function FamilyListCard({
  family: f,
  searchBlobAttr,
  onOpenDetails,
}: {
  family: FamilyRow
  searchBlobAttr: string
  onOpenDetails: () => void
}) {
  const guardians = f.guardians ?? []
  const students = f.students ?? []
  const sum = financeSummary(f)

  const fr = f as Record<string, unknown>
  const invoices = (fr.invoices as InvoiceRow[] | undefined) ?? []
  const payments = (fr.payments as PaymentRow[] | undefined) ?? []
  const invoiceMap = (fr.invoice_map as Record<string, string> | undefined) ?? {}

  const $__hasDetails = [
    f.address_line1,
    f.address_line2,
    f.city,
    f.state,
    f.postal_code,
    f.country,
    f.primary_phone,
    f.preferred_lang,
    f.preferred_contact_method,
  ].some((x) => String(x ?? '').trim() !== '')

  const hasInvoices = invoices.length > 0
  const hasPayments = payments.length > 0
  const half = hasInvoices && hasPayments

  return (
    <div className="card mb-3 family-card" data-search={searchBlobAttr}>
      <div className="card-header">
        <div className="d-flex flex-wrap justify-content-between align-items-center">
          <div className="mb-2 mb-sm-0">
            <strong>{f.household_name?.trim() || `Family #${f.id}`}</strong>
            {f.is_primary_home ? (
              <span className="badge bg-primary ms-2">Primary</span>
            ) : null}
            <span className="badge bg-light text-dark ms-2">Code: {f.family_code ?? '—'}</span>
          </div>
          <div className="text-end">
            <span className="badge bg-secondary me-1">Guardians: {guardians.length}</span>
            <span className="badge bg-secondary me-1">Students: {students.length}</span>
            <span className="badge bg-secondary me-1">Invoices: {sum.invoices_count}</span>
            <span
              className={`badge ${sum.balance > 0 ? 'bg-danger' : 'bg-success'}`}
            >
              Balance: {formatMoney(sum.balance)}
            </span>
          </div>
        </div>
      </div>
      <div className="card-body">
        <div className="row g-2">
          <div className="col-lg-4 order-lg-2">
            {$__hasDetails ? (
              <>
                <h6 className="mb-2">Family Details</h6>
                <div className="small text-muted">Address</div>
                <div>
                  {f.address_line1 ?? ''} {f.address_line2 ?? ''}
                </div>
                <div>
                  {f.city ?? ''} {f.state ?? ''} {f.postal_code ?? ''}
                </div>
                {f.country ? <div>{f.country}</div> : null}
                <div className="mt-2">
                  <span className="text-muted small">Phone:</span> {f.primary_phone ?? '—'}
                </div>
                <div className="mt-1">
                  <span className="text-muted small">Lang:</span> {f.preferred_lang ?? '—'}
                </div>
                <div className="mt-1">
                  <span className="text-muted small">Contact:</span>{' '}
                  {f.preferred_contact_method ?? '—'}
                </div>
                <div className="mt-1">
                  <span className="text-muted small">Active:</span>{' '}
                  {f.is_active ? 'Yes' : 'No'}
                </div>
              </>
            ) : null}
            <div className="mt-3">
              <h6 className="mb-2">Students</h6>
              {students.length === 0 ? (
                <div className="text-muted small">No students linked.</div>
              ) : (
                <ul className="list-group students-list">
                  {students.map((s) => (
                    <li key={String(s.id)} className="list-group-item student-item">
                      <button
                        type="button"
                        className="btn btn-link p-0 text-decoration-none text-start"
                        onClick={onOpenDetails}
                      >
                        {String(s.firstname ?? '').trim()} {String(s.lastname ?? '').trim()}
                      </button>
                      {gradeOf(s) ? (
                        <span className="text-muted small"> • {gradeOf(s)}</span>
                      ) : null}
                    </li>
                  ))}
                </ul>
              )}
            </div>
          </div>

          <div className="col-lg-8 order-lg-1">
            <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">
                  <thead className="table-light">
                    <tr>
                      <th style={{ minWidth: 220 }}>Guardian</th>
                      <th style={{ minWidth: 220 }}>Contact</th>
                      <th style={{ minWidth: 260 }}>Address</th>
                      <th style={{ minWidth: 140 }}>Prefs</th>
                    </tr>
                  </thead>
                  <tbody>
                    {guardians.map((g: FamilyGuardianRow) => (
                      <tr key={String(g.user_id ?? `${g.firstname}-${g.lastname}`)} className="guard-row">
                        <td>
                          <div>
                            <strong>
                              <button
                                type="button"
                                className="btn btn-link p-0 text-decoration-none"
                                onClick={onOpenDetails}
                              >
                                {String(g.firstname ?? '').trim()} {String(g.lastname ?? '').trim()}
                              </button>
                            </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">
                          <div>
                            <i className="bi bi-envelope me-1 text-muted" aria-hidden />
                            {g.email ? (
                              <a href={`mailto:${g.email}`}>{g.email}</a>
                            ) : (
                              <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">
                          <i className="bi bi-geo-alt me-1 text-muted" aria-hidden />
                          {guardianAddress(g)}
                        </td>
                        <td>
                          {g.receive_emails ? (
                            <span className="badge text-bg-success">
                              <i className="bi bi-envelope-fill" aria-hidden /> Email
                            </span>
                          ) : (
                            <span className="badge text-bg-secondary">
                              <i className="bi bi-envelope" aria-hidden /> Email
                            </span>
                          )}
                          {g.receive_sms ? (
                            <span className="badge text-bg-info ms-1">
                              <i className="bi bi-chat-dots-fill" aria-hidden /> SMS
                            </span>
                          ) : (
                            <span className="badge text-bg-secondary ms-1">
                              <i className="bi bi-chat-dots" aria-hidden /> SMS
                            </span>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          {hasInvoices ? (
            <div className={half ? 'col-lg-6' : 'col-12'}>
              <h6 className="mb-2">Invoices</h6>
              <div className="table-responsive">
                <table className="table table-sm table-striped table-hover align-middle">
                  <thead className="table-light">
                    <tr>
                      <th>#</th>
                      <th>Status</th>
                      <th>Total</th>
                      <th>Paid</th>
                      <th>Balance</th>
                      <th>Date</th>
                    </tr>
                  </thead>
                  <tbody>
                    {invoices.map((iv, i) => (
                      <tr key={`${iv.invoice_number}-${i}`}>
                        <td>{iv.invoice_number ?? ''}</td>
                        <td>{iv.status ?? ''}</td>
                        <td>{formatMoney(iv.total_amount)}</td>
                        <td>{formatMoney(iv.paid_amount)}</td>
                        <td>{formatMoney(iv.balance)}</td>
                        <td>{iv.issue_date ? formatMdY(iv.issue_date) : ''}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          ) : null}

          {hasPayments ? (
            <div className={half ? 'col-lg-6' : 'col-12'}>
              <h6 className="mb-2">Recent Payments</h6>
              <div className="table-responsive">
                <table className="table table-sm table-striped table-hover align-middle">
                  <thead className="table-light">
                    <tr>
                      <th>Invoice</th>
                      <th>Amount</th>
                      <th>Balance</th>
                      <th>Method</th>
                      <th>Date</th>
                      <th>Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {payments.map((p, i) => {
                      const iid = Number(p.invoice_id ?? 0)
                      const invLabel =
                        invoiceMap[String(iid)] ?? invoiceMap[iid] ?? `#${iid}`
                      return (
                        <tr key={`${iid}-${i}`}>
                          <td>{invLabel}</td>
                          <td>{formatMoney(p.paid_amount)}</td>
                          <td>{formatMoney(p.balance)}</td>
                          <td>{p.payment_method ?? ''}</td>
                          <td>{p.payment_date ? formatMdY(p.payment_date) : ''}</td>
                          <td>{p.status ?? ''}</td>
                        </tr>
                      )
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          ) : null}
        </div>
      </div>
    </div>
  )
}
