import { useState } from "react";

import EmployeeFacilityDistanceForm, {
  emptyEmployeeFacilityDistanceForm,
  employeeFacilityDistanceFormToPayload,
  FormActions,
} from "./EmployeeFacilityDistanceForm";
import ModalPortal from "../../components/ui/ModalPortal";

function errorMessage(result) {
  if (result.status === 403) {
    return "Keine Berechtigung, Entfernungen anzulegen.";
  }
  if (result.status === 400) {
    return typeof result.data === "string" ? result.data : "Eingaben prüfen.";
  }
  return "Entfernung konnte nicht angelegt werden.";
}

export default function CreateEmployeeFacilityDistanceDialog({ facilityId, onClose, onCreated }) {
  const [form, setForm] = useState(emptyEmployeeFacilityDistanceForm);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState(null);

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

    if (!form.employeeId) {
      setError("Mitarbeiter ist erforderlich.");
      return;
    }

    setIsSaving(true);
    setError(null);

    const result = await window.omsorg.employeeFacilityDistances.create(
      facilityId,
      employeeFacilityDistanceFormToPayload(form, { includeEmployeeId: true })
    );

    setIsSaving(false);

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

    onCreated(result.data);
  }

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

          <form onSubmit={handleSubmit}>
            <EmployeeFacilityDistanceForm form={form} onChange={setForm} includeEmployeeSelect />

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

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