'use client'

import { SortableTable, type SortableColumn } from '@/components/sortable-table'
import { fmtHoursMinutes, fmtUsd } from '@/lib/format'

export type ProjectRow = {
  operator: string
  client: string
  project: string
  prevSeconds: number
  thisSeconds: number
  allSeconds: number
  prevCost: number
  thisCost: number
  allCost: number
  /** Owner-only fields. Sum to 0 when no billout rate is set. */
  prevBillout: number
  thisBillout: number
  allBillout: number
}

type Props = {
  rows: ProjectRow[]
  totals: {
    prevSeconds: number
    thisSeconds: number
    allSeconds: number
    prevCost: number
    thisCost: number
    allCost: number
    prevBillout: number
    thisBillout: number
    allBillout: number
  }
  labels: { prev: string; this: string }
  /**
   * Owner-only flag. When true, each money cell renders billout (bold)
   * stacked above cost+hours (muted). When false, only cost+hours is
   * shown — same as the pre-billout look.
   */
  canSeeBillout: boolean
}

/** Cost + hours combined, e.g. `$1,234.56 (12:34)`. */
function fmtCostAndHours(cost: number, seconds: number): string {
  if (!cost && !seconds) return '—'
  return `${fmtUsd(cost)} (${fmtHoursMinutes(seconds)})`
}

function renderCell(
  cost: number,
  seconds: number,
  billout: number,
  canSeeBillout: boolean,
) {
  if (!canSeeBillout) {
    return fmtCostAndHours(cost, seconds)
  }
  // Owner view: billout on top (bold), cost + hours muted underneath.
  if (!cost && !seconds && !billout) return '—'
  return (
    <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', lineHeight: 1.15 }}>
      <span style={{ fontWeight: 600 }}>
        {billout > 0 ? fmtUsd(billout) : <span className="muted">—</span>}
      </span>
      <span className="muted" style={{ fontSize: '0.85em' }}>
        {fmtCostAndHours(cost, seconds)}
      </span>
    </span>
  )
}

export function SummaryTable({ rows, totals, labels, canSeeBillout }: Props) {
  const columns: SortableColumn<ProjectRow>[] = [
    {
      key: 'operator',
      header: 'Operator',
      accessor: (r) => r.operator.toLowerCase(),
      render: (r) => r.operator,
    },
    {
      key: 'client',
      header: 'Client',
      accessor: (r) => r.client.toLowerCase(),
      render: (r) => r.client,
    },
    {
      key: 'project',
      header: 'Project',
      accessor: (r) => r.project.toLowerCase(),
      render: (r) => r.project,
    },
    {
      key: 'prev',
      header: `Prev (${labels.prev})`,
      // Sort by billout when visible (revenue is the more useful axis for
      // owners), otherwise by cost.
      accessor: (r) => (canSeeBillout ? r.prevBillout : r.prevCost),
      numeric: true,
      render: (r) =>
        renderCell(r.prevCost, r.prevSeconds, r.prevBillout, canSeeBillout),
    },
    {
      key: 'this',
      header: `This (${labels.this})`,
      accessor: (r) => (canSeeBillout ? r.thisBillout : r.thisCost),
      numeric: true,
      render: (r) =>
        renderCell(r.thisCost, r.thisSeconds, r.thisBillout, canSeeBillout),
    },
    {
      key: 'all',
      header: 'All time',
      accessor: (r) => (canSeeBillout ? r.allBillout : r.allCost),
      numeric: true,
      render: (r) =>
        renderCell(r.allCost, r.allSeconds, r.allBillout, canSeeBillout),
    },
  ]

  return (
    <SortableTable
      columns={columns}
      rows={rows}
      defaultSortKey="this"
      defaultDir="desc"
      rowKey={(r) => `${r.operator}|${r.client}|${r.project}`}
      empty={<p className="empty">No entries yet. Try the Import page.</p>}
      footer={
        rows.length > 0 ? (
          <tfoot>
            <tr style={{ fontWeight: 600, borderTop: '2px solid #e5e5e5' }}>
              <td colSpan={3}>Total</td>
              <td className="num">
                {renderCell(
                  totals.prevCost,
                  totals.prevSeconds,
                  totals.prevBillout,
                  canSeeBillout,
                )}
              </td>
              <td className="num">
                {renderCell(
                  totals.thisCost,
                  totals.thisSeconds,
                  totals.thisBillout,
                  canSeeBillout,
                )}
              </td>
              <td className="num">
                {renderCell(
                  totals.allCost,
                  totals.allSeconds,
                  totals.allBillout,
                  canSeeBillout,
                )}
              </td>
            </tr>
          </tfoot>
        ) : null
      }
    />
  )
}
