import React, { useEffect, useState } from 'react';

const SCOPE_OPTIONS = [
  { id: 'plan', label: 'Plan' },
  { id: 'project', label: 'Project' },
  { id: 'global', label: 'Global' },
];

const PRIORITY_OPTIONS = [
  { value: 'high', label: 'High' },
  { value: 'medium', label: 'Medium' },
  { value: 'low', label: 'Low' },
];

type Scope = 'plan' | 'project' | 'global';
type Priority = 'high' | 'medium' | 'low';

type BacklogEntry = {
  backlogId: string;
  task: string;
  title?: string;
  desc?: string;
  status?: string;
  priority?: Priority;
  repoRoot?: string;
  worktree?: string;
  ts?: string;
  scope?: Scope;
};

type BacklogResponse = {
  scope: Scope;
  entries: BacklogEntry[];
};

export default function Backlog() {
  const [scope, setScope] = useState<Scope>('plan');
  const [entries, setEntries] = useState<BacklogEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [busyKey, setBusyKey] = useState('');

  useEffect(() => {
    let cancelled = false;

    async function load() {
      setLoading(true);
      setError('');
      try {
        const response = await fetch(`/api/gateway/backlog?scope=${encodeURIComponent(scope)}`);
        if (!response.ok) {
          throw new Error(`failed-${response.status}`);
        }
        const payload = (await response.json()) as BacklogResponse;
        if (!cancelled) {
          setEntries(Array.isArray(payload.entries) ? payload.entries : []);
        }
      } catch (_error) {
        if (!cancelled) {
          setEntries([]);
          setError('Unable to load backlog items.');
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }

    void load();

    return () => {
      cancelled = true;
    };
  }, [scope]);

  async function updatePriority(entry: BacklogEntry, priority: Priority) {
    const busyId = `priority:${entry.backlogId}`;
    setBusyKey(busyId);
    setError('');
    try {
      const response = await fetch(`/api/gateway/backlog/${encodeURIComponent(entry.backlogId)}/priority`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ priority }),
      });
      if (!response.ok) {
        throw new Error(`failed-${response.status}`);
      }
      setEntries(current =>
        current.map(item => (item.backlogId === entry.backlogId ? { ...item, priority } : item)),
      );
    } catch (_error) {
      setError('Unable to update priority.');
    } finally {
      setBusyKey('');
    }
  }

  async function rerun(entry: BacklogEntry) {
    const busyId = `rerun:${entry.backlogId}`;
    setBusyKey(busyId);
    setError('');
    try {
      const response = await fetch(`/api/gateway/backlog/${encodeURIComponent(entry.backlogId)}/requeue`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ sourceScope: scope }),
      });
      if (!response.ok) {
        throw new Error(`failed-${response.status}`);
      }
    } catch (_error) {
      setError('Unable to re-run backlog item.');
    } finally {
      setBusyKey('');
    }
  }

  return (
    <main style={styles.page}>
      <section style={styles.shell}>
        <div style={styles.header}>
          <div>
            <p style={styles.eyebrow}>Harness Control Surface</p>
            <h1 style={styles.title}>Backlog queue</h1>
            <p style={styles.lede}>Review deferred work, switch backlog scope, set priority, and re-run a task without leaving the queue.</p>
          </div>
          <div style={styles.tabs} role="tablist" aria-label="Backlog scopes">
            {SCOPE_OPTIONS.map(option => (
              <button
                key={option.id}
                type="button"
                role="tab"
                aria-selected={scope === option.id}
                onClick={() => setScope(option.id as Scope)}
                style={scope === option.id ? { ...styles.tab, ...styles.tabActive } : styles.tab}
              >
                {option.label}
              </button>
            ))}
          </div>
        </div>
        {error ? <p style={styles.error}>{error}</p> : null}
        {loading ? <p style={styles.state}>Loading backlog…</p> : null}
        {!loading && entries.length === 0 ? <p style={styles.state}>No backlog entries in this scope.</p> : null}
        <div style={styles.grid}>
          {entries.map(entry => {
            const priority = entry.priority || 'medium';
            return (
              <article key={entry.backlogId} style={styles.card}>
                <div style={styles.cardTop}>
                  <div>
                    <p style={styles.cardTitle}>{entry.title || entry.task}</p>
                    <p style={styles.cardMeta}>{entry.task}</p>
                  </div>
                  <span style={styles.status}>{entry.status || 'pending'}</span>
                </div>
                <p style={styles.desc}>{entry.desc || 'Deferred harness work item.'}</p>
                <div style={styles.metaRow}>
                  <span>{entry.repoRoot || entry.worktree || 'current repo'}</span>
                  <span>{entry.ts || 'timestamp unavailable'}</span>
                </div>
                <div style={styles.actions}>
                  <label style={styles.priorityLabel}>
                    <span>Priority</span>
                    <select
                      value={priority}
                      disabled={busyKey === `priority:${entry.backlogId}`}
                      onChange={event => {
                        const priority = event.target.value as Priority;
                        void updatePriority(entry, priority);
                      }}
                      style={styles.select}
                    >
                      {PRIORITY_OPTIONS.map(option => (
                        <option key={option.value} value={option.value}>
                          {option.label}
                        </option>
                      ))}
                    </select>
                  </label>
                  <button
                    type="button"
                    onClick={() => {
                      void rerun(entry);
                    }}
                    disabled={busyKey === `rerun:${entry.backlogId}`}
                    style={styles.rerun}
                  >
                    Re-run
                  </button>
                </div>
              </article>
            );
          })}
        </div>
      </section>
    </main>
  );
}

