import { useState } from "react";

import FacilityForm, { facilityFormToPayload, facilityToFormValues, FormActions } from "./FacilityForm";
import FollowUpDaysDialog from "./FollowUpDaysDialog";
import ModalPortal from "../../components/ui/ModalPortal";
import { useValueListItems } from "../../app/useValueListItems";

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

export default function EditFacilityDialog({ facility, onClose, onUpdated }) {
  const { items: crmStatusOptions } = useValueListItems("CrmStatus");
  const [form, setForm] = useState(() => facilityToFormValues(facility));
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState(null);
  const [isFollowUpDialogOpen, setIsFollowUpDialogOpen] = useState(false);

  async function save(followUpDays) {
    setIsSaving(true);
    setError(null);

    const payload = facilityFormToPayload(form, { followUpDays });
    const result = await window.omsorg.facilities.update(facility.id, payload);

    setIsSaving(false);

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

    onUpdated(result.data);
  }

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

    if (!form.name.trim()) {
      setError("Name ist erforderlich.");
      return;
    }

    const selectedCrmStatus = crmStatusOptions.find((option) => option.value === form.crmStatus);
    const entersFollowUpTriggerStatus = Boolean(selectedCrmStatus?.triggersFollowUp) && facility.crmStatus !== form.crmStatus;
    if (entersFollowUpTriggerStatus) {
      setIsFollowUpDialogOpen(true);
      return;
    }

    await save(null);
  }

  return (
    <ModalPortal>
      <div className="modal-overlay" role="dialog" aria-modal="true" aria-label="Einrichtung bearbeiten">
        <div className="modal-panel">
          <h2>{facility.name} bearbeiten</h2>

          <form onSubmit={handleSubmit}>
            <FacilityForm form={form} onChange={setForm} currentCrmStatus={facility.crmStatus} />

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

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

      {isFollowUpDialogOpen && (
        <FollowUpDaysDialog
          onCancel={() => setIsFollowUpDialogOpen(false)}
          onConfirm={(followUpDays) => {
            setIsFollowUpDialogOpen(false);
            save(followUpDays);
          }}
        />
      )}
    </ModalPortal>
  );
}
