import { useState } from "react";

import ModalPortal from "../../components/ui/ModalPortal";
import { useValueListItems } from "../../app/useValueListItems";
import { FormActions } from "./ContractForm";

function errorMessage(result) {
  if (result.status === 403) {
    return "Keine Berechtigung, Dokumente zu bearbeiten.";
  }
  if (result.status === 400) {
    return typeof result.data === "string" ? result.data : "Eingaben prüfen.";
  }
  return "Dokument konnte nicht gespeichert werden.";
}

export default function EditDocumentDialog({ doc, onClose, onUpdated }) {
  const { items: categories } = useValueListItems("DocumentCategory");
  const [category, setCategory] = useState(doc.category ?? "");
  const [description, setDescription] = useState(doc.description ?? "");
  const [fileName, setFileName] = useState(doc.fileName ?? "");
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState(null);

  async function handleSubmit(event) {
    event.preventDefault();

    if (!category) {
      setError("Kategorie ist erforderlich.");
      return;
    }

    if (!fileName.trim()) {
      setError("Dateiname ist erforderlich.");
      return;
    }

    setIsSaving(true);
    setError(null);

    const result = await window.omsorg.documents.update(doc.id, {
      category,
      description: description.trim() || null,
      fileName: fileName.trim(),
    });

    setIsSaving(false);

    if (!result.ok) {
      setError(errorMessage(result));
      return;
    }

    onUpdated(result.data);
  }

  return (
    <ModalPortal>
      <div className="modal-overlay" role="dialog" aria-modal="true" aria-label="Dokument bearbeiten">
        <div className="modal-panel">
          <h2>Dokument bearbeiten</h2>

          <form onSubmit={handleSubmit}>
            <div className="form-grid">
              <label className="form-field">
                <span>Kategorie *</span>
                <select value={category} onChange={(event) => setCategory(event.target.value)} required>
                  <option value="">— auswählen —</option>
                  {categories.map((option) => (
                    <option key={option.id} value={option.value}>
                      {option.value}
                    </option>
                  ))}
                </select>
              </label>

              <label className="form-field">
                <span>Dateiname *</span>
                <input value={fileName} onChange={(event) => setFileName(event.target.value)} required />
              </label>

              <label className="form-field">
                <span>Beschreibung</span>
                <textarea value={description} onChange={(event) => setDescription(event.target.value)} />
              </label>
            </div>

            {error && <p className="login-error form-error">{error}</p>}

            <FormActions onCancel={onClose} isSaving={isSaving} submitLabel="Speichern" />
          </form>
        </div>
      </div>
    </ModalPortal>
  );
}
