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 hochzuladen.";
  }
  if (result.status === 400) {
    return typeof result.data === "string" ? result.data : "Eingaben prüfen.";
  }
  return "Dokument konnte nicht hochgeladen werden.";
}

export default function UploadDocumentDialog({ employeeId, onClose, onUploaded }) {
  const { items: categories } = useValueListItems("DocumentCategory");
  const [category, setCategory] = useState("");
  const [description, setDescription] = useState("");
  const [file, setFile] = useState(null);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState(null);

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

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

    if (!file) {
      setError("Datei ist erforderlich.");
      return;
    }

    setIsSaving(true);
    setError(null);

    const data = await file.arrayBuffer();
    const result = await window.omsorg.documents.upload({
      entityType: "Employee",
      entityId: employeeId,
      category,
      description: description.trim() || null,
      fileName: file.name,
      contentType: file.type,
      data,
    });

    setIsSaving(false);

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

    onUploaded(result.data);
  }

  return (
    <ModalPortal>
      <div className="modal-overlay" role="dialog" aria-modal="true" aria-label="Dokument hochladen">
        <div className="modal-panel">
          <h2>Dokument hochladen</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>Datei *</span>
                <input type="file" onChange={(event) => setFile(event.target.files?.[0] ?? null)} 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="Hochladen" />
          </form>
        </div>
      </div>
    </ModalPortal>
  );
}
