'use client'

import { useState } from 'react'

type Props = {
  /** Pre-rendered tab-separated lines, one per (client × project)
   * breakdown row. Joined with newlines. Empty string = no rows yet. */
  text: string
}

/**
 * Tab-separated paste block for the legacy PlusROI sheet. Renders the
 * text in a fixed-width &lt;pre&gt; (triple-click to select all) plus a
 * one-click "Copy" button. No file download — the destination is a
 * Google Sheet paste, not an import.
 *
 * Each line shape (see lib/invoices.ts &gt; formatPasteBlock):
 *   {client} : {project}<TAB>Bowden Works<TAB>{amount}<TAB>{date}<TAB><TAB>Bowden Works<TAB>Labour
 *
 * The 5th column is intentionally empty per the destination sheet's
 * column layout (per user direction 2026-05-25).
 */
export function PasteBlock({ text }: Props) {
  const [copied, setCopied] = useState(false)

  async function onCopy() {
    try {
      await navigator.clipboard.writeText(text)
      setCopied(true)
      setTimeout(() => setCopied(false), 1500)
    } catch {
      // Clipboard API can fail under non-HTTPS or restrictive
      // permissions. The &lt;pre&gt; below is the fallback — user can
      // triple-click + Ctrl+C.
    }
  }

  if (!text) {
    return (
      <p className="muted" style={{ padding: '1rem', margin: 0 }}>
        Apply some entries to this invoice first — the paste block needs
        at least one (client × project) row to render.
      </p>
    )
  }

  return (
    <div style={{ padding: '0.75rem 1rem' }}>
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '0.4rem',
        }}
      >
        <span className="muted" style={{ fontSize: '0.85em' }}>
          One line per (client × project). Paste into the PlusROI sheet
          starting at the Description column.
        </span>
        <button type="button" className="secondary" onClick={onCopy}>
          {copied ? '✓ Copied' : 'Copy to clipboard'}
        </button>
      </div>
      <pre
        style={{
          background: '#f5f5f5',
          padding: '0.6rem 0.75rem',
          borderRadius: 4,
          overflowX: 'auto',
          fontSize: '0.85rem',
          lineHeight: 1.4,
          margin: 0,
          whiteSpace: 'pre',
        }}
      >
        {text}
      </pre>
    </div>
  )
}
