'use client';

import * as React from 'react';
import AdminModal from '@/app/components/admin/admin-modal.jsx';
import EngineModelPicker from './engine-model-picker.jsx';
import ToolPicker from './tool-picker.jsx';
import SchedulePicker from './schedule-picker.jsx';

type EngineMeta = { id: string; label: string; available?: boolean; models?: { name: string }[]; default_model?: string };

type ToolMeta = {
  name: string;
  title: string;
  description?: string;
  category: string;
  risk_level?: string;
  available?: boolean;
  missing_env?: string[];
};

interface NewAgentModalProps {
  engines: EngineMeta[];
  agents: Array<{ id: string; name: string }>;
  tools: ToolMeta[];
  projects?: Array<{ id: string; name: string }>;
  currentProjectId?: string;
  defaultTools?: string[];
  createAction: (formData: FormData) => void | Promise<void>;
}

export default function NewAgentModal({ engines, agents, tools, projects = [], currentProjectId, defaultTools = [], createAction }: NewAgentModalProps) {
  const [open, setOpen] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);

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

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

      <AdminModal
        open={open}
        onClose={close}
        eyebrow="New agent"
        title="Compose a worker"
        size="wide"
      >
        <form
          className="agents-modal-form agents-modal-form--split"
          action={async (formData) => {
            setSubmitting(true);
            await createAction(formData);
          }}
        >
          <div className="agents-modal-body">
            <aside className="agents-modal-aside" aria-label="Tools">
              <div className="agents-modal-aside-head">
                <h3>Tools</h3>
                <p>Pick the capabilities this agent can use.</p>
              </div>
              <ToolPicker tools={tools} defaultSelected={defaultTools} />
            </aside>

            <div className="agents-modal-main">
              <section className="agents-modal-section">
                <label className="agents-modal-field wide">
                  <span>Name</span>
                  <input name="name" required placeholder="Competitor Intel" autoFocus />
                </label>
                <label className="agents-modal-field wide">
                  <span>Mission</span>
                  <textarea
                    name="mission"
                    rows={3}
                    required
                    placeholder="What this agent owns, in one or two sentences."
                    defaultValue="Support madarX OS operations."
                  />
                </label>
                {projects.length > 1 ? (
                  <label className="agents-modal-field wide">
                    <span>Project</span>
                    <select name="project_id" defaultValue={currentProjectId || 'personal'}>
                      {projects.map((p) => (
                        <option key={p.id} value={p.id}>{p.name}</option>
                      ))}
                    </select>
                  </label>
                ) : (
                  <input
                    type="hidden"
                    name="project_id"
                    value={currentProjectId || projects[0]?.id || 'personal'}
                  />
                )}
              </section>

              <section className="agents-modal-section">
                <div className="agents-modal-section-head">
                  <span>Engine</span>
                  <small>Runtime that executes this agent.</small>
                </div>
                <div className="agent-engine-form agents-modal-engine">
                  <EngineModelPicker engines={engines} initialEngine="claude-code" />
                </div>
              </section>

              <section className="agents-modal-section">
                <div className="agents-modal-section-head">
                  <span>Identity</span>
                  <small>Optional — used by agent chart.</small>
                </div>
                <div className="agents-modal-grid">
                  <label className="agents-modal-field">
                    <span>Title</span>
                    <input name="title" placeholder="e.g. Head of Marketing" />
                  </label>
                  <label className="agents-modal-field">
                    <span>Role</span>
                    <select name="role" defaultValue="individual_contributor">
                      <option value="executive">Executive</option>
                      <option value="manager">Manager</option>
                      <option value="team_lead">Team Lead</option>
                      <option value="individual_contributor">Contributor</option>
                    </select>
                  </label>
                  <label className="agents-modal-field wide">
                    <span>Reports to</span>
                    <select name="reports_to" defaultValue="">
                      <option value="">— None (top of chain)</option>
                      {agents.map((candidate) => (
                        <option key={candidate.id} value={candidate.id}>
                          {candidate.name}
                        </option>
                      ))}
                    </select>
                  </label>
                </div>
              </section>

              <section className="agents-modal-section">
                <div className="agents-modal-section-head">
                  <span>Schedule</span>
                  <small>When this agent runs.</small>
                </div>
                <SchedulePicker />
              </section>

              <section className="agents-modal-section">
                <div className="agents-modal-section-head">
                  <span>Approval</span>
                  <small>How autonomously this agent can act.</small>
                </div>
                <div className="agents-modal-radio-group" role="radiogroup" aria-label="Approval mode">
                  <label className="agents-modal-radio">
                    <input type="radio" name="approval" value="human-in-loop" defaultChecked />
                    <div className="agents-modal-radio-body">
                      <b>Standard</b>
                      <small>Asks before risky actions — deploy, merge, send email, delete data.</small>
                    </div>
                  </label>
                  <label className="agents-modal-radio">
                    <input type="radio" name="approval" value="owner-required" />
                    <div className="agents-modal-radio-body">
                      <b>Strict</b>
                      <small>Asks before every action. Best for new agents you don&apos;t fully trust yet.</small>
                    </div>
                  </label>
                </div>
              </section>
            </div>
          </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 agent'}
            </button>
          </footer>
        </form>
      </AdminModal>
    </>
  );
}
