'use client'

import { useMemo, useState } from 'react'
import { markSelectedTransferred } from './actions'
import {
  fmtHoursMinutes,
  fmtHoursMinutesSeconds,
  fmtTimestampShort,
  fmtUsd,
} from '@/lib/format'
import { SortableHeader } from '@/components/sortable-header'

type Entry = {
  id: string
  source_user_email: string | null
  operator: string | null
  client: string | null
  project: string | null
  description: string | null
  start_at: string
  converted_user: string | null
  duration_seconds: number | null
  converted_duration_seconds: number | null
  billout_cost_usd: number | null
}

type Props = {
  entries: Entry[]
  canTransfer: boolean
  defaultRelevantMonth: string
}

export function TransferTable({
  entries,
  canTransfer,
  defaultRelevantMonth,
}: Props) {
  const [selected, setSelected] = useState<Set<string>>(new Set())

  const allVisibleSelected = useMemo(
    () => entries.length > 0 && entries.every((e) => selected.has(e.id)),
    [entries, selected],
  )

  function toggleOne(id: string) {
    setSelected((prev) => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  function toggleAll() {
    if (allVisibleSelected) {
      setSelected(new Set())
    } else {
      setSelected(new Set(entries.map((e) => e.id)))
    }
  }

  const selectedHours = useMemo(() => {
    let s = 0
    for (const e of entries) {
      if (selected.has(e.id)) s += e.converted_duration_seconds ?? 0
    }
    return s
  }, [entries, selected])

  const selectedCost = useMemo(() => {
    let c = 0
    for (const e of entries) {
      if (selected.has(e.id) && e.billout_cost_usd != null) {
        c += Number(e.billout_cost_usd)
      }
    }
    return c
  }, [entries, selected])

  if (entries.length === 0) {
    return (
      <div className="panel">
        <p className="empty">No pending entries match this filter.</p>
      </div>
    )
  }

  function confirmMark(e: React.MouseEvent<HTMLButtonElement>) {
    if (
      !window.confirm(
        `Mark ${selected.size} entries (${fmtHoursMinutes(selectedHours)}, ${fmtUsd(selectedCost)}) as transferred? You can undo from the batch list below.`,
      )
    ) {
      e.preventDefault()
    }
  }

  return (
    <form>
      {[...selected].map((id) => (
        <input key={id} type="hidden" name="id" value={id} />
      ))}

      <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
        <div
          style={{
            padding: '1rem 1.25rem',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            gap: '1rem',
            flexWrap: 'wrap',
            borderBottom: '1px solid #f0f0f0',
          }}
        >
          <div>
            <h2 style={{ margin: 0, fontSize: '1.05rem' }}>
              Ready to transfer ({entries.length})
            </h2>
            <p
              className="muted"
              style={{ fontSize: '0.85em', margin: '0.25rem 0 0' }}
            >
              {selected.size} selected · {fmtHoursMinutes(selectedHours)} ·{' '}
              {fmtUsd(selectedCost)}
            </p>
          </div>
          <div
            className="flex-row"
            style={{ gap: '0.75rem', alignItems: 'flex-end', flexWrap: 'wrap' }}
          >
            <label
              style={{
                display: 'flex',
                flexDirection: 'column',
                fontSize: '0.8em',
                color: '#555',
              }}
            >
              Relevant month
              <input
                type="text"
                name="relevant_month"
                defaultValue={defaultRelevantMonth}
                pattern="\d{4}-\d{2}"
                placeholder="YYYY-MM"
                title="The billing month to tag this export with (column G in the CSV). Format: YYYY-MM."
                style={{ width: '7rem', padding: '0.3rem 0.4rem' }}
              />
            </label>
            <button
              type="submit"
              formAction="/transfer/download"
              formMethod="post"
              className="secondary"
              disabled={selected.size === 0}
            >
              Download CSV ({selected.size})
            </button>
            {canTransfer && (
              <button
                type="submit"
                formAction={markSelectedTransferred}
                disabled={selected.size === 0}
                onClick={confirmMark}
              >
                Mark {selected.size} as transferred
              </button>
            )}
          </div>
        </div>

        <div className="table-wrap" style={{ border: 'none', borderRadius: 0 }}>
          <table className="data">
            <thead>
              <tr>
                <th style={{ width: '2rem' }}>
                  <input
                    type="checkbox"
                    checked={allVisibleSelected}
                    onChange={toggleAll}
                    aria-label="Select all"
                  />
                </th>
                <th><SortableHeader sortKey="date" defaultDir="asc">Date</SortableHeader></th>
                <th><SortableHeader sortKey="user">User</SortableHeader></th>
                <th><SortableHeader sortKey="source_email">Source email</SortableHeader></th>
                <th><SortableHeader sortKey="client">Client</SortableHeader></th>
                <th><SortableHeader sortKey="project">Project</SortableHeader></th>
                <th><SortableHeader sortKey="description">Description</SortableHeader></th>
                <th className="num"><SortableHeader sortKey="source_hrs" numeric>Source hrs</SortableHeader></th>
                <th className="num"><SortableHeader sortKey="billout_hrs" numeric>Billout hrs</SortableHeader></th>
                <th className="num"><SortableHeader sortKey="cost" numeric>Cost</SortableHeader></th>
              </tr>
            </thead>
            <tbody>
              {entries.map((e) => (
                <tr key={e.id}>
                  <td>
                    <input
                      type="checkbox"
                      checked={selected.has(e.id)}
                      onChange={() => toggleOne(e.id)}
                      aria-label={`Select ${e.id}`}
                    />
                  </td>
                  <td>{fmtTimestampShort(e.start_at)}</td>
                  <td>{e.converted_user}</td>
                  <td>
                    <span className="muted" style={{ fontSize: '0.85em' }}>
                      {e.source_user_email}
                    </span>
                  </td>
                  <td>{e.client ?? '—'}</td>
                  <td>{e.project}</td>
                  <td>{e.description}</td>
                  <td className="num">
                    {fmtHoursMinutesSeconds(e.duration_seconds)}
                  </td>
                  <td className="num">
                    {fmtHoursMinutesSeconds(e.converted_duration_seconds)}
                  </td>
                  <td className="num">
                    {e.billout_cost_usd != null
                      ? fmtUsd(Number(e.billout_cost_usd))
                      : '—'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </form>
  )
}
