// Aria editor — Skill section: expandable skill cards with attributes & action.
const { Card, Badge, Button, IconButton, TextField, Select, RadioGroup, Switch, Checkbox, Icon } = window.AriaDesignSystem_af77ab;

function ActionTypeBadge({ type }) {
  const map = { http_native: ["info", "Chiamata HTTP"], reply: ["success", "Risposta"], builtin: ["neutral", "Predefinita"] };
  const [tone, label] = map[type] || ["neutral", type];
  return <Badge tone={tone}>{label}</Badge>;
}

function AttributeRow({ attr, base, onChange, onRemove, errText }) {
  const { enums } = window.AriaData;
  return (
    <div style={{ border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-md)", padding: 14, display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px 16px", background: "var(--surface-card)" }}>
      <TextField label="Nome" required value={attr.name} error={errText && errText(`${base}.name`)} onChange={(e) => onChange(`${base}.name`, e.target.value)} />
      <Select label="Tipo" required value={attr.type} onChange={(e) => onChange(`${base}.type`, e.target.value)} options={enums.attrType} />
      <RadioGroup label="Validazione" value={attr.validation || "strict"} onChange={(v) => onChange(`${base}.validation`, v)} options={enums.validation} />
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 12 }}>
        <Switch checked={!!attr.internal} onChange={(e) => onChange(`${base}.internal`, e.target.checked)} label="Interno" />
        <Button variant="ghost" size="sm" iconLeft={<Icon name="trash-2" size={15} />} onClick={onRemove}>Rimuovi</Button>
      </div>
      {attr.collectionHint != null && (
        <div style={{ gridColumn: "1 / -1" }}>
          <TextField label="Suggerimento di raccolta" optional value={attr.collectionHint} onChange={(e) => onChange(`${base}.collectionHint`, e.target.value)} />
        </div>
      )}
    </div>
  );
}

function ActionEditor({ action, base, onChange, isPending, errText }) {
  const { enums } = window.AriaData;
  const type = action.type;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <RadioGroup label="Tipo di azione" required value={type} onChange={(v) => onChange(`${base}.type`, v)} options={enums.actionType} />
      {type === "http_native" && (
        <React.Fragment>
          <TextField label="URL" required
            value={isPending(action.url) ? "" : action.url}
            error={errText ? errText(`${base}.url`) : (isPending(action.url) ? "Da completare" : undefined)}
            placeholder="https://api.acme.it/ordini/stato"
            onChange={(e) => onChange(`${base}.url`, e.target.value)} />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start" }}>
            <Select label="Autenticazione" value={(action.auth && action.auth.kind) || "none"} onChange={(e) => onChange(`${base}.auth.kind`, e.target.value)} options={enums.authKind} />
            {action.auth && action.auth.kind !== "none" && (
              <TextField label="Token" required
                value={isPending(action.auth.token) ? "" : (action.auth.token || "")}
                error={errText ? errText(`${base}.auth.token`) : (isPending(action.auth.token) ? "Da completare" : undefined)}
                placeholder="••••••••" type="password"
                onChange={(e) => onChange(`${base}.auth.token`, e.target.value)} />
            )}
          </div>
          <Checkbox checked={!!action.confirmBeforeExecute} onChange={(e) => onChange(`${base}.confirmBeforeExecute`, e.target.checked)} label="Conferma prima di eseguire" />
        </React.Fragment>
      )}
      {type === "reply" && (
        <TextField label="Testo della risposta" required multiline rows={3} value={action.text || ""} error={errText && errText(`${base}.text`)} onChange={(e) => onChange(`${base}.text`, e.target.value)} />
      )}
      {type === "builtin" && (
        <TextField label="Funzione predefinita" value={action.builtin || ""} disabled hint="Funzione di sistema — non modificabile." />
      )}
    </div>
  );
}

