import React, { useState } from "react";
import api from "../../../services/api.js";

const initial = {
  title: "",
  doc_type: "SWI",
  contract_ref: "",
  activity_code: "",
  review_cycle_months: 12,
  body_text: "",
};

/**
 * @param {{ open: boolean, onClose: () => void, onCreated: () => void }} props
 */
const NewDocumentModal = ({ open, onClose, onCreated }) => {
  const [form, setForm] = useState(initial);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  if (!open) return null;

  const submit = async (e) => {
    e.preventDefault();
    setError("");
    setSaving(true);
    try {
      await api.post("/swi/documents", {
        ...form,
        review_cycle_months: Number(form.review_cycle_months) || 12,
      });
      setForm(initial);
      onCreated();
      onClose();
    } catch (err) {
      setError(err.response?.data?.error || err.message || "Save failed");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="swi-modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="swi-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="new-swi-title"
        onClick={(ev) => ev.stopPropagation()}
      >
        <h3 id="new-swi-title">New SWI / SOP</h3>
        {error ? <div className="swi-error">{error}</div> : null}
        <form onSubmit={submit}>
          <div className="swi-form-row">
            <label htmlFor="title">Title</label>
            <input
              id="title"
              className="swi-input"
              value={form.title}
              onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))}
              required
            />
          </div>
          <div className="swi-form-row">
            <label htmlFor="doc_type">Type</label>
            <select
              id="doc_type"
              className="swi-select"
              value={form.doc_type}
              onChange={(e) =>
                setForm((f) => ({ ...f, doc_type: e.target.value }))
              }
            >
              <option value="SWI">SWI (Standard Work Instruction)</option>
              <option value="SOP">SOP (Standard Operating Procedure)</option>
            </select>
          </div>
          <div className="swi-form-row">
            <label htmlFor="contract_ref">Contract ref</label>
            <input
              id="contract_ref"
              className="swi-input"
              value={form.contract_ref}
              onChange={(e) =>
                setForm((f) => ({ ...f, contract_ref: e.target.value }))
              }
            />
          </div>
          <div className="swi-form-row">
            <label htmlFor="activity_code">Activity code</label>
            <input
              id="activity_code"
              className="swi-input"
              value={form.activity_code}
              onChange={(e) =>
                setForm((f) => ({ ...f, activity_code: e.target.value }))
              }
            />
          </div>
          <div className="swi-form-row">
            <label htmlFor="review_cycle_months">Review cycle (months)</label>
            <input
              id="review_cycle_months"
              type="number"
              min={1}
              className="swi-input"
              value={form.review_cycle_months}
              onChange={(e) =>
                setForm((f) => ({
                  ...f,
                  review_cycle_months: e.target.value,
                }))
              }
            />
          </div>
          <div className="swi-form-row">
            <label htmlFor="body_text">Content (plain text for now)</label>
            <textarea
              id="body_text"
              className="swi-textarea"
              value={form.body_text}
              onChange={(e) =>
                setForm((f) => ({ ...f, body_text: e.target.value }))
              }
            />
          </div>
          <div className="swi-modal-actions">
            <button type="button" className="swi-btn swi-btn--ghost" onClick={onClose}>
              Cancel
            </button>
            <button type="submit" className="swi-btn swi-btn--primary" disabled={saving}>
              {saving ? "Saving…" : "Create & route approvals"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default NewDocumentModal;