const styles: Record<string, React.CSSProperties> = {
  page: {
    minHeight: '100vh',
    background:
      'radial-gradient(circle at top, rgba(251, 191, 36, 0.18), transparent 34%), linear-gradient(180deg, #f8fafc 0%, #fff7ed 100%)',
    padding: '32px 20px 64px',
  },
  shell: {
    maxWidth: '1120px',
    margin: '0 auto',
    padding: '28px',
    borderRadius: '28px',
    background: 'rgba(255,255,255,0.84)',
    border: '1px solid rgba(154, 52, 18, 0.16)',
    boxShadow: '0 28px 70px rgba(15, 23, 42, 0.08)',
  },
  header: {
    display: 'flex',
    gap: '24px',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    flexWrap: 'wrap',
  },
  eyebrow: {
    margin: '0 0 12px',
    fontSize: '0.8rem',
    fontWeight: 700,
    letterSpacing: '0.16em',
    textTransform: 'uppercase',
    color: '#9a3412',
  },
  title: {
    margin: 0,
    fontSize: 'clamp(2.4rem, 5vw, 4.6rem)',
    lineHeight: 0.95,
  },
  lede: {
    maxWidth: '48rem',
    margin: '16px 0 0',
    lineHeight: 1.7,
    color: '#334155',
  },
  tabs: {
    display: 'flex',
    gap: '10px',
    flexWrap: 'wrap',
  },
  tab: {
    borderRadius: '999px',
    border: '1px solid rgba(148, 163, 184, 0.4)',
    background: '#fff',
    color: '#334155',
    padding: '10px 16px',
    fontSize: '0.95rem',
    cursor: 'pointer',
  },
  tabActive: {
    background: '#0f172a',
    color: '#fff7ed',
    borderColor: '#0f172a',
  },
  error: {
    margin: '20px 0 0',
    color: '#b91c1c',
    fontWeight: 700,
  },
  state: {
    margin: '20px 0 0',
    color: '#475569',
  },
  grid: {
    display: 'grid',
    gap: '18px',
    marginTop: '24px',
  },
  card: {
    borderRadius: '24px',
    border: '1px solid rgba(148, 163, 184, 0.2)',
    background: 'rgba(255,255,255,0.96)',
    padding: '20px',
  },
  cardTop: {
    display: 'flex',
    justifyContent: 'space-between',
    gap: '16px',
    alignItems: 'flex-start',
  },
  cardTitle: {
    margin: 0,
    fontSize: '1.2rem',
    fontWeight: 700,
  },
  cardMeta: {
    margin: '4px 0 0',
    color: '#64748b',
    fontFamily: 'ui-monospace,SFMono-Regular,Menlo,monospace',
    fontSize: '0.9rem',
  },
  status: {
    borderRadius: '999px',
    background: '#ffedd5',
    color: '#9a3412',
    padding: '6px 10px',
    fontSize: '0.82rem',
    fontWeight: 700,
    textTransform: 'uppercase',
  },
  desc: {
    margin: '16px 0 0',
    color: '#334155',
    lineHeight: 1.6,
  },
  metaRow: {
    display: 'flex',
    justifyContent: 'space-between',
    gap: '12px',
    flexWrap: 'wrap',
    marginTop: '16px',
    color: '#64748b',
    fontSize: '0.88rem',
  },
  actions: {
    display: 'flex',
    justifyContent: 'space-between',
    gap: '16px',
    flexWrap: 'wrap',
    alignItems: 'end',
    marginTop: '20px',
  },
  priorityLabel: {
    display: 'grid',
    gap: '6px',
    fontWeight: 700,
    color: '#334155',
  },
  select: {
    minWidth: '160px',
    borderRadius: '12px',
    border: '1px solid rgba(148, 163, 184, 0.4)',
    padding: '10px 12px',
    background: '#fff',
    color: '#0f172a',
  },
  rerun: {
    borderRadius: '999px',
    border: 0,
    background: '#ea580c',
    color: '#fff',
    padding: '12px 18px',
    fontWeight: 700,
    cursor: 'pointer',
  },
};
