import { useState } from "react";

import EmployeeForm, { employeeFormToPayload, employeeToFormValues, FormActions } from "./EmployeeForm";
import ModalPortal from "../../components/ui/ModalPortal";

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

export default function EditEmployeeDialog({ employee, onClose, onUpdated }) {
  const [form, setForm] = useState(() => employeeToFormValues(employee));
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState(null);

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

    if (!form.firstName.trim() || !form.lastName.trim()) {
      setError("Vorname und Nachname sind erforderlich.");
      return;
    }

    setIsSaving(true);
    setError(null);

    const payload = employeeFormToPayload(form, { includeStatus: true });
    const result = await window.omsorg.employees.update(employee.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="Mitarbeiter bearbeiten">
        <div className="modal-panel">
          <h2>{`${employee.firstName} ${employee.lastName}`.trim()} bearbeiten</h2>

          <form onSubmit={handleSubmit}>
            <EmployeeForm form={form} onChange={setForm} includeStatus />

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

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