'use client';

import * as React from 'react';
import AdminModal from '@/app/components/admin/admin-modal.jsx';

const TASK_PRIORITIES = ['low', 'medium', 'high', 'urgent'];
const TASK_STATUSES = [
  { key: 'backlog', label: 'Backlog' },
  { key: 'todo', label: 'To do' },
  { key: 'in_progress', label: 'In progress' },
  { key: 'in_review', label: 'In review' },
  { key: 'blocked', label: 'Blocked' },
];
const RECURRENCE_PRESETS = [
  { key: '', label: 'None' },
  { key: 'daily', label: 'Daily' },
  { key: 'weekly', label: 'Weekly' },
  { key: 'monthly', label: 'Monthly' },
  { key: 'every 1d', label: 'Every 1 day' },
  { key: 'every 3d', label: 'Every 3 days' },
  { key: 'every 1w', label: 'Every 1 week' },
];

export default function NewTaskModal({ agents, projects = [], parentTasks = [], createAction }) {
  const [open, setOpen] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [activeProjectId, setActiveProjectId] = React.useState('');
  const [status, setStatus] = React.useState('todo');
  const [assignee, setAssignee] = React.useState('');
  const [tags, setTags] = React.useState([]);
  const [tagDraft, setTagDraft] = React.useState('');
  const [watchers, setWatchers] = React.useState([]);
  const [checklist, setChecklist] = React.useState([]);
  const [checklistDraft, setChecklistDraft] = React.useState('');
  const [recurrence, setRecurrence] = React.useState('');

  React.useEffect(() => {
    try { setActiveProjectId(localStorage.getItem('madarx.activeProjectId') || ''); } catch {}
    const onChange = (e) => setActiveProjectId(e?.detail?.project_id || '');
    window.addEventListener('madarx:project-change', onChange);
    return () => window.removeEventListener('madarx:project-change', onChange);
  }, []);

  React.useEffect(() => {
    if (!open) {
      setStatus('todo');
      setAssignee('');
      setTags([]);
      setTagDraft('');
      setWatchers([]);
      setChecklist([]);
      setChecklistDraft('');
      setRecurrence('');
    }
  }, [open]);

  React.useEffect(() => {
    if (!assignee && status === 'in_progress') setStatus('todo');
  }, [assignee, status]);

  const close = React.useCallback(() => {
    if (submitting) return;
    setOpen(false);
  }, [submitting]);

  function commitTag() {
    const clean = tagDraft.trim().replace(/^#/, '');
    if (!clean) return;
    if (tags.includes(clean) || tags.length >= 12) {
      setTagDraft('');
      return;
    }
    setTags([...tags, clean]);
    setTagDraft('');
  }

  function commitChecklist() {
    const clean = checklistDraft.trim();
    if (!clean) return;
    if (checklist.length >= 20) return;
    setChecklist([...checklist, clean]);
    setChecklistDraft('');
  }

  function toggleWatcher(agentId) {
    setWatchers((w) => w.includes(agentId) ? w.filter((x) => x !== agentId) : [...w, agentId]);
  }

  return (
    <>
      <button type="button" className="admin-button agents-new-cta" onClick={() => setOpen(true)}>
        <span aria-hidden className="agents-new-cta-glyph">+</span>
        New task
      </button>

      <AdminModal open={open} onClose={close} eyebrow="New task" title="Delegate work" size="wide">
        <form
          className="agents-modal-form task-modal-form"
          action={async (formData) => {
            tags.forEach((t) => formData.append('tags', t));
            watchers.forEach((w) => formData.append('watchers', w));
            checklist.forEach((c) => formData.append('checklist', c));
            formData.set('recurrence', recurrence);
            setSubmitting(true);
            try {
              await createAction(formData);
            } finally {
              setSubmitting(false);
            }
          }}
        >
          <div className="task-modal-grid">
            <section className="task-modal-main">
              <label className="agents-modal-field">
                <span>Title</span>
                <input name="title" required placeholder="What needs to happen?" autoFocus />
              </label>

              <label className="agents-modal-field">
                <span>Description</span>
                <textarea
                  name="description"
                  rows={5}
                  placeholder="Context, links, anything the assignee needs."
                />
              </label>

              <label className="agents-modal-field">
                <span>Acceptance criteria</span>
                <textarea
                  name="acceptance_criteria"
                  rows={4}
                  placeholder={'- [ ] Endpoint returns 200\n- [ ] Reviewed by Kareem\n- [ ] Deployed to staging'}
                />
              </label>

              <div className="agents-modal-field">
                <span>Checklist</span>
                <div className="task-chip-input-row">
                  <input
                    type="text"
                    value={checklistDraft}
                    onChange={(e) => setChecklistDraft(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') { e.preventDefault(); commitChecklist(); }
                    }}
                    placeholder="Add a sub-step and press Enter"
                  />
                  <button type="button" className="admin-button secondary" onClick={commitChecklist}>Add</button>
                </div>
                {checklist.length ? (
                  <ol className="task-chip-checklist">
                    {checklist.map((item, idx) => (
                      <li key={idx}>
                        <span>{item}</span>
                        <button
                          type="button"
                          aria-label={`Remove ${item}`}
                          onClick={() => setChecklist(checklist.filter((_, i) => i !== idx))}
                        >×</button>
                      </li>
                    ))}
                  </ol>
                ) : null}
              </div>

              {status === 'blocked' ? (
                <label className="agents-modal-field">
                  <span>Blocked reason</span>
                  <textarea
                    name="blocked_reason"
                    rows={2}
                    placeholder="Why is this blocked? Who or what unblocks it?"
                  />
                </label>
              ) : null}
            </section>

            <aside className="task-modal-side">
              <label className="agents-modal-field">
                <span>Project</span>
                <select name="project_id" defaultValue={activeProjectId} key={activeProjectId}>
                  <option value="">No project</option>
                  {projects.map((p) => (
                    <option key={p.id} value={p.id}>{p.name}</option>
                  ))}
                </select>
              </label>

              <label className="agents-modal-field">
                <span>Status</span>
                <select name="status" value={status} onChange={(e) => setStatus(e.target.value)}>
                  {TASK_STATUSES.map((s) => (
                    <option
                      key={s.key}
                      value={s.key}
                      disabled={s.key === 'in_progress' && !assignee}
                    >
                      {s.label}{s.key === 'in_progress' && !assignee ? ' — needs assignee' : ''}
                    </option>
                  ))}
                </select>
              </label>

              <label className="agents-modal-field">
                <span>Priority</span>
                <select name="priority" defaultValue="medium">
                  {TASK_PRIORITIES.map((p) => <option key={p} value={p}>{p}</option>)}
                </select>
              </label>

              <label className="agents-modal-field">
                <span>Assignee</span>
                <select
                  name="assignee_agent_id"
                  value={assignee}
                  onChange={(e) => setAssignee(e.target.value)}
                >
                  <option value="">Unassigned (backlog)</option>
                  {agents.map((agent) => <option key={agent.id} value={agent.id}>{agent.name}</option>)}
                </select>
              </label>

              <div className="agents-modal-field task-modal-field-row">
                <label className="task-modal-half">
                  <span>Due date</span>
                  <input type="date" name="due_at" />
                </label>
                <label className="task-modal-half">
                  <span>Estimate (min)</span>
                  <input type="number" name="estimate_minutes" min="0" step="15" placeholder="e.g. 60" />
                </label>
              </div>

              <div className="agents-modal-field">
                <span>Tags</span>
                <div className="task-chip-input-row">
                  <input
                    type="text"
                    value={tagDraft}
                    onChange={(e) => setTagDraft(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); commitTag(); }
                      else if (e.key === 'Backspace' && !tagDraft && tags.length) {
                        setTags(tags.slice(0, -1));
                      }
                    }}
                    onBlur={commitTag}
                    placeholder="Type and press Enter"
                  />
                </div>
                {tags.length ? (
                  <div className="task-chip-list">
                    {tags.map((t) => (
                      <span key={t} className="task-chip">
                        #{t}
                        <button type="button" aria-label={`Remove ${t}`} onClick={() => setTags(tags.filter((x) => x !== t))}>×</button>
                      </span>
                    ))}
                  </div>
                ) : null}
              </div>

              <div className="agents-modal-field">
                <span>Watchers</span>
                <div className="task-watcher-grid">
                  {agents.length === 0 ? (
                    <small className="task-modal-hint">No agents available.</small>
                  ) : agents.map((a) => (
                    <label key={a.id} className={'task-watcher-chip' + (watchers.includes(a.id) ? ' on' : '')}>
                      <input
                        type="checkbox"
                        checked={watchers.includes(a.id)}
                        onChange={() => toggleWatcher(a.id)}
                      />
                      <span>{a.name}</span>
                    </label>
                  ))}
                </div>
              </div>

              <label className="agents-modal-field">
                <span>Recurrence</span>
                <select value={recurrence} onChange={(e) => setRecurrence(e.target.value)}>
                  {RECURRENCE_PRESETS.map((r) => <option key={r.key} value={r.key}>{r.label}</option>)}
                </select>
                <small className="task-modal-hint">Creates next instance when this one is marked done.</small>
              </label>

              <label className="agents-modal-field">
                <span>Parent task</span>
                <select name="parent_task_id" defaultValue="">
                  <option value="">None (top-level)</option>
                  {parentTasks.map((t) => (
                    <option key={t.id} value={t.id}>
                      {t.title.length > 60 ? t.title.slice(0, 57) + '…' : t.title}
                    </option>
                  ))}
                </select>
              </label>

              <label className="agents-modal-field">
                <span>Goal ID</span>
                <input name="goal_id" placeholder="goal-… (optional)" />
              </label>
            </aside>
          </div>

          <footer className="agents-modal-foot">
            <button type="button" className="admin-button secondary" onClick={close} disabled={submitting}>
              Cancel
            </button>
            <button type="submit" className="admin-button" disabled={submitting} aria-busy={submitting || undefined}>
              {submitting ? 'Creating…' : 'Create task'}
            </button>
          </footer>
        </form>
      </AdminModal>
    </>
  );
}
