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 {
  defaultInvoiceDate,
  formatPasteBlock,
  getInvoice,
  getInvoiceProjectBreakdown,
  getInvoiceTotals,
  type InvoiceStatus,
} from '@/lib/invoices'
import { fmtHoursMinutesSeconds, fmtUsd } from '@/lib/format'
import { DeleteForm } from '@/components/delete-form'
import { deleteInvoice, updateInvoice } from '../actions'
import { PasteBlock } from './paste-block'

const STATUS_BADGE: Record<InvoiceStatus, { label: string; color: string }> = {
  open: { label: 'Open', color: '#0a7d3f' },
  sent: { label: 'Sent', color: '#0369a1' },
  paid: { label: 'Paid', color: '#6b7280' },
}

export default async function InvoiceDetailPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>
  searchParams: Promise<{ error?: string; info?: string; edit?: string }>
}) {
  const { id } = await params
  const sp = await searchParams

  const supabase = await createClient()
  const org = await getAppOrg(supabase)
  if (!org) {
    return (
      <main>
        <h1>Invoice</h1>
        <p className="error">Bowden Works organization not found.</p>
      </main>
    )
  }

  const eu = await getEffectiveUser(supabase, org.id)
  const userCanTransfer = canTransfer(eu)

  const invoice = await getInvoice(supabase, org.id, id)
  if (!invoice) {
    return (
      <main>
        <h1>Invoice not found</h1>
        <p>
          <Link href="/invoices">← Back to invoices</Link>
        </p>
      </main>
    )
  }

  const [totals, breakdown] = await Promise.all([
    getInvoiceTotals(supabase, org.id, id),
    getInvoiceProjectBreakdown(supabase, org.id, id),
  ])

  const effectiveBillout = invoice.manual_total_usd ?? totals.billout_amount_usd
  const margin = effectiveBillout - totals.cost_usd
  const marginPct =
    effectiveBillout > 0 ? (margin / effectiveBillout) * 100 : null

  // For the edit form, pull operator + client options.
  const [{ data: operators }, { data: clients }] = await Promise.all([
    supabase
      .from('operators')
      .select('id, name')
      .eq('org_id', org.id)
      .order('name')
      .returns<{ id: string; name: string }[]>(),
    supabase
      .from('clients')
      .select('id, name, operator_id')
      .eq('org_id', org.id)
      .order('name')
      .returns<{ id: string; name: string; operator_id: string | null }[]>(),
  ])

  const editing = sp.edit === '1' && userCanTransfer

  return (
    <main>
      <div className="page-head">
        <div>
          <p className="muted" style={{ fontSize: '0.85em', margin: 0 }}>
            <Link href="/invoices">← All invoices</Link>
          </p>
          <h1 style={{ margin: '0.1rem 0' }}>
            {invoice.name}{' '}
            <span
              className="badge"
              style={{
                background: STATUS_BADGE[invoice.status].color,
                color: '#fff',
                padding: '0.2em 0.6em',
                borderRadius: 999,
                fontSize: '0.55em',
                verticalAlign: 'middle',
                marginLeft: '0.5rem',
              }}
            >
              {STATUS_BADGE[invoice.status].label}
            </span>
          </h1>
          <p className="muted" style={{ fontSize: '0.9em', margin: '0.1rem 0' }}>
            {invoice.invoice_date && (
              <>
                Invoice date <strong>{invoice.invoice_date}</strong> ·{' '}
              </>
            )}
            Created {invoice.created_at.slice(0, 10)}
            {invoice.sent_at && ` · Sent ${invoice.sent_at.slice(0, 10)}`}
            {invoice.paid_at && ` · Paid ${invoice.paid_at.slice(0, 10)}`}
          </p>
        </div>
        {userCanTransfer && !editing && (
          <div className="flex-row" style={{ gap: '0.5rem' }}>
            <Link
              href={`/invoices/${id}?edit=1`}
              className="button-link"
              scroll={false}
            >
              Edit
            </Link>
            <DeleteForm
              action={deleteInvoice}
              id={id}
              confirmText={`Delete invoice "${invoice.name}"? Attached entries will be detached and unlocked. This can't be undone.`}
            />
          </div>
        )}
      </div>

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

      {editing && (
        <div className="panel" style={{ marginBottom: '1.25rem' }}>
          <div className="panel-header">
            <h3 style={{ margin: 0, fontSize: '0.95rem' }}>Edit invoice</h3>
          </div>
          <form action={updateInvoice}>
            <input type="hidden" name="id" value={invoice.id} />
            <div
              style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
                gap: '0.75rem 1rem',
              }}
            >
              <label style={{ gridColumn: 'span 2' }}>
                Name
                <input
                  type="text"
                  name="name"
                  defaultValue={invoice.name}
                  required
                />
              </label>
              <label>
                Status
                <select name="status" defaultValue={invoice.status}>
                  <option value="open">Open</option>
                  <option value="sent">Sent</option>
                  <option value="paid">Paid</option>
                </select>
              </label>
              <label>
                Invoice date
                <input
                  type="date"
                  name="invoice_date"
                  defaultValue={invoice.invoice_date ?? defaultInvoiceDate()}
                />
              </label>
              <label>
                Operator
                <select name="operator_id" defaultValue={invoice.operator_id ?? ''}>
                  <option value="">— any —</option>
                  {(operators ?? []).map((o) => (
                    <option key={o.id} value={o.id}>
                      {o.name}
                    </option>
                  ))}
                </select>
              </label>
              <label>
                Client
                <select name="client_id" defaultValue={invoice.client_id ?? ''}>
                  <option value="">— any —</option>
                  {(clients ?? []).map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.name}
                    </option>
                  ))}
                </select>
              </label>
              <label>
                Manual total{' '}
                <span className="muted">(blank = use sum of entries)</span>
                <input
                  type="number"
                  name="manual_total_usd"
                  step="0.01"
                  min="0"
                  defaultValue={
                    invoice.manual_total_usd == null
                      ? ''
                      : invoice.manual_total_usd.toFixed(2)
                  }
                />
              </label>
              <label style={{ gridColumn: 'span 3' }}>
                Notes
                <input type="text" name="notes" defaultValue={invoice.notes ?? ''} />
              </label>
            </div>
            <div
              className="flex-row"
              style={{ gap: '0.5rem', marginTop: '0.75rem' }}
            >
              <button type="submit">Save</button>
              <Link href={`/invoices/${id}`} className="button-link-secondary">
                Cancel
              </Link>
            </div>
          </form>
        </div>
      )}

      {invoice.notes && !editing && (
        <p
          className="muted"
          style={{
            margin: '0.5rem 0 1rem',
            padding: '0.5rem 0.75rem',
            background: '#f5f5f5',
            borderRadius: 4,
          }}
        >
          {invoice.notes}
        </p>
      )}

      <div className="panel" style={{ marginBottom: '1.25rem' }}>
        <div className="stat-row">
          <div className="stat">
            <span className="stat-label">Entries</span>
            <span className="stat-value">
              {totals.row_count.toLocaleString()}
            </span>
          </div>
          <div className="stat">
            <span className="stat-label">Hours</span>
            <span className="stat-value">
              {fmtHoursMinutesSeconds(totals.source_seconds)}
            </span>
          </div>
          <div className="stat">
            <span className="stat-label">Cost</span>
            <span className="stat-value">{fmtUsd(totals.cost_usd)}</span>
          </div>
          <div className="stat">
            <span
              className="stat-label"
              title={
                invoice.manual_total_usd != null
                  ? `Manual total override. Sum of entries: ${fmtUsd(totals.billout_amount_usd)}`
                  : undefined
              }
            >
              Billout
              {invoice.manual_total_usd != null && (
                <span style={{ fontSize: '0.7em', marginLeft: '0.3em' }}>
                  ★
                </span>
              )}
            </span>
            <span className="stat-value" style={{ color: '#0a7d3f' }}>
              {fmtUsd(effectiveBillout)}
            </span>
          </div>
          <div className="stat">
            <span className="stat-label">Margin</span>
            <span
              className="stat-value"
              style={{ color: margin >= 0 ? '#0a7d3f' : '#b91c1c' }}
            >
              {margin >= 0 ? '+' : ''}
              {fmtUsd(margin)}
              {marginPct != null && (
                <span
                  className="muted"
                  style={{ fontSize: '0.6em', marginLeft: '0.3em' }}
                >
                  ({marginPct.toFixed(1)}%)
                </span>
              )}
            </span>
          </div>
        </div>
      </div>

      <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
        <div className="panel-header">
          <h3 style={{ margin: 0, fontSize: '0.95rem' }}>
            Per client × project
          </h3>
        </div>
        {breakdown.length === 0 ? (
          <p
            className="empty"
            style={{ padding: '1rem', margin: 0 }}
          >
            No entries attached yet. Go to{' '}
            <Link href="/entries">/entries</Link>, filter the rows you want,
            and use the bulk &ldquo;Apply to invoice&rdquo; action.
          </p>
        ) : (
          <div className="table-wrap" style={{ border: 'none', borderRadius: 0 }}>
            <table className="data">
              <thead>
                <tr>
                  <th>Client</th>
                  <th>Project</th>
                  <th className="num">Entries</th>
                  <th className="num">Hours</th>
                  <th className="num">Cost</th>
                  <th className="num">Billout</th>
                  <th className="num">Margin</th>
                </tr>
              </thead>
              <tbody>
                {breakdown.map((r) => {
                  const rowMargin = r.billout_amount_usd - r.cost_usd
                  const rowPct =
                    r.billout_amount_usd > 0
                      ? (rowMargin / r.billout_amount_usd) * 100
                      : null
                  return (
                    <tr key={`${r.client ?? ''}::${r.project ?? ''}`}>
                      <td>{r.client ?? <span className="muted">—</span>}</td>
                      <td>{r.project ?? <span className="muted">—</span>}</td>
                      <td className="num">{r.row_count}</td>
                      <td className="num">
                        {fmtHoursMinutesSeconds(r.source_seconds)}
                      </td>
                      <td className="num">{fmtUsd(r.cost_usd)}</td>
                      <td className="num">{fmtUsd(r.billout_amount_usd)}</td>
                      <td
                        className="num"
                        style={{ color: rowMargin >= 0 ? '#0a7d3f' : '#b91c1c' }}
                      >
                        {rowMargin >= 0 ? '+' : ''}
                        {fmtUsd(rowMargin)}
                        {rowPct != null && (
                          <span
                            className="muted"
                            style={{
                              display: 'block',
                              fontSize: '0.75em',
                              lineHeight: 1.2,
                            }}
                          >
                            {rowPct.toFixed(1)}%
                          </span>
                        )}
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <div
        className="panel"
        style={{ marginTop: '1.25rem', padding: 0, overflow: 'hidden' }}
      >
        <div className="panel-header">
          <h3 style={{ margin: 0, fontSize: '0.95rem' }}>
            Paste block for the PlusROI sheet
          </h3>
        </div>
        <PasteBlock
          text={formatPasteBlock(
            breakdown,
            invoice.invoice_date ?? defaultInvoiceDate(),
          )}
        />
      </div>

      <p style={{ marginTop: '1rem' }}>
        <Link
          href={`/entries?status=applied&invoice=${id}`}
          className="muted"
          style={{ fontSize: '0.9em' }}
        >
          → View the {totals.row_count} attached entries on /entries
        </Link>
      </p>
    </main>
  )
}
