'use client'

import { useState } from 'react'
import { SearchableCombobox } from '@/components/searchable-combobox'
import { DeleteForm } from '@/components/delete-form'
import { fmtUsd } from '@/lib/format'
import { updateCcLine, deleteCcLine } from '../actions'

export type LineForRow = {
  id: string
  batch_id: string
  line_index: number
  expense_date: string | null
  description: string | null
  amount_usd: number | null
  project_id: string | null
  project_label: string | null
  assignment_description: string | null
  category: string | null
  /** TRUE when the assignment came from a cc_auto_rules match and the
   * user has not yet saved the row. Drives the orange (vs green)
   * row color so unconfirmed auto-matches stand out. */
  auto_assigned: boolean
}

type Props = {
  line: LineForRow
  projectOptions: { id: string; label: string }[]
  categoryOptions: string[]
  /** Set when the line's description matches a highlight keyword. The
   * row gets a yellow background to flag it for review. Wins over the
   * "assigned = soft green" styling since attention beats confirmation. */
  highlightMatch?: string | null
}

/**
 * One row of the CC expenses table. Renders the parsed columns
 * (read-only) plus three assignment inputs (Project combobox,
 * Description text, Category text-with-datalist) and per-row Save +
 * Delete actions.
 *
 * The row's project_id / description / category are tracked locally
 * so the Save button only fires when the user actually changes
 * something. After Save, the page revalidates and the new server
 * values become the defaults on the next render.
 */
export function ExpenseLineRow({
  line,
  projectOptions,
  categoryOptions,
  highlightMatch,
}: Props) {
  const [assignDesc, setAssignDesc] = useState(line.assignment_description ?? '')
  const [category, setCategory] = useState(line.category ?? '')
  const categoryListId = `cc-cats-${line.id}`

  // Row color priority (assigned state wins; highlight only paints
  // when nothing else does):
  //   - green  = user has saved this row ("confirmed") — highest
  //              priority; the user has explicitly taken ownership.
  //   - orange = assigned BY an auto-rule, not yet user-saved
  //              ("needs review")
  //   - yellow = unassigned AND description matches a highlight
  //              keyword ("look at this; it's probably assignable")
  //   - none   = unassigned, no match
  // auto_assigned flips false on any updateCcLine call, moving rows
  // from orange → green as the user works through them.
  const rowStyle = line.project_id
    ? line.auto_assigned
      ? { background: '#fed7aa' /* orange-200 */ }
      : { background: '#d1fae5' /* green-200 */ }
    : highlightMatch
      ? { background: '#fef9c3' /* yellow-100 */ }
      : undefined

  return (
    <tr
      style={rowStyle}
      title={
        highlightMatch
          ? `Highlight match: "${highlightMatch}"`
          : undefined
      }
    >
      <td className="muted" style={{ fontSize: '0.85em', whiteSpace: 'nowrap' }}>
        {line.expense_date ?? <span style={{ color: '#b91c1c' }}>?</span>}
      </td>
      <td style={{ fontFamily: 'monospace', fontSize: '0.85em' }}>
        {line.description ?? <span className="muted">—</span>}
      </td>
      <td className="num" style={{ whiteSpace: 'nowrap' }}>
        {line.amount_usd != null ? fmtUsd(line.amount_usd) : '—'}
      </td>
      <td colSpan={4} style={{ padding: '0.3rem 0.4rem' }}>
        <form action={updateCcLine}>
          <input type="hidden" name="id" value={line.id} />
          <input type="hidden" name="batch_id" value={line.batch_id} />
          <div
            style={{
              display: 'grid',
              gridTemplateColumns: '2fr 1.5fr 1.5fr auto',
              gap: '0.4rem',
              alignItems: 'center',
            }}
          >
            <SearchableCombobox
              name="project_id"
              options={projectOptions}
              placeholder="search projects…"
              defaultId={line.project_id}
            />
            <input
              type="text"
              name="assignment_description"
              placeholder="e.g. Google"
              value={assignDesc}
              onChange={(e) => setAssignDesc(e.target.value)}
              style={{ padding: '0.35rem 0.5rem', fontSize: '0.85rem' }}
            />
            <input
              type="text"
              name="category"
              list={categoryListId}
              placeholder="e.g. Client Advertising Spend"
              value={category}
              onChange={(e) => setCategory(e.target.value)}
              style={{ padding: '0.35rem 0.5rem', fontSize: '0.85rem' }}
            />
            <datalist id={categoryListId}>
              {categoryOptions.map((c) => (
                <option key={c} value={c} />
              ))}
            </datalist>
            <div className="flex-row" style={{ gap: '0.4rem' }}>
              <button type="submit" style={{ padding: '0.3rem 0.7rem' }}>
                Save
              </button>
            </div>
          </div>
        </form>
      </td>
      <td className="right" style={{ verticalAlign: 'middle' }}>
        <DeleteForm
          action={deleteCcLine}
          id={line.id}
          extra={{ batch_id: line.batch_id }}
          confirmText="Delete this line? Cannot be undone."
          label="🗑️"
        />
      </td>
    </tr>
  )
}
