'use client'

import { Fragment, useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { usePathname, useSearchParams } from 'next/navigation'
import { fmtUsd } from '@/lib/format'
import { SubmitButton } from '@/components/submit-button'
import {
  bulkUpdateProjectFields,
  deleteProjectRateOverride,
  updateProjectIncome,
  upsertProjectRateOverride,
} from './actions'

export type ProjectRow = {
  operator: string | null
  client: string | null
  project: string | null
  /** projects.id, or null when this row didn't match an entity. */
  projectEntityId: string | null
  rowCount: number
  billoutSeconds: number
  cost: number
  /** Owner-only: sum of billout_amount_usd across entries in this row. */
  billoutAmount: number | null
  /** Owner-only: billoutAmount × (1 + pct/100) + adjAmount. */
  billoutAdjusted: number | null
  /** Owner-only: project's billout pct adjustment (signed %). */
  billoutAdjPct: number | null
  /** Owner-only: project's billout fixed adjustment ($). */
  billoutAdjAmount: number | null
  /** null for managers (RLS hides it) or for projects with no income set. */
  income: number | null
}

export type FilterSnapshot = {
  date?: string
  start?: string
  end?: string
  status?: string
  batch?: string
  q?: string
  project?: string
  user?: string
  source_email?: string
  client?: string
  operator?: string
  imported_by?: string
  missing_info?: string
}

export type OverrideForRow = {
  id: string
  team_member_id: string | null
  /** Absolute rate (USD/hr) — set when the rule is rate-kind, NULL otherwise. */
  rate: number | null
  /** Signed percentage — set when the rule is pct-kind, NULL otherwise. */
  pct: number | null
  team_member_name: string | null
  team_member_email: string | null
}

export type TeamMemberPick = {
  id: string
  label: string
  email: string
  team: string | null
}

type Props = {
  rows: ProjectRow[]
  canEdit: boolean
  /** True only for owner / super_admin. Gates Income + Margin columns. */
  canSeeIncome: boolean
  filter: FilterSnapshot
  expandKeys: Set<string>
  sortKey: string
  sortDir: 'asc' | 'desc'
  /** projectKey of the row currently in income/adjustment-edit mode. */
  editKey: string | null
  /** projectKey of the row currently in rate-overrides-edit mode. */
  editRatesKey: string | null
  /** project entity id → list of override rules for that project. */
  overridesByProjectId: Record<string, OverrideForRow[]>
  /** Full team_member roster for the override "user" select. */
  teamMemberOptions: TeamMemberPick[]
}

type DescriptionRow = {
  description: string | null
  rowCount: number
  billoutSeconds: number
  cost: number
}

/**
 * Stable key per project group used for both the selection set and the
 * expand-keys URL param. NULLs are encoded as the empty string so an
 * "all-null" group still has a deterministic key. Pipe separator is
 * fine because none of the columns can contain a literal pipe.
 */
function projectKey(p: ProjectRow): string {
  return `${p.operator ?? ''}|${p.client ?? ''}|${p.project ?? ''}`
}

function fmtHM(seconds: number): string {
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  return `${h}:${m.toString().padStart(2, '0')}`
}

export function ProjectsTable({
  rows,
  canEdit,
  canSeeIncome,
  filter,
  expandKeys: initialExpandKeys,
  editKey,
  editRatesKey,
  overridesByProjectId,
  teamMemberOptions,
}: Props) {
  const pathname = usePathname()
  const params = useSearchParams()

  // Track expanded projects locally so we can lazy-load + persist their
  // breakdown without a full page reload. We seed from the URL so a
  // shared link with ?expand=… renders pre-expanded.
  const [expanded, setExpanded] = useState<Set<string>>(initialExpandKeys)
  const [breakdowns, setBreakdowns] = useState<
    Record<string, DescriptionRow[] | 'loading' | 'error'>
  >({})

  // Selection for bulk edit.
  const [selected, setSelected] = useState<Set<string>>(new Set())
  const [bulkEditOpen, setBulkEditOpen] = useState(false)
  const [bulkOperator, setBulkOperator] = useState('')
  const [bulkClient, setBulkClient] = useState('')
  const [bulkProject, setBulkProject] = useState('')

  // Selection resets whenever the filter changes — same UX as /entries.
  const filterSignature = JSON.stringify(filter)
  useEffect(() => {
    setSelected(new Set())
    setBulkEditOpen(false)
  }, [filterSignature])

  const visibleKeys = useMemo(() => rows.map(projectKey), [rows])
  const allSelected =
    visibleKeys.length > 0 && visibleKeys.every((k) => selected.has(k))

  function toggleOne(key: string) {
    setSelected((prev) => {
      const next = new Set(prev)
      if (next.has(key)) next.delete(key)
      else next.add(key)
      return next
    })
  }

  function toggleAll() {
    if (allSelected) {
      setSelected(new Set())
    } else {
      setSelected(new Set(visibleKeys))
    }
  }

  async function toggleExpand(row: ProjectRow) {
    const key = projectKey(row)
    setExpanded((prev) => {
      const next = new Set(prev)
      if (next.has(key)) next.delete(key)
      else next.add(key)
      return next
    })
    // Fetch breakdown on first expand only.
    if (!expanded.has(key) && !breakdowns[key]) {
      setBreakdowns((prev) => ({ ...prev, [key]: 'loading' }))
      try {
        const qs = new URLSearchParams()
        // Include the filter so the breakdown matches what the row's
        // sums were computed over.
        for (const [k, v] of Object.entries(filter)) {
          if (typeof v === 'string' && v !== '') qs.set(k, v)
        }
        qs.set('operator', row.operator ?? '__null__')
        qs.set('client', row.client ?? '__null__')
        qs.set('project', row.project ?? '__null__')
        const res = await fetch(`/projects/expand?${qs.toString()}`, {
          cache: 'no-store',
        })
        if (!res.ok) throw new Error(await res.text())
        const data = (await res.json()) as DescriptionRow[]
        setBreakdowns((prev) => ({ ...prev, [key]: data }))
      } catch (err) {
        console.error('expand failed', err)
        setBreakdowns((prev) => ({ ...prev, [key]: 'error' }))
      }
    }
  }

  // Filter-passthrough hidden inputs so bulk-update knows what scope it
  // operates over. Mirrors the /entries pattern.
  const filterInputs = (
    <>
      {Object.entries(filter).map(([k, v]) =>
        typeof v === 'string' && v !== '' ? (
          <input key={k} type="hidden" name={`filter_${k}`} value={v} />
        ) : null,
      )}
    </>
  )

  function confirmBulk(e: React.FormEvent<HTMLFormElement>) {
    const fields: string[] = []
    if (bulkOperator) fields.push(`operator → "${bulkOperator}"`)
    if (bulkClient) fields.push(`client → "${bulkClient}"`)
    if (bulkProject) fields.push(`project → "${bulkProject}"`)
    if (fields.length === 0) {
      e.preventDefault()
      window.alert('Set at least one field to update.')
      return
    }
    const totalEntries = rows
      .filter((r) => selected.has(projectKey(r)))
      .reduce((acc, r) => acc + r.rowCount, 0)
    const msg = `Update ${totalEntries} entries across ${selected.size} project group${
      selected.size === 1 ? '' : 's'
    }?\n\n${fields.join('\n')}`
    if (!window.confirm(msg)) {
      e.preventDefault()
    }
  }

  function sortHref(key: string): string {
    const next = new URLSearchParams(params.toString())
    const currentKey = next.get('sort') ?? 'billout_hrs'
    const currentDir = next.get('dir') ?? 'desc'
    if (currentKey === key) {
      next.set('dir', currentDir === 'asc' ? 'desc' : 'asc')
    } else {
      next.set('sort', key)
      next.set('dir', 'desc')
    }
    return `${pathname}?${next.toString()}`
  }

  function editIncomeHref(key: string | null): string {
    const next = new URLSearchParams(params.toString())
    if (key === null) next.delete('edit_income')
    else next.set('edit_income', key)
    next.delete('edit_rates')
    return `${pathname}?${next.toString()}`
  }

  function editRatesHref(key: string | null): string {
    const next = new URLSearchParams(params.toString())
    if (key === null) next.delete('edit_rates')
    else next.set('edit_rates', key)
    next.delete('edit_income')
    return `${pathname}?${next.toString()}`
  }

  /** colSpan for the expand row & inline edit row. */
  const colCount =
    (canEdit ? 1 : 0) +
    1 /* expand toggle */ +
    6 /* op, client, project, entries, billout, cost */ +
    (canSeeIncome ? 2 /* income, margin */ : 0)

  return (
    <>
      {canEdit && selected.size > 0 && (
        <div
          className="panel"
          style={{
            position: 'sticky',
            top: 0,
            zIndex: 10,
            background: '#1f2937',
            color: 'white',
            padding: '0.75rem 1rem',
            marginBottom: '0.75rem',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            gap: '0.75rem',
            flexWrap: 'wrap',
          }}
        >
          <div>
            <strong>{selected.size}</strong> project group
            {selected.size === 1 ? '' : 's'} selected (
            {rows
              .filter((r) => selected.has(projectKey(r)))
              .reduce((acc, r) => acc + r.rowCount, 0)}{' '}
            entries)
          </div>
          <div className="flex-row" style={{ gap: '0.5rem' }}>
            <button
              type="button"
              onClick={() => setBulkEditOpen((v) => !v)}
              style={{ background: '#374151', color: 'white' }}
            >
              {bulkEditOpen ? 'Hide edit ▾' : 'Edit fields ▾'}
            </button>
            <button
              type="button"
              onClick={() => setSelected(new Set())}
              style={{ background: '#374151', color: 'white' }}
            >
              Clear
            </button>
          </div>
        </div>
      )}

      {canEdit && bulkEditOpen && selected.size > 0 && (
        <form
          action={bulkUpdateProjectFields}
          onSubmit={confirmBulk}
          className="panel"
          style={{ marginBottom: '0.75rem' }}
        >
          {filterInputs}
          {[...selected].map((k) => (
            <input key={k} type="hidden" name="project_key" value={k} />
          ))}
          <p
            className="muted"
            style={{ margin: '0 0 0.5rem', fontSize: '0.9em' }}
          >
            These values overwrite the matching column on every entry in
            the selected project groups. Empty inputs are skipped.
            Effective on both pending and transferred rows (you&apos;re
            an owner) — be careful.
          </p>
          <div
            style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
              gap: '0.5rem 1rem',
            }}
          >
            <label>
              Operator
              <input
                name="bulk_operator"
                type="text"
                value={bulkOperator}
                onChange={(e) => setBulkOperator(e.target.value)}
              />
            </label>
            <label>
              Client
              <input
                name="bulk_client"
                type="text"
                value={bulkClient}
                onChange={(e) => setBulkClient(e.target.value)}
              />
            </label>
            <label>
              Project
              <input
                name="bulk_project"
                type="text"
                value={bulkProject}
                onChange={(e) => setBulkProject(e.target.value)}
              />
            </label>
          </div>
          <div className="flex-row" style={{ marginTop: '0.75rem' }}>
            <button type="submit">Apply</button>
          </div>
        </form>
      )}

      <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
        <div className="table-wrap" style={{ border: 'none', borderRadius: 0 }}>
          <table className="data">
            <thead>
              <tr>
                {canEdit && (
                  <th style={{ width: '2rem' }}>
                    <input
                      type="checkbox"
                      checked={allSelected}
                      onChange={toggleAll}
                      aria-label="Select all visible"
                    />
                  </th>
                )}
                <th style={{ width: '2rem' }} aria-label="expand" />
                <th>
                  <Link href={sortHref('operator')}>Operator</Link>
                </th>
                <th>
                  <Link href={sortHref('client')}>Client</Link>
                </th>
                <th>
                  <Link href={sortHref('project')}>Project</Link>
                </th>
                <th className="num">
                  <Link href={sortHref('row_count')}>Entries</Link>
                </th>
                <th className="num">
                  <Link href={sortHref('billout_hrs')}>Billout hrs</Link>
                </th>
                <th className="num">
                  <Link href={sortHref('cost')}>Cost</Link>
                </th>
                {canSeeIncome && (
                  <>
                    <th
                      className="num"
                      title="Owner-only: what we charge the client for these billout hours."
                    >
                      <Link href={sortHref('billout_amount')}>Billout</Link>
                    </th>
                    <th className="num">
                      <Link href={sortHref('income')}>Income</Link>
                    </th>
                    <th className="num">
                      <Link href={sortHref('margin')}>Margin</Link>
                    </th>
                  </>
                )}
              </tr>
            </thead>
            <tbody>
              {rows.map((row) => {
                const key = projectKey(row)
                const isExpanded = expanded.has(key)
                const breakdown = breakdowns[key]
                return (
                  <Fragment key={key}>
                    <tr className={selected.has(key) ? 'row-selected' : ''}>
                      {canEdit && (
                        <td>
                          <input
                            type="checkbox"
                            checked={selected.has(key)}
                            onChange={() => toggleOne(key)}
                            aria-label={`Select ${key}`}
                          />
                        </td>
                      )}
                      <td>
                        <button
                          type="button"
                          onClick={() => toggleExpand(row)}
                          aria-label={isExpanded ? 'Collapse' : 'Expand'}
                          title={
                            isExpanded
                              ? 'Hide description breakdown'
                              : 'Show description breakdown'
                          }
                          style={{
                            background: 'transparent',
                            border: 'none',
                            cursor: 'pointer',
                            padding: '0 0.25rem',
                            fontSize: '0.9em',
                          }}
                        >
                          {isExpanded ? '▼' : '▶'}
                        </button>
                      </td>
                      <td>
                        {row.operator ?? (
                          <span className="muted">(missing)</span>
                        )}
                      </td>
                      <td>
                        {row.client ?? (
                          <span className="muted">(missing)</span>
                        )}
                      </td>
                      <td>
                        {row.project ?? (
                          <span className="muted">(missing)</span>
                        )}
                        {canEdit && row.projectEntityId && (
                          <Link
                            href={`/projects/manage?edit=pr:${row.projectEntityId}`}
                            title="Rename project"
                            aria-label="Rename project"
                            style={{
                              fontSize: '0.85em',
                              textDecoration: 'none',
                              opacity: 0.55,
                              marginLeft: '0.4rem',
                            }}
                          >
                            ✏️
                          </Link>
                        )}
                      </td>
                      <td className="num">{row.rowCount}</td>
                      <td className="num">{fmtHM(row.billoutSeconds)}</td>
                      <td className="num">{fmtUsd(row.cost)}</td>
                      {canSeeIncome && (
                        <>
                          <td className="num">
                            {row.billoutAmount == null ||
                            row.billoutAmount === 0 ? (
                              <span className="muted">—</span>
                            ) : (
                              (() => {
                                const adjusted =
                                  row.billoutAdjusted ?? row.billoutAmount
                                const hasAdj =
                                  (row.billoutAdjPct != null &&
                                    row.billoutAdjPct !== 0) ||
                                  (row.billoutAdjAmount != null &&
                                    row.billoutAdjAmount !== 0)
                                if (!hasAdj) return fmtUsd(adjusted)
                                // Show adjusted total; raw + adjustment in tooltip + small line.
                                const pctTxt =
                                  row.billoutAdjPct != null && row.billoutAdjPct !== 0
                                    ? `${row.billoutAdjPct > 0 ? '+' : ''}${row.billoutAdjPct}%`
                                    : ''
                                const amtTxt =
                                  row.billoutAdjAmount != null && row.billoutAdjAmount !== 0
                                    ? `${row.billoutAdjAmount > 0 ? '+' : ''}${fmtUsd(row.billoutAdjAmount)}`
                                    : ''
                                const adjTxt = [pctTxt, amtTxt].filter(Boolean).join(' ')
                                return (
                                  <span
                                    style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', lineHeight: 1.15 }}
                                    title={`raw ${fmtUsd(row.billoutAmount)} + ${adjTxt}`}
                                  >
                                    <span style={{ fontWeight: 600 }}>
                                      {fmtUsd(adjusted)}
                                    </span>
                                    <span className="muted" style={{ fontSize: '0.78em' }}>
                                      {fmtUsd(row.billoutAmount)} · {adjTxt}
                                    </span>
                                  </span>
                                )
                              })()
                            )}
                          </td>
                          <td className="num">
                            {row.income == null ? (
                              <span className="muted">—</span>
                            ) : (
                              fmtUsd(row.income)
                            )}{' '}
                            <Link
                              href={editIncomeHref(key)}
                              scroll={false}
                              title="Edit income / billout adjustment"
                              aria-label="Edit income"
                              style={{
                                fontSize: '0.85em',
                                textDecoration: 'none',
                                opacity: 0.6,
                              }}
                            >
                              ✏️
                            </Link>
                            {row.projectEntityId && (
                              <Link
                                href={editRatesHref(key)}
                                scroll={false}
                                title="Edit rate overrides for this project"
                                aria-label="Edit rate overrides"
                                style={{
                                  fontSize: '0.85em',
                                  textDecoration: 'none',
                                  opacity: 0.6,
                                  marginLeft: '0.15rem',
                                }}
                              >
                                ⚙️
                                {overridesByProjectId[row.projectEntityId]
                                  ?.length ? (
                                  <sup
                                    style={{
                                      fontSize: '0.7em',
                                      color: '#0a7d3f',
                                      marginLeft: '0.05rem',
                                    }}
                                  >
                                    {
                                      overridesByProjectId[
                                        row.projectEntityId
                                      ].length
                                    }
                                  </sup>
                                ) : null}
                              </Link>
                            )}
                          </td>
                          <td className="num">
                            {row.income == null ? (
                              <span className="muted">—</span>
                            ) : (
                              <span
                                className={
                                  row.income - row.cost >= 0
                                    ? 'over-target'
                                    : 'under-target'
                                }
                              >
                                {row.income - row.cost >= 0 ? '+' : ''}
                                {fmtUsd(row.income - row.cost)}
                              </span>
                            )}
                          </td>
                        </>
                      )}
                    </tr>
                    {editKey === key && canSeeIncome && (
                      <tr style={{ background: '#fff8e1' }}>
                        <td colSpan={colCount} style={{ padding: '0.75rem 1rem' }}>
                          <form
                            action={updateProjectIncome}
                            style={{
                              display: 'flex',
                              gap: '0.5rem',
                              alignItems: 'end',
                              flexWrap: 'wrap',
                            }}
                          >
                            <input
                              type="hidden"
                              name="operator"
                              value={row.operator ?? ''}
                            />
                            <input
                              type="hidden"
                              name="client"
                              value={row.client ?? ''}
                            />
                            <input
                              type="hidden"
                              name="project"
                              value={row.project ?? ''}
                            />
                            <input
                              type="hidden"
                              name="_return_url"
                              value={editIncomeHref(null)}
                            />
                            <label
                              style={{
                                display: 'flex',
                                flexDirection: 'column',
                                fontSize: '0.85em',
                              }}
                            >
                              Income (USD){' '}
                              <span className="muted">
                                (blank = clear)
                              </span>
                              <input
                                name="income_usd"
                                type="text"
                                inputMode="decimal"
                                defaultValue={
                                  row.income == null
                                    ? ''
                                    : row.income.toFixed(2)
                                }
                                placeholder="0.00"
                                autoFocus
                                style={{ width: '9rem' }}
                              />
                            </label>
                            <label
                              style={{
                                display: 'flex',
                                flexDirection: 'column',
                                fontSize: '0.85em',
                              }}
                              title="Signed percentage applied to this project's billout. Negative = discount. Pct first, then fixed amount."
                            >
                              Billout adj %
                              <input
                                name="billout_adjustment_pct"
                                type="text"
                                inputMode="decimal"
                                defaultValue={
                                  row.billoutAdjPct == null
                                    ? ''
                                    : String(row.billoutAdjPct)
                                }
                                placeholder="e.g. 10"
                                style={{ width: '7rem' }}
                              />
                            </label>
                            <label
                              style={{
                                display: 'flex',
                                flexDirection: 'column',
                                fontSize: '0.85em',
                              }}
                              title="Fixed $ adjustment on this project's billout. Negative = discount."
                            >
                              Billout adj $
                              <input
                                name="billout_adjustment_amount"
                                type="text"
                                inputMode="decimal"
                                defaultValue={
                                  row.billoutAdjAmount == null
                                    ? ''
                                    : row.billoutAdjAmount.toFixed(2)
                                }
                                placeholder="e.g. 100.00"
                                style={{ width: '9rem' }}
                              />
                            </label>
                            <button type="submit">Save</button>
                            <Link
                              href={editIncomeHref(null)}
                              scroll={false}
                              className="button-link-secondary"
                            >
                              Cancel
                            </Link>
                            <span
                              className="muted"
                              style={{
                                fontSize: '0.85em',
                                marginLeft: '0.5rem',
                              }}
                            >
                              {row.operator ?? '(no operator)'} ·{' '}
                              {row.client ?? '(no client)'} ·{' '}
                              {row.project ?? '(no project)'}
                            </span>
                          </form>
                        </td>
                      </tr>
                    )}
                    {editRatesKey === key &&
                      canSeeIncome &&
                      row.projectEntityId && (
                        <RatesEditRow
                          projectEntityId={row.projectEntityId}
                          projectLabel={`${row.operator ?? '—'} / ${row.client ?? '—'} / ${row.project ?? '—'}`}
                          overrides={
                            overridesByProjectId[row.projectEntityId] ?? []
                          }
                          teamMemberOptions={teamMemberOptions}
                          returnUrl={editRatesHref(null)}
                          cancelHref={editRatesHref(null)}
                          colCount={colCount}
                        />
                      )}
                    {isExpanded && (
                      <tr>
                        <td
                          colSpan={colCount}
                          style={{
                            background: '#f9fafb',
                            padding: '0.5rem 1rem 0.75rem 3rem',
                          }}
                        >
                          {breakdown === 'loading' ? (
                            <span className="muted">Loading…</span>
                          ) : breakdown === 'error' ? (
                            <span className="error">
                              Couldn&apos;t load breakdown. Reload and try
                              again.
                            </span>
                          ) : !breakdown ? null : breakdown.length === 0 ? (
                            <span className="muted">No entries.</span>
                          ) : (
                            <table
                              className="data"
                              style={{ width: '100%', fontSize: '0.9em' }}
                            >
                              <thead>
                                <tr>
                                  <th>Description</th>
                                  <th className="num">Entries</th>
                                  <th className="num">Billout hrs</th>
                                  <th className="num">Cost</th>
                                </tr>
                              </thead>
                              <tbody>
                                {breakdown.map((d, i) => (
                                  <tr key={i}>
                                    <td>
                                      {d.description ?? (
                                        <span className="muted">
                                          (no description)
                                        </span>
                                      )}
                                    </td>
                                    <td className="num">{d.rowCount}</td>
                                    <td className="num">
                                      {fmtHM(d.billoutSeconds)}
                                    </td>
                                    <td className="num">{fmtUsd(d.cost)}</td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          )}
                        </td>
                      </tr>
                    )}
                  </Fragment>
                )
              })}
            </tbody>
          </table>
        </div>
      </div>
    </>
  )
}


/**
 * Inline panel for editing a project's rate-override rules. Shows the
 * existing rules + an "Add new" form. The "All hours" rule is the
 * project-wide default (used when no user-specific rule matches).
 */
function RatesEditRow({
  projectEntityId,
  projectLabel,
  overrides,
  teamMemberOptions,
  returnUrl,
  cancelHref,
  colCount,
}: {
  projectEntityId: string
  projectLabel: string
  overrides: OverrideForRow[]
  teamMemberOptions: TeamMemberPick[]
  returnUrl: string
  cancelHref: string
  colCount: number
}) {
  // Sort: project-wide (NULL user) first, then by display name.
  const sorted = [...overrides].sort((a, b) => {
    if (a.team_member_id === null) return -1
    if (b.team_member_id === null) return 1
    return (a.team_member_name ?? '').localeCompare(b.team_member_name ?? '')
  })

  return (
    <tr style={{ background: '#eef2ff' }}>
      <td colSpan={colCount} style={{ padding: '0.75rem 1rem' }}>
        <div
          style={{
            display: 'flex',
            flexDirection: 'column',
            gap: '0.75rem',
          }}
        >
          <div>
            <strong>Rate overrides</strong>{' '}
            <span className="muted" style={{ fontSize: '0.85em' }}>
              for {projectLabel}. Re-stamps affected entries on save.
            </span>
          </div>

          {sorted.length === 0 ? (
            <p className="muted" style={{ margin: 0, fontSize: '0.9em' }}>
              No overrides set. Entries on this project bill at each
              team_member&apos;s default rate.
            </p>
          ) : (
            <table className="data" style={{ fontSize: '0.9em' }}>
              <thead>
                <tr>
                  <th>Scope</th>
                  <th className="num">Rate</th>
                  <th />
                </tr>
              </thead>
              <tbody>
                {sorted.map((o) => (
                  <tr key={o.id}>
                    <td>
                      {o.team_member_id === null ? (
                        <em>All hours on this project</em>
                      ) : (
                        <>
                          {o.team_member_name ?? '(unknown)'}{' '}
                          <span
                            className="muted"
                            style={{ fontSize: '0.85em' }}
                          >
                            {o.team_member_email ?? ''}
                          </span>
                        </>
                      )}
                    </td>
                    <td className="num">
                      {o.rate != null ? (
                        `${fmtUsd(o.rate)}/hr`
                      ) : o.pct != null ? (
                        <span
                          title="Percentage adjustment on top of the user's normal billout rate. Negative = discount."
                        >
                          {o.pct > 0 ? '+' : ''}
                          {o.pct}% on rate
                        </span>
                      ) : (
                        <span className="muted">—</span>
                      )}
                    </td>
                    <td className="right">
                      <form action={deleteProjectRateOverride}>
                        <input type="hidden" name="id" value={o.id} />
                        <input
                          type="hidden"
                          name="_return_url"
                          value={returnUrl}
                        />
                        <SubmitButton
                          pendingLabel="…"
                          className="secondary"
                          style={{
                            padding: '0.2rem 0.5rem',
                            fontSize: '0.8em',
                          }}
                        >
                          Delete
                        </SubmitButton>
                      </form>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}

          <form
            action={upsertProjectRateOverride}
            style={{
              display: 'flex',
              gap: '0.5rem',
              alignItems: 'flex-end',
              flexWrap: 'wrap',
              padding: '0.5rem 0 0',
              borderTop: '1px dashed #c7d2fe',
            }}
          >
            <input
              type="hidden"
              name="project_id"
              value={projectEntityId}
            />
            <input type="hidden" name="_return_url" value={returnUrl} />
            <label
              style={{
                display: 'flex',
                flexDirection: 'column',
                fontSize: '0.85em',
              }}
            >
              Scope
              <select name="team_member_id" defaultValue="">
                <option value="">All hours on this project</option>
                {teamMemberOptions.map((m) => (
                  <option key={m.id} value={m.id}>
                    {m.label}
                    {m.team ? ` (${m.team})` : ''}
                  </option>
                ))}
              </select>
            </label>
            <label
              style={{
                display: 'flex',
                flexDirection: 'column',
                fontSize: '0.85em',
              }}
            >
              Kind
              <select name="override_kind" defaultValue="rate">
                <option value="rate">Absolute rate ($/hr)</option>
                <option value="pct">Adjustment (% of user&apos;s rate)</option>
              </select>
            </label>
            <label
              style={{
                display: 'flex',
                flexDirection: 'column',
                fontSize: '0.85em',
              }}
              title="For rate: a non-negative dollar amount per billout hour. For pct: signed % (-20 = 20% discount, +10 = 10% markup)."
            >
              Value
              <input
                name="override_value"
                type="text"
                inputMode="decimal"
                placeholder="e.g. 30.00 or -20"
                required
                style={{ width: '8rem' }}
              />
            </label>
            <SubmitButton pendingLabel="Re-stamping entries…">
              Add / update rule
            </SubmitButton>
            <Link
              href={cancelHref}
              className="button-link-secondary"
              scroll={false}
            >
              Done
            </Link>
            <span className="muted" style={{ fontSize: '0.8em' }}>
              User-specific rule wins over &quot;all hours&quot;. Both
              fall back to the team_member&apos;s default billout rate.
            </span>
          </form>
        </div>
      </td>
    </tr>
  )
}
