import { useState } from "react";

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

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

export default function EditEmployeeFacilityDistanceDialog({ facilityId, distance, onClose, onUpdated }) {
  const [form, setForm] = useState(() => employeeFacilityDistanceToFormValues(distance));
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState(null);

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

    setIsSaving(true);
    setError(null);

    const payload = employeeFacilityDistanceFormToPayload(form);
    const result = await window.omsorg.employeeFacilityDistances.update(facilityId, distance.id, payload);

    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="Entfernung bearbeiten">
        <div className="modal-panel">
          <h2>
            {distance.employeeFirstName} {distance.employeeLastName} bearbeiten
          </h2>

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

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

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