import { useState } from "react";

import FacilityQualificationRateForm, {
  facilityQualificationRateFormToPayload,
  facilityQualificationRateToFormValues,
  FormActions,
} from "./FacilityQualificationRateForm";
import ModalPortal from "../../components/ui/ModalPortal";

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

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

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

    if (!form.qualification) {
      setError("Qualifikation ist erforderlich.");
      return;
    }

    setIsSaving(true);
    setError(null);

    const payload = facilityQualificationRateFormToPayload(form);
    const result = await window.omsorg.facilityQualificationRates.update(facilityId, rate.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="Qualifikationspreis bearbeiten">
        <div className="modal-panel">
          <h2>{rate.qualification} bearbeiten</h2>

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

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

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