function SkillCard({ skill, index, onChange, onRemove, open, onToggle, errText, onAiEdit }) {
  const { enums } = window.AriaData;
  const { isPending } = window.AriaEditorUtil;
  const base = `skills.${index}`;
  const pendingInSkill = (skill.action && (isPending(skill.action.url) || (skill.action.auth && isPending(skill.action.auth.token))));

  function addAttr() {
    const next = (skill.attributes || []).concat({ name: "", type: "string", validation: "strict", internal: false, scope: "conversation", sources: [{ type: "user_input", priority: 10 }] });
    onChange(`${base}.attributes`, next);
  }
  function removeAttr(i) {
    onChange(`${base}.attributes`, skill.attributes.filter((_, x) => x !== i));
  }

  return (
    <Card flat style={{ overflow: "hidden" }}>
      <button onClick={onToggle} style={{
        display: "flex", alignItems: "center", gap: 12, width: "100%", border: 0, background: open ? "var(--surface-tint)" : "var(--surface-card)",
        padding: "14px 16px", cursor: "pointer", textAlign: "left",
      }}>
        <Icon name={open ? "chevron-down" : "chevron-right"} size={18} color="var(--text-muted)" />
        <span style={{ width: 30, height: 30, borderRadius: 8, background: "var(--sage-100)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
          <Icon name="puzzle" size={16} color="var(--primary-text)" />
        </span>
        <span style={{ display: "flex", flexDirection: "column", lineHeight: 1.3, flex: 1, minWidth: 0 }}>
          <span style={{ fontWeight: 500, color: "var(--text-strong)", fontSize: 14 }}>{skill.id || "Nuova skill"}</span>
          <span style={{ fontSize: 12, color: "var(--text-muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{skill.description}</span>
        </span>
        {pendingInSkill && <Badge tone="danger">Da completare</Badge>}
        {skill.priority === "low" && <Badge tone="neutral">Bassa priorità</Badge>}
        <ActionTypeBadge type={skill.action.type} />
      </button>

      {open && (
        <div style={{ padding: 18, display: "flex", flexDirection: "column", gap: 20, borderTop: "1px solid var(--border-subtle)" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start" }}>
            <TextField label="ID skill" required value={skill.id} onChange={(e) => onChange(`${base}.id`, e.target.value)} />
            <RadioGroup label="Priorità" value={skill.priority || "normal"} onChange={(v) => onChange(`${base}.priority`, v)} options={enums.priority} />
          </div>
          <TextField label="Descrizione" required multiline rows={2} value={skill.description} onChange={(e) => onChange(`${base}.description`, e.target.value)} />

          <section>
            <div style={{ display: "flex", alignItems: "center", marginBottom: 10 }}>
              <span style={{ font: "var(--text-h3)", color: "var(--text-strong)" }}>Attributi</span>
              <Badge tone="neutral" style={{ marginLeft: 8 }}>{(skill.attributes || []).length}</Badge>
              <Button variant="ghost" size="sm" style={{ marginLeft: "auto" }} iconLeft={<Icon name="plus" size={15} />} onClick={addAttr}>Aggiungi attributo</Button>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {(skill.attributes || []).length === 0 && <p style={{ fontSize: 13, color: "var(--text-subtle)" }}>Nessun attributo da raccogliere.</p>}
              {(skill.attributes || []).map((attr, i) => (
                <AttributeRow key={i} attr={attr} base={`${base}.attributes.${i}`} onChange={onChange} onRemove={() => removeAttr(i)} errText={errText} />
              ))}
            </div>
          </section>

          <section>
            <div style={{ font: "var(--text-h3)", color: "var(--text-strong)", marginBottom: 10 }}>Azione</div>
            <ActionEditor action={skill.action} base={`${base}.action`} onChange={onChange} isPending={isPending} errText={errText} />
          </section>

          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderTop: "1px solid var(--border-subtle)", paddingTop: 14 }}>
            <Button variant="ghost" size="sm" iconLeft={<Icon name="sparkles" size={15} />} onClick={() => onAiEdit && onAiEdit(index)}>Rigenera con AI</Button>
            <Button variant="danger" size="sm" iconLeft={<Icon name="trash-2" size={15} />} onClick={onRemove}>Rimuovi skill</Button>
          </div>
        </div>
      )}
    </Card>
  );
}

function SkillSection({ config, onChange, errText, focus, onAiEdit }) {
  const [open, setOpen] = React.useState(0);
  React.useEffect(() => {
    if (focus && focus.nonce) setOpen(focus.index);
  }, [focus && focus.nonce]);
  function addSkill() {
    const next = config.skills.concat({ id: "", description: "", priority: "normal", attributes: [], requires: [], action: { type: "reply", text: "" } });
    onChange("skills", next);
    setOpen(next.length - 1);
  }
  function removeSkill(i) {
    onChange("skills", config.skills.filter((_, x) => x !== i));
    setOpen(null);
  }
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      {config.skills.map((s, i) => (
        <SkillCard key={i} skill={s} index={i} onChange={onChange} onRemove={() => removeSkill(i)} open={open === i} onToggle={() => setOpen(open === i ? null : i)} errText={errText} onAiEdit={onAiEdit} />
      ))}
      <Button variant="secondary" iconLeft={<Icon name="plus" />} onClick={addSkill} style={{ alignSelf: "flex-start" }}>Aggiungi skill</Button>
    </div>
  );
}

Object.assign(window, { SkillSection });
