import { useEffect, useState } from "react";

import OmsorgButton from "../../components/ui/OmsorgButton";

export const emptyEmployeeFacilityDistanceForm = {
  employeeId: "",
  distanceKm: "",
};

export function employeeFacilityDistanceToFormValues(distance) {
  return {
    employeeId: distance.employeeId ?? "",
    distanceKm: typeof distance.distanceKm === "number" ? String(distance.distanceKm) : "",
  };
}

export function employeeFacilityDistanceFormToPayload(form, { includeEmployeeId = false } = {}) {
  const payload = {
    distanceKm: Number(form.distanceKm) || 0,
  };

  if (includeEmployeeId) {
    payload.employeeId = form.employeeId;
  }

  return payload;
}

export default function EmployeeFacilityDistanceForm({ form, onChange, includeEmployeeSelect = false }) {
  const [employees, setEmployees] = useState([]);

  useEffect(() => {
    if (!includeEmployeeSelect) return;

    let cancelled = false;
    window.omsorg.employees.list({ pageSize: 500 }).then((result) => {
      if (!cancelled && result.ok) {
        setEmployees(result.data?.items ?? []);
      }
    });

    return () => {
      cancelled = true;
    };
  }, [includeEmployeeSelect]);

  function updateField(field) {
    return (event) => onChange({ ...form, [field]: event.target.value });
  }

  return (
    <div className="form-grid">
      {includeEmployeeSelect && (
        <label className="form-field">
          <span>Mitarbeiter *</span>
          <select value={form.employeeId} onChange={updateField("employeeId")} required>
            <option value="">— auswählen —</option>
            {employees.map((employee) => (
              <option key={employee.id} value={employee.id}>
                {employee.firstName} {employee.lastName}
              </option>
            ))}
          </select>
        </label>
      )}

      <label className="form-field">
        <span>Entfernung (km, einfache Strecke) *</span>
        <input type="number" step="0.1" min="0" value={form.distanceKm} onChange={updateField("distanceKm")} required />
      </label>
    </div>
  );
}

export function FormActions({ onCancel, isSaving, submitLabel }) {
  return (
    <div className="form-actions">
      <OmsorgButton variant="secondary" type="button" onClick={onCancel} disabled={isSaving}>
        Abbrechen
      </OmsorgButton>
      <OmsorgButton type="submit" disabled={isSaving}>
        {isSaving ? "Speichert..." : submitLabel}
      </OmsorgButton>
    </div>
  );
}
