// Automations — list + create/edit modal. v1: only Storage upload trigger.
// The "AI authoring chat" the user described is intentionally deferred — for
// now the user types the natural-language instructions directly into a textarea
// and the backend runs them through the same AiAssistantService used by the
// in-app chat when the trigger fires.
const TRIGGER_OPTIONS = [
  { value: 1, en: "When a file is uploaded", es: "Al subir un archivo" },
];

function triggerLabel(triggerType, lang) {
  const t = TRIGGER_OPTIONS.find(o => o.value === triggerType);
  if (!t) return `#${triggerType}`;
  return lang === "es" ? t.es : t.en;
}

function parseConfig(json) {
  if (!json) return {};
  try { return JSON.parse(json); } catch { return {}; }
}

function AutomationModal({ open, onClose, lang, toast, editing, onSaved }) {
  const isEdit = !!editing;
  const [form, setForm] = React.useState({
    name: "", instructions: "", triggerType: 1, isActive: true,
    folderId: "", namePattern: "",
  });
  const [folders, setFolders] = React.useState([]);
  const [submitting, setSubmitting] = React.useState(false);

  React.useEffect(() => {
    if (!open) return;
    const cfg = parseConfig(editing?.triggerConfigJson);
    setForm({
      name: editing?.name || "",
      instructions: editing?.instructions || "",
      triggerType: editing?.triggerType ?? 1,
      isActive: editing ? !!editing.isActive : true,
      folderId: cfg.folderId || "",
      namePattern: cfg.namePattern || "",
    });
  }, [open, editing]);

  // Load root folders so the user can pick a filter without copy-pasting GUIDs.
  React.useEffect(() => {
    if (!open) return;
    let cancelled = false;
    window.api.storage.contents()
      .then(c => { if (!cancelled) setFolders(c.folders || []); })
      .catch(() => { /* fine — leave folder picker empty */ });
    return () => { cancelled = true; };
  }, [open]);

  const canSubmit = form.name.trim() && form.instructions.trim() && !submitting;

  const handleSave = async () => {
    if (!canSubmit) return;
    setSubmitting(true);
    try {
      const config = {};
      if (form.folderId) config.folderId = form.folderId;
      if (form.namePattern.trim()) config.namePattern = form.namePattern.trim();
      const triggerConfigJson = Object.keys(config).length ? JSON.stringify(config) : null;

      if (isEdit) {
        await window.api.automations.update(editing.id, {
          name: form.name.trim(),
          instructions: form.instructions.trim(),
          triggerType: form.triggerType,
          triggerConfigJson,
        });
        // isActive isn't part of the update endpoint — flip it separately if changed.
        if (!!editing.isActive !== !!form.isActive) {
          await window.api.automations.setActive(editing.id, form.isActive);
        }
        toast(lang === "es" ? "Automatización actualizada" : "Automation updated", "success");
      } else {
        await window.api.automations.create({
          name: form.name.trim(),
          instructions: form.instructions.trim(),
          triggerType: form.triggerType,
          triggerConfigJson,
          isActive: form.isActive,
        });
        toast(lang === "es" ? "Automatización creada" : "Automation created", "success");
      }
      onSaved && onSaved();
      onClose();
    } catch (err) {
      toast(err.message || (lang === "es" ? "No se pudo guardar" : "Could not save"), "danger");
    } finally {
      setSubmitting(false);
    }
  };

  if (!open) return null;

  const folderOptions = [
    { value: "", label: lang === "es" ? "Cualquier carpeta" : "Any folder" },
    ...folders.map(f => ({ value: f.id, label: f.name })),
  ];

  return (
    <window.Modal open={open} onClose={onClose}
      title={isEdit
        ? (lang === "es" ? "Editar automatización" : "Edit automation")
        : (lang === "es" ? "Nueva automatización" : "New automation")}
      subtitle={lang === "es"
        ? "Describe en lenguaje natural lo que la IA debe hacer cuando ocurra el evento."
        : "Describe in plain language what the AI should do when the event happens."}
      width={620}
      footer={
        <>
          <window.Btn variant="ghost" onClick={onClose} disabled={submitting}>
            {lang === "es" ? "Cancelar" : "Cancel"}
          </window.Btn>
          <window.Btn variant="brand" onClick={handleSave} disabled={!canSubmit}>
            {submitting
              ? (lang === "es" ? "Guardando…" : "Saving…")
              : (lang === "es" ? "Guardar" : "Save")}
          </window.Btn>
        </>
      }
    >
      <div style={{ display: "grid", gap: 12 }}>
        <label className="field">
          <span>{lang === "es" ? "Nombre" : "Name"} <i className="req">*</i></span>
          <input className="input" maxLength={120} value={form.name}
            onChange={e => setForm({ ...form, name: e.target.value })}
            placeholder={lang === "es" ? "Ej: Procesar contratos" : "e.g. Process contracts"} />
        </label>

        <div className="field">
          <span>{lang === "es" ? "Disparador" : "Trigger"}</span>
          <window.Select
            value={form.triggerType}
            onChange={v => setForm({ ...form, triggerType: parseInt(v, 10) })}
            options={TRIGGER_OPTIONS.map(o => ({ value: o.value, label: lang === "es" ? o.es : o.en }))}
          />
        </div>

        {form.triggerType === 1 && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <div className="field">
              <span>{lang === "es" ? "Solo en esta carpeta" : "Only in this folder"}</span>
              <window.Select
                value={form.folderId}
                onChange={v => setForm({ ...form, folderId: v })}
                options={folderOptions}
              />
            </div>
            <label className="field">
              <span>{lang === "es" ? "Nombre contiene" : "Name contains"}</span>
              <input className="input" value={form.namePattern}
                onChange={e => setForm({ ...form, namePattern: e.target.value })}
                placeholder={lang === "es" ? "ej: contrato" : "e.g. contract"} />
            </label>
          </div>
        )}

        <label className="field">
          <span>{lang === "es" ? "Instrucciones para la IA" : "Instructions for the AI"} <i className="req">*</i></span>
          <textarea
            className="input"
            rows={6}
            maxLength={4000}
            value={form.instructions}
            onChange={e => setForm({ ...form, instructions: e.target.value })}
            placeholder={lang === "es"
              ? "Ejemplo: Cuando se suba un contrato, crea las tareas relacionadas en el board principal y prepara las facturas correspondientes para el cliente del contrato."
              : "Example: When a contract is uploaded, create the related tasks on the main board and draft the corresponding invoices for the contract's client."}
            style={{ resize: "vertical", minHeight: 120, fontFamily: "inherit", lineHeight: 1.5 }}
          />
          <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 4 }}>
            {form.instructions.length}/4000
          </div>
        </label>

        <div className="field">
          <span>{lang === "es" ? "Estado" : "Status"}</span>
          <window.Select
            value={form.isActive ? "active" : "paused"}
            onChange={v => setForm({ ...form, isActive: v === "active" })}
            options={[
              { value: "active", label: lang === "es" ? "Activa" : "Active" },
              { value: "paused", label: lang === "es" ? "Pausada" : "Paused" },
            ]}
          />
        </div>
      </div>
    </window.Modal>
  );
}

