'use client';

import { useState, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';

// Lightweight JSON workflow editor. Textarea-based so we don't ship Monaco in
// the main bundle — agents and humans pasting JSON is the primary use case.
// "Validate" hits /api/processes/definitions/validate (no DB write).
// "Publish" hits POST /api/processes/definitions.

export default function DefinitionEditor({ starterSpec }) {
  const router = useRouter();
  const [text, setText] = useState(() => JSON.stringify(starterSpec, null, 2));
  const [parseError, setParseError] = useState(null);
  const [validationResult, setValidationResult] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);

  const parsed = useMemo(() => {
    try {
      return { spec: JSON.parse(text), error: null };
    } catch (err) {
      return { spec: null, error: err.message };
    }
  }, [text]);

  const handleChange = useCallback((e) => {
    setText(e.target.value);
    setParseError(null);
    setValidationResult(null);
    setSubmitError(null);
  }, []);

  const handleValidate = useCallback(async () => {
    if (parsed.error) {
      setParseError(parsed.error);
      setValidationResult(null);
      return;
    }
    setParseError(null);
    try {
      const res = await fetch('/api/processes/definitions/validate', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ spec: parsed.spec }),
      });
      const data = await res.json();
      setValidationResult(data);
    } catch (err) {
      setValidationResult({ ok: false, errors: [err.message || String(err)], warnings: [] });
    }
  }, [parsed]);

  const handlePublish = useCallback(async () => {
    if (parsed.error) {
      setParseError(parsed.error);
      return;
    }
    setSubmitting(true);
    setSubmitError(null);
    try {
      const res = await fetch('/api/processes/definitions', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ spec: parsed.spec }),
      });
      const data = await res.json();
      if (!res.ok || !data.ok) {
        setSubmitError(data);
        setValidationResult({
          ok: false,
          errors: data.errors || [data.error || data.message || 'unknown error'],
          warnings: [],
        });
        return;
      }
      router.push(`/workflows`);
      router.refresh();
    } catch (err) {
      setSubmitError({ error: err.message || String(err) });
    } finally {
      setSubmitting(false);
    }
  }, [parsed, router]);

  const summary = useMemo(() => {
    if (parsed.error || !parsed.spec) return null;
    const s = parsed.spec;
    return {
      slug: s.slug || '—',
      name: s.name || '—',
      stages: Array.isArray(s.stages) ? s.stages.length : 0,
      version: s.version || 1,
      status: s.status || 'draft',
    };
  }, [parsed]);

  return (
    <div className="wf-editor">
      <aside className="wf-editor-sidebar">
        <div className="wf-editor-summary">
          <h3>Spec summary</h3>
          {parseError || parsed.error ? (
            <p className="wf-editor-parse-err">JSON parse error: {parseError || parsed.error}</p>
          ) : summary ? (
            <dl>
              <dt>Slug</dt><dd>{summary.slug}</dd>
              <dt>Name</dt><dd>{summary.name}</dd>
              <dt>Version</dt><dd>v{summary.version}</dd>
              <dt>Status</dt><dd>{summary.status}</dd>
              <dt>Stages</dt><dd>{summary.stages}</dd>
            </dl>
          ) : null}
        </div>

        <div className="wf-editor-actions">
          <button className="wf-defcard-btn" onClick={handleValidate} disabled={submitting}>
            Validate
          </button>
          <button
            className="wf-defcard-btn wf-defcard-btn--primary"
            onClick={handlePublish}
            disabled={submitting || Boolean(parsed.error)}
          >
            {submitting ? 'Publishing…' : 'Publish'}
          </button>
        </div>

        {validationResult ? (
          <div className={`wf-editor-result wf-editor-result--${validationResult.ok ? 'ok' : 'err'}`}>
            <strong>{validationResult.ok ? 'Spec is valid' : 'Spec has errors'}</strong>
            {validationResult.errors && validationResult.errors.length ? (
              <ul>
                {validationResult.errors.map((e, i) => (<li key={i}>{e}</li>))}
              </ul>
            ) : null}
            {validationResult.warnings && validationResult.warnings.length ? (
              <details>
                <summary>{validationResult.warnings.length} warning{validationResult.warnings.length === 1 ? '' : 's'}</summary>
                <ul>
                  {validationResult.warnings.map((w, i) => (<li key={i}>{w}</li>))}
                </ul>
              </details>
            ) : null}
          </div>
        ) : null}

        {submitError ? (
          <div className="wf-editor-result wf-editor-result--err">
            <strong>Publish failed</strong>
            <p>{submitError.error || submitError.message || 'unknown'}</p>
          </div>
        ) : null}

        <p className="wf-editor-hint">
          Validate runs the same rules the engine enforces at write time. Publishing creates the
          workflow as <code>draft</code> by default — set <code>status: "published"</code> in the
          spec to make it appear under <a href="/workflows">/workflows</a>.
        </p>
      </aside>

      <div className="wf-editor-codepane">
        <textarea
          className="wf-editor-textarea"
          value={text}
          onChange={handleChange}
          spellCheck={false}
          autoComplete="off"
          autoCapitalize="off"
          autoCorrect="off"
          aria-label="Workflow JSON spec"
        />
      </div>
    </div>
  );
}
