import Link from 'next/link'
import { createClient } from '@/lib/supabase/server'
import { getAppOrg } from '@/lib/org'
import { getEffectiveUser } from '@/lib/effective-user'
import { canTransfer } from '@/lib/permissions'
import { fmtUsd } from '@/lib/format'
import { DeleteForm } from '@/components/delete-form'
import { createCcBatch, deleteCcBatch } from './actions'

type BatchRow = {
  id: string
  name: string
  created_at: string
}

export default async function CcExpensesListPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string; info?: string; new?: string }>
}) {
  const sp = await searchParams
  const supabase = await createClient()
  const org = await getAppOrg(supabase)
  if (!org) {
    return (
      <main>
        <h1>Credit Card Expenses</h1>
        <p className="error">Bowden Works organization not found.</p>
      </main>
    )
  }
  const eu = await getEffectiveUser(supabase, org.id)
  if (!canTransfer(eu)) {
    return (
      <main>
        <h1>Credit Card Expenses</h1>
        <p className="error">Owner only.</p>
      </main>
    )
  }

  const showNew = sp.new === '1'

  const { data: batches } = await supabase
    .from('cc_expense_batches')
    .select('id, name, created_at')
    .eq('org_id', org.id)
    .order('created_at', { ascending: false })
    .returns<BatchRow[]>()

  // Per-batch aggregates: line count + assigned count + total amount.
  // Fetched as one round-trip via the lines table; cheap at this scale.
  const ids = (batches ?? []).map((b) => b.id)
  const totals = new Map<
    string,
    { lines: number; assigned: number; total: number }
  >()
  if (ids.length > 0) {
    const { data: aggRows } = await supabase
      .from('cc_expense_lines')
      .select('batch_id, project_id, amount_usd')
      .in('batch_id', ids)
      .returns<
        {
          batch_id: string
          project_id: string | null
          amount_usd: number | string | null
        }[]
      >()
    for (const r of aggRows ?? []) {
      const cur = totals.get(r.batch_id) ?? {
        lines: 0,
        assigned: 0,
        total: 0,
      }
      cur.lines += 1
      if (r.project_id) cur.assigned += 1
      cur.total += Number(r.amount_usd ?? 0)
      totals.set(r.batch_id, cur)
    }
  }

  return (
    <main>
      <div className="page-head">
        <div>
          <p className="muted" style={{ fontSize: '0.85em', margin: 0 }}>
            <Link href="/tools">← Tools</Link>
          </p>
          <h1 style={{ margin: '0.1rem 0' }}>
            Bill Through Credit Card Expenses
          </h1>
          <p className="subtitle">
            Paste raw CC statement lines into a batch, assign each to a
            (client × project), and copy the paste block into the
            PlusROI sheet.
          </p>
        </div>
        <div className="flex-row" style={{ gap: '0.5rem' }}>
          <Link
            href="/tools/cc-expenses/rules"
            className="button-link-secondary"
          >
            Manage rules
          </Link>
          {!showNew && (
            <Link
              href="/tools/cc-expenses?new=1"
              className="button-link"
              scroll={false}
            >
              + New batch
            </Link>
          )}
        </div>
      </div>

      {sp.error && <p className="error">{sp.error}</p>}
      {sp.info && <p className="info">{sp.info}</p>}

      {showNew && (
        <div className="panel" style={{ marginBottom: '1.25rem' }}>
          <div className="panel-header">
            <h3 style={{ margin: 0, fontSize: '0.95rem' }}>New batch</h3>
          </div>
          <form action={createCcBatch}>
            <label>
              Batch name
              <input
                type="text"
                name="name"
                placeholder="e.g. April 2026 PlusROI"
                required
                autoFocus
              />
            </label>
            <div className="flex-row" style={{ gap: '0.5rem', marginTop: '0.75rem' }}>
              <button type="submit">Create batch</button>
              <Link
                href="/tools/cc-expenses"
                className="button-link-secondary"
              >
                Cancel
              </Link>
            </div>
          </form>
        </div>
      )}

      {batches && batches.length > 0 ? (
        <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
          <div className="table-wrap" style={{ border: 'none', borderRadius: 0 }}>
            <table className="data">
              <thead>
                <tr>
                  <th>Name</th>
                  <th className="num">Lines</th>
                  <th className="num">Assigned</th>
                  <th className="num">Total</th>
                  <th>Created</th>
                  <th />
                </tr>
              </thead>
              <tbody>
                {batches.map((b) => {
                  const t = totals.get(b.id) ?? {
                    lines: 0,
                    assigned: 0,
                    total: 0,
                  }
                  return (
                    <tr key={b.id}>
                      <td>
                        <Link href={`/tools/cc-expenses/${b.id}`}>
                          {b.name}
                        </Link>
                      </td>
                      <td className="num">{t.lines}</td>
                      <td className="num">
                        {t.assigned}
                        {t.lines > 0 && (
                          <span
                            className="muted"
                            style={{ fontSize: '0.78em', marginLeft: '0.3em' }}
                          >
                            ({Math.round((t.assigned / t.lines) * 100)}%)
                          </span>
                        )}
                      </td>
                      <td className="num">{fmtUsd(t.total)}</td>
                      <td className="muted" style={{ fontSize: '0.85em' }}>
                        {b.created_at.slice(0, 10)}
                      </td>
                      <td className="right">
                        <DeleteForm
                          action={deleteCcBatch}
                          id={b.id}
                          confirmText={`Delete batch "${b.name}" and all its lines? Cannot be undone.`}
                        />
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        </div>
      ) : (
        <p className="empty">No batches yet.</p>
      )}
    </main>
  )
}
