/**
 * Basic AI form builder (All Forms › Build with AI): describe a form, check the fields, create it.
 * New forms only, common field types, up to 12 fields. FormGlut Pro replaces this button
 * (key "fg-ai") with its advanced builder.
 */
import React, { useState } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { Button, Empty, Input, Modal, Tag, message } from 'antd';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faWandMagicSparkles } from '@fortawesome/free-solid-svg-icons';
import * as api from '../services/api';
import { createField } from '../fields/fieldTypes.jsx';
import { _pg } from './adminData';

const ai = () => ((window.formglut_admin || {}).ai || {});

let seq = 0;
/** Turn the AI's field list into real FormGlut fields. */
function buildFields(list) {
  return list.map((x) => {
    const f = { ...createField(x.type), id: 'ai' + Date.now().toString(36) + (++seq) };
    if (x.label) f.label = x.label;
    f.required = !!x.required;
    if (x.placeholder && 'placeholder' in f) f.placeholder = x.placeholder;
    if (x.help) f.help_text = x.help;
    if (Array.isArray(x.options) && x.options.length && Array.isArray(f.options)) {
      const tpl = f.options[0] || { label: '', value: '' };
      f.options = x.options.map((o, i) => ({ ...tpl, label: o, value: String(o).toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '') || 'option' + (i + 1) }));
    }
    return f;
  });
}

function AIModal({ onClose }) {
  const [prompt, setPrompt] = useState('');
  const [busy, setBusy] = useState(false);
  const [result, setResult] = useState(null);

  const ask = async () => {
    setBusy(true); setResult(null);
    try { setResult(await api.request('formglut_ai_build', { prompt }, 'POST')); } catch (e) { message.error(e.message); }
    setBusy(false);
  };
  const create = async () => {
    setBusy(true);
    try {
      const r = await api.createForm({ title: result.title || __( 'New form', 'formglut' ), fields: buildFields(result.fields), submit_btn: {}, settings: {} });
      window.location.href = _pg.editor + '&form_id=' + r.form_id;
    } catch (e) { message.error(e.message); setBusy(false); }
  };

  const footer = !ai().ready ? null : result
    ? [<Button key="b" onClick={() => setResult(null)}>{__( 'Back', 'formglut' )}</Button>, <Button key="c" type="primary" loading={busy} disabled={!result.fields.length} onClick={create}>{__( 'Create form', 'formglut' )}</Button>]
    : [<Button key="a" type="primary" loading={busy} disabled={prompt.trim().length < 5} onClick={ask}>{__( 'Generate', 'formglut' )}</Button>];

  return (
    <Modal open onCancel={onClose} width={620} title={__( 'Build a form with AI', 'formglut' )} footer={footer}>
      {!ai().ready ? (
        <Empty description={<span>{__( 'Add your Claude API key first.', 'formglut' )} <a href={_pg.settings + '&section=ai'}>{__( 'Open settings', 'formglut' )}</a></span>} />
      ) : !result ? (
        <>
          <Input.TextArea rows={5} value={prompt} maxLength={2000} onChange={(e) => setPrompt(e.target.value)}
            placeholder={__( 'e.g. A contact form for a bakery: name, email, phone, cake type, pickup date and a message', 'formglut' )} />
          <p style={{ color: '#64748b', fontSize: 12, margin: '8px 0 0' }}>
            {sprintf(__( 'Basic builder: up to %d fields with text, email, phone, number, date, paragraph and choice fields. Only your description is sent to Anthropic.', 'formglut' ), ai().max_fields || 12)}{' '}
            <a href={_pg.pro_features} target="_blank" rel="noopener noreferrer">{__( 'Pro: every field type, longer forms, add fields to existing forms, AI on entries.', 'formglut' )}</a>
          </p>
        </>
      ) : (
        <div>
          <h3 style={{ marginTop: 0 }}>{result.title}</h3>
          {!result.fields.length ? <Empty description={__( 'No usable fields came back. Try again with more detail.', 'formglut' )} /> : (
            <ol style={{ paddingLeft: 18 }}>
              {result.fields.map((f, i) => (
                <li key={i} style={{ marginBottom: 4 }}>
                  <strong>{f.label}</strong> <Tag>{f.type}</Tag>{f.required && <Tag color="red">{__( 'required', 'formglut' )}</Tag>}
                  {f.options && <div style={{ fontSize: 12, color: '#64748b' }}>{f.options.join(' · ')}</div>}
                </li>
              ))}
            </ol>
          )}
        </div>
      )}
    </Modal>
  );
}

export default function AIBuilder() {
  const [open, setOpen] = useState(false);
  return (
    <>
      <Button icon={<FontAwesomeIcon icon={faWandMagicSparkles} />} onClick={() => setOpen(true)}>{__( 'Build with AI', 'formglut' )}</Button>
      {open && <AIModal onClose={() => setOpen(false)} />}
    </>
  );
}