window.AutomationsScreen = function AutomationsScreen({ t, lang, subTab }) {
  const sub = subTab || "all";
  const Icons = window.Icons;
  const toast = window.useToast();

  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [refreshKey, setRefreshKey] = React.useState(0);
  const [showModal, setShowModal] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const refresh = React.useCallback(() => setRefreshKey(k => k + 1), []);

  React.useEffect(() => {
    let cancelled = false;
    setLoading(true);
    window.api.automations.list()
      .then(list => { if (!cancelled) { setItems(list); setError(null); } })
      .catch(err => { if (!cancelled) setError(err.message); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [refreshKey]);

  const filtered = React.useMemo(() => {
    if (sub === "active") return items.filter(i => i.isActive);
    if (sub === "paused") return items.filter(i => !i.isActive);
    return items;
  }, [items, sub]);

  const handleNew = () => { setEditing(null); setShowModal(true); };
  const handleEdit = (item) => { setEditing(item); setShowModal(true); };

  const handleToggle = async (item) => {
    try {
      await window.api.automations.setActive(item.id, !item.isActive);
      toast(
        item.isActive
          ? (lang === "es" ? "Automatización pausada" : "Automation paused")
          : (lang === "es" ? "Automatización activada" : "Automation activated"),
        "success");
      refresh();
    } catch (err) {
      toast(err.message, "danger");
    }
  };

  const handleDelete = async (item) => {
    const ok = window.confirm(lang === "es"
      ? `¿Eliminar "${item.name}"? Esta acción no se puede deshacer.`
      : `Delete "${item.name}"? This cannot be undone.`);
    if (!ok) return;
    try {
      await window.api.automations.delete(item.id);
      toast(lang === "es" ? "Automatización eliminada" : "Automation deleted", "success");
      refresh();
    } catch (err) {
      toast(err.message, "danger");
    }
  };

  return (
    <div className="page">
      <window.PageHeader
        title={lang === "es" ? "Automatizaciones" : "Automations"}
        subtitle={lang === "es"
          ? "Define qué debe hacer la IA cuando ocurre un evento en tu workspace."
          : "Tell the AI what to do when something happens in your workspace."}
        actions={
          <window.Btn variant="brand" icon={Icons.Plus} onClick={handleNew}>
            {lang === "es" ? "Nueva automatización" : "New automation"}
          </window.Btn>
        }
      />

      <window.Toolbar>
        <span style={{ marginLeft: "auto", color: "var(--text-muted)", fontSize: 12 }}>
          {filtered.length} {lang === "es" ? "automatizaciones" : "automations"}
        </span>
      </window.Toolbar>

      <div className="card">
        {loading && items.length === 0 && (
          <div style={{ textAlign: "center", padding: 32, color: "var(--text-muted)" }}>Cargando…</div>
        )}
        {error && (
          <div style={{ textAlign: "center", padding: 32, color: "var(--danger)" }}>{error}</div>
        )}
        {!loading && !error && filtered.length === 0 && (
          <div className="empty" style={{ padding: "60px 24px" }}>
            <div className="empty-icon"><Icons.Brain /></div>
            <h3>{lang === "es" ? "Aún no hay automatizaciones" : "No automations yet"}</h3>
            <p>{lang === "es"
              ? "Crea tu primera automatización para que la IA actúe por ti cuando ocurra un evento."
              : "Create your first automation so the AI can act for you when an event happens."}
            </p>
          </div>
        )}
        {!loading && !error && filtered.length > 0 && (
          <table className="tbl">
            <thead>
              <tr>
                <th style={{ width: "30%" }}>{lang === "es" ? "Nombre" : "Name"}</th>
                <th>{lang === "es" ? "Disparador" : "Trigger"}</th>
                <th>{lang === "es" ? "Estado" : "Status"}</th>
                <th>{lang === "es" ? "Actualizada" : "Updated"}</th>
                <th style={{ width: 120 }}></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(a => (
                <tr key={a.id}
                  style={{ opacity: a.isActive ? 1 : 0.6, cursor: "pointer" }}
                  onDoubleClick={() => handleEdit(a)}
                  title={lang === "es" ? "Doble click para editar" : "Double click to edit"}
                >
                  <td>
                    <div style={{ fontWeight: 500 }}>{a.name}</div>
                    <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 2, maxWidth: 360, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                      {a.instructions}
                    </div>
                  </td>
                  <td>{triggerLabel(a.triggerType, lang)}</td>
                  <td>
                    <window.Badge tone={a.isActive ? "success" : "neutral"}>
                      {a.isActive
                        ? (lang === "es" ? "Activa" : "Active")
                        : (lang === "es" ? "Pausada" : "Paused")}
                    </window.Badge>
                  </td>
                  <td className="mono" style={{ fontSize: 11, color: "var(--text-muted)" }}>
                    {new Date(a.updatedAt).toLocaleString(lang === "es" ? "es-ES" : "en-US")}
                  </td>
                  <td>
                    <div style={{ display: "flex", gap: 6, justifyContent: "flex-end" }} onClick={e => e.stopPropagation()}>
                      <button className="icon-btn" title={a.isActive
                        ? (lang === "es" ? "Pausar" : "Pause")
                        : (lang === "es" ? "Activar" : "Activate")}
                        onClick={() => handleToggle(a)}>
                        {a.isActive ? <Icons.Clock /> : <Icons.Zap />}
                      </button>
                      <button className="icon-btn" title={lang === "es" ? "Editar" : "Edit"}
                        onClick={() => handleEdit(a)}>
                        <Icons.Edit />
                      </button>
                      <button className="icon-btn" title={lang === "es" ? "Eliminar" : "Delete"}
                        onClick={() => handleDelete(a)}>
                        <Icons.X />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <AutomationModal
        open={showModal}
        onClose={() => setShowModal(false)}
        lang={lang}
        toast={toast}
        editing={editing}
        onSaved={refresh}
      />
    </div>
  );
};

Object.assign(window, { AutomationsScreen: window.AutomationsScreen });
