---
import type { DispatchWithAuthor, UserPublic, PulseRow } from '../../lib/db';
import { fmtDateTime } from '../../lib/markdown';
import { dispatchKindLabel } from '../../lib/format';

interface Props {
  dispatches: DispatchWithAuthor[];
  editing: DispatchWithAuthor | null;
  editingPoll: PulseRow | null;
  fenjaUsers: UserPublic[];
  currentUserId: number;
}

const { dispatches, editing, editingPoll, fenjaUsers, currentUserId } = Astro.props;

function toInputValue(sql: string | null | undefined): string {
  if (!sql) return '';
  return sql.replace(' ', 'T').slice(0, 16);
}

const pollOptionsForForm: string[] = editingPoll ? [...editingPoll.options] : [];
while (pollOptionsForForm.length < 4) pollOptionsForForm.push('');

const STATUS_LABEL: Record<string, string> = {
  draft:     'Draft',
  published: 'Published',
  archived:  'Archived',
};

const formAction = editing ? 'update_dispatch' : 'create_dispatch';
const defaultAuthorId = editing?.author_id ?? currentUserId;
---
<div class="tab-content">

  <section class="section">
    <h2 class="label-sm section-heading">{editing ? 'Edit dispatch' : 'New dispatch'}</h2>

    <form method="POST" class="invite-form" novalidate>
      <input type="hidden" name="action" value={formAction} />
      {editing && <input type="hidden" name="dispatch_id" value={editing.id} />}

      <div class="field">
        <label for="d-title" class="label-sm field-label">Title</label>
        <input type="text" id="d-title" name="title" class="input body-md" required value={editing?.title ?? ''} />
      </div>

      <div class="form-grid">
        <div class="field">
          <label for="d-kind" class="label-sm field-label">Kind</label>
          <select id="d-kind" name="kind" class="select body-md" required>
            {(['decision','update','behind_the_scenes','note'] as const).map(k => (
              <option value={k} selected={editing?.kind === k}>{dispatchKindLabel(k)}</option>
            ))}
          </select>
        </div>
        <div class="field">
          <label for="d-author" class="label-sm field-label">Author (Fenja team)</label>
          <select id="d-author" name="author_id" class="select body-md" required>
            {fenjaUsers.map(u => (
              <option value={u.id} selected={u.id === defaultAuthorId}>
                {u.name}{u.title ? ` — ${u.title}` : ''}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div class="field">
        <label for="d-excerpt" class="label-sm field-label">Excerpt (optional)</label>
        <textarea id="d-excerpt" name="excerpt" class="input body-md" rows="4">{editing?.excerpt ?? ''}</textarea>
        <span class="body-sm muted">Write 2–4 sentences. The first sentence becomes the lead paragraph on the /roadmap dispatch banner; the rest follows in muted text. Use a blank line to control the paragraph break. Falls back to the first ~200 chars of the body if empty.</span>
      </div>

      <div class="field">
        <label for="d-body" class="label-sm field-label">Body (markdown)</label>
        <textarea id="d-body" name="body" class="input body-md mono" rows="12" required>{editing?.body ?? ''}</textarea>
      </div>

      {!editing && (
        <div class="form-grid">
          <div class="field">
            <label for="d-status" class="label-sm field-label">Status on save</label>
            <select id="d-status" name="status" class="select body-md">
              <option value="draft" selected>Draft (hidden from members)</option>
              <option value="published">Published (stamps published_at)</option>
            </select>
          </div>
        </div>
      )}

      <!-- ── Attached poll (optional) ────────────────────────────── -->
      <fieldset class="poll-fieldset">
        <legend class="label-sm field-label">Attach a poll (optional)</legend>
        <input type="hidden" name="poll_explicit" value="1" />

        <p class="body-sm muted poll-help">
          Fill in a question and at least two options to attach a poll. Leave them all blank
          to {editingPoll ? 'detach the existing poll' : 'skip'}.
          {editingPoll && <span class="poll-existing-flag"> · Currently attached: pulse #{editingPoll.id}, status {editingPoll.status}.</span>}
        </p>

        <div class="field">
          <label for="d-poll-question" class="label-sm field-label">Poll question</label>
          <input
            type="text"
            id="d-poll-question"
            name="poll_question"
            class="input body-md"
            value={editingPoll?.question ?? ''}
            placeholder={editing ? editing.title : 'A question for the council'}
          />
        </div>

        <div class="poll-options-grid">
          {pollOptionsForForm.map((val, i) => (
            <input
              type="text"
              name={`poll_option_${i}`}
              placeholder={`Option ${String.fromCharCode(65 + i)}${i < 2 ? '' : ' (optional)'}`}
              class="input body-md"
              value={val}
            />
          ))}
        </div>

        <div class="form-grid">
          <div class="field">
            <label for="d-poll-opens" class="label-sm field-label">Poll opens at (UTC)</label>
            <input
              type="datetime-local"
              id="d-poll-opens"
              name="poll_opens_at"
              class="input body-md"
              value={toInputValue(editingPoll?.opens_at)}
            />
          </div>
          <div class="field">
            <label for="d-poll-closes" class="label-sm field-label">Poll closes at (UTC)</label>
            <input
              type="datetime-local"
              id="d-poll-closes"
              name="poll_closes_at"
              class="input body-md"
              value={toInputValue(editingPoll?.closes_at)}
            />
          </div>
        </div>
      </fieldset>

      <div class="form-actions">
        <button type="submit" class="btn-primary label-sm">{editing ? 'Save changes' : 'Save dispatch'}</button>
        {editing && <a href="/admin?tab=dispatches" class="action-link label-sm">Cancel</a>}
      </div>
    </form>
  </section>

  <section class="section">
    <h2 class="label-sm section-heading">All dispatches</h2>
    {dispatches.length === 0 ? (
      <p class="body-sm empty-msg">No dispatches yet.</p>
    ) : (
      <table class="data-table">
        <thead>
          <tr>
            <th class="label-sm">Title</th>
            <th class="label-sm">Kind</th>
            <th class="label-sm">Author</th>
            <th class="label-sm">Status</th>
            <th class="label-sm">Published</th>
            <th class="label-sm">Actions</th>
          </tr>
        </thead>
        <tbody>
          {dispatches.map(d => (
            <tr>
              <td class="body-sm">{d.title}</td>
              <td class="body-sm muted">{dispatchKindLabel(d.kind)}</td>
              <td class="body-sm">{d.author_name}</td>
              <td class="body-sm"><span class:list={['status-pill', `status-${d.status}`]}>{STATUS_LABEL[d.status]}</span></td>
              <td class="body-sm muted">{d.published_at ? fmtDateTime(d.published_at) : '—'}</td>
              <td class="action-cell">
                <a href={`/admin?tab=dispatches&edit=${d.id}`} class="action-link label-sm">Edit</a>
                {d.status === 'draft' && (
                  <form method="POST" class="inline-form">
                    <input type="hidden" name="action" value="publish_dispatch" />
                    <input type="hidden" name="dispatch_id" value={d.id} />
                    <button type="submit" class="action-link label-sm">Publish</button>
                  </form>
                )}
                {d.status === 'published' && (
                  <form method="POST" class="inline-form">
                    <input type="hidden" name="action" value="archive_dispatch" />
                    <input type="hidden" name="dispatch_id" value={d.id} />
                    <button type="submit" class="action-link label-sm">Archive</button>
                  </form>
                )}
                <form method="POST" class="inline-form">
                  <input type="hidden" name="action" value="delete_dispatch" />
                  <input type="hidden" name="dispatch_id" value={d.id} />
                  <button type="submit" class="danger-btn label-sm" onclick="return confirm('Delete this dispatch?')">Delete</button>
                </form>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    )}
  </section>

</div>

<style>
  .mono { font-family: var(--font-mono); font-size: var(--text-body-sm); }
  .form-actions { display: flex; gap: var(--space-3); align-items: center; }

  .poll-fieldset {
    border: 0.5px solid var(--surface-card-border);
    border-radius: var(--radius-md);
    padding: var(--space-5);
    display: flex;
    flex-direction: column;
    gap: var(--space-4);
    margin: 0;
  }
  .poll-fieldset legend {
    padding: 0 var(--space-2);
    letter-spacing: var(--tracking-wide);
    text-transform: uppercase;
    color: var(--on-surface-variant);
  }
  .poll-help { color: var(--on-surface-muted); margin: 0; }
  .poll-existing-flag { color: var(--pigment-terracotta); }
  .poll-options-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: var(--space-3);
  }
  .muted { color: var(--on-surface-muted); }

  .status-pill {
    display: inline-block;
    padding: 0.15em var(--space-3);
    border-radius: var(--radius-full);
    font-family: var(--font-sans);
    font-size: var(--text-label-sm);
    letter-spacing: var(--tracking-wide);
    text-transform: uppercase;
  }
  .status-draft     { background: var(--surface-container); color: var(--on-surface-muted); }
  .status-published { background: rgba(109, 140, 124, 0.18); color: var(--pigment-copper); font-weight: 600; }
  .status-archived  { background: var(--surface-container-low); color: var(--on-surface-muted); font-style: italic; }

  .action-cell { display: flex; gap: var(--space-3); align-items: center; flex-wrap: wrap; }
  .action-link {
    background: none;
    border: none;
    color: var(--on-surface-muted);
    text-decoration: none;
    border-bottom: none;
    letter-spacing: var(--tracking-wide);
    text-transform: uppercase;
    cursor: pointer;
    font-family: var(--font-sans);
    transition: color var(--duration-fast) var(--ease-standard);
    padding: 0;
  }
  .action-link:hover { color: var(--on-surface-variant); border-bottom: none; }
</style>
