'use client';

import { useState } from 'react';
import { createPrivateApp, type PrivateApp } from '@/features/private-apps/api.client';
import { errorText } from '@/lib/api/errors';
import { ScopeChips, ScopeDrawer, useScopeCatalog } from '../service-keys/ScopeDrawer';

const NAME_MAX = 100;
const DESCRIPTION_MAX = 120;

/**
 * HUB-745 (QA #922): "Create legacy app" makes a private app again: a name, a description and its
 * scopes (POST /private-apps). Its token is shown on the new app's Auth tab.
 */
export function CreateLegacyAppForm({
  onCreated,
  onCancel,
}: {
  onCreated: (app: PrivateApp) => void;
  onCancel: () => void;
}) {
  const { catalog, error: catalogError } = useScopeCatalog();
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [scopes, setScopes] = useState<string[]>([]);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const problem = !name.trim()
    ? 'Give the app a name.'
    : !scopes.length
      ? 'Add at least one scope.'
      : null;

  const create = async () => {
    if (problem) {
      setError(problem);
      return;
    }
    setSaving(true);
    setError(null);
    try {
      const created = await createPrivateApp({
        name: name.trim(),
        ...(description.trim() ? { description: description.trim() } : {}),
        scopes,
      });
      onCreated(created);
    } catch (err) {
      setError(errorText(err));
    } finally {
      setSaving(false);
    }
  };

  return (
    <form
      className="la-modal-body"
      noValidate
      onSubmit={(e) => {
        e.preventDefault();
        void create();
      }}
    >
      <div className="ase-field-group">
        <label htmlFor="la-new-name" className="ase-label">
          Name <span className="ase-required">*</span>
        </label>
        <input
          id="la-new-name"
          className="ase-input"
          value={name}
          maxLength={NAME_MAX}
          autoFocus
          onChange={(e) => setName(e.target.value)}
        />
      </div>
      <div className="ase-field-group">
        <label htmlFor="la-new-desc" className="ase-label">
          Description
        </label>
        <textarea
          id="la-new-desc"
          className="ase-textarea"
          rows={3}
          maxLength={DESCRIPTION_MAX}
          value={description}
          onChange={(e) => setDescription(e.target.value)}
        />
      </div>
      <div className="ase-field-group">
        <div className="ase-scopes-header">
          <span className="ase-label">
            Scopes <span className="ase-required">*</span>
          </span>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => setDrawerOpen(true)}
          >
            Add new scope
          </button>
        </div>
        <div className="sk-scope-chips">
          <ScopeChips
            scopes={scopes}
            catalog={catalog}
            onRemove={(s) => setScopes((cur) => cur.filter((x) => x !== s))}
            empty="No scopes yet. Add the ones the app needs, and no more."
          />
        </div>
      </div>
      {error ? (
        <p className="crm-text-danger crm-fs-7" role="alert">
          {error}
        </p>
      ) : null}
      <div
        className="la-modal-actions"
        style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}
      >
        <button type="button" className="btn-crm btn-crm--outline" onClick={onCancel}>
          Back
        </button>
        <button type="submit" className="btn-crm btn-crm--primary" disabled={saving}>
          {saving ? 'Creating…' : 'Create app'}
        </button>
      </div>
      {drawerOpen ? (
        <ScopeDrawer
          catalog={catalog}
          catalogError={catalogError}
          selected={scopes}
          onApply={(next) => {
            setScopes(next);
            setDrawerOpen(false);
          }}
          onClose={() => setDrawerOpen(false)}
        />
      ) : null}
    </form>
  );
}
