import { useEffect, useState } from "react";

import OmsorgButton from "../../components/ui/OmsorgButton";
import { useValueListItems } from "../../app/useValueListItems";

export const emptyOrderForm = {
  facilityId: "",
  facilityContactId: "",
  startDate: "",
  endDate: "",
  requiredQualification: "",
  shiftType: "",
  requiredHeadcount: 1,
  conditions: "",
  priority: "",
  statusId: "",
};

// order.startDate/endDate kommen vom generierten API-Client als echte Date-Objekte
// (nicht als "YYYY-MM-DD"-String) - <input type="date"> akzeptiert aber nur diesen
// exakten Stringformat, sonst bleibt/wird das Feld unparsbar.
function toDateInputValue(value) {
  if (!value) {
    return "";
  }
  const date = value instanceof Date ? value : new Date(value);
  return Number.isNaN(date.getTime()) ? "" : date.toISOString().slice(0, 10);
}

export function orderToFormValues(order) {
  return {
    facilityId: order.facilityId ?? "",
    facilityContactId: order.facilityContactId ?? "",
    startDate: toDateInputValue(order.startDate),
    endDate: toDateInputValue(order.endDate),
    requiredQualification: order.requiredQualification ?? "",
    shiftType: order.shiftType ?? "",
    requiredHeadcount: order.requiredHeadcount ?? 1,
    conditions: order.conditions ?? "",
    priority: order.priority ?? "",
    statusId: order.statusId ?? "",
  };
}

export function orderFormToPayload(form, { includeStatus = false } = {}) {
  const payload = {
    facilityId: form.facilityId,
    facilityContactId: form.facilityContactId || null,
    startDate: form.startDate,
    endDate: form.endDate || null,
    requiredQualification: form.requiredQualification.trim() || null,
    shiftType: form.shiftType.trim() || null,
    requiredHeadcount: Number(form.requiredHeadcount) || 1,
    conditions: form.conditions.trim() || null,
    priority: form.priority.trim(),
  };

  if (includeStatus) {
    payload.statusId = form.statusId;
  }

  return payload;
}

export default function OrderForm({ form, onChange, facilities, includeStatus = false }) {
  const [contacts, setContacts] = useState([]);
  const { items: statusItems } = useValueListItems("OrderStatus");
  const { items: qualifications } = useValueListItems("Qualification");
  const { items: shiftTypes } = useValueListItems("ShiftType");
  const { items: priorities } = useValueListItems("Priority");
  const [transitions, setTransitions] = useState(null);

  useEffect(() => {
    let cancelled = false;

    if (!form.facilityId) {
      setContacts([]);
      return undefined;
    }

    window.omsorg.facilityContacts.list(form.facilityId).then((result) => {
      if (!cancelled) {
        setContacts(result.ok ? result.data ?? [] : []);
      }
    });

    return () => {
      cancelled = true;
    };
  }, [form.facilityId]);

  useEffect(() => {
    if (!includeStatus) {
      return;
    }
    let cancelled = false;

    window.omsorg.valueLists.listTransitions("OrderStatus").then((result) => {
      if (!cancelled) {
        setTransitions(result.ok ? result.data ?? [] : []);
      }
    });

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

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

  function handleFacilityChange(event) {
    onChange({ ...form, facilityId: event.target.value, facilityContactId: "" });
  }

  const statusOptions =
    transitions === null
      ? statusItems.filter((item) => item.id === form.statusId)
      : statusItems.filter(
          (item) =>
            item.id === form.statusId ||
            transitions.some((t) => t.fromItemId === form.statusId && t.toItemId === item.id)
        );

  return (
    <div className="form-grid">
      <label className="form-field">
        <span>Einrichtung *</span>
        <select value={form.facilityId} onChange={handleFacilityChange} required>
          <option value="">— auswählen —</option>
          {facilities.map((facility) => (
            <option key={facility.id} value={facility.id}>
              {facility.name}
            </option>
          ))}
        </select>
      </label>

      <label className="form-field">
        <span>Ansprechpartner</span>
        <select value={form.facilityContactId} onChange={updateField("facilityContactId")} disabled={!form.facilityId}>
          <option value="">— kein Ansprechpartner —</option>
          {contacts.map((contact) => (
            <option key={contact.id} value={contact.id}>
              {contact.name}
            </option>
          ))}
        </select>
      </label>

      <div className="form-row">
        <label className="form-field">
          <span>Beginn *</span>
          <input type="date" value={form.startDate} onChange={updateField("startDate")} required />
        </label>

        <label className="form-field">
          <span>Ende</span>
          <input type="date" value={form.endDate} onChange={updateField("endDate")} />
        </label>
      </div>

      <label className="form-field">
        <span>Benötigte Qualifikation</span>
        <select value={form.requiredQualification} onChange={updateField("requiredQualification")}>
          <option value="">— nicht angegeben —</option>
          {qualifications.map((option) => (
            <option key={option.id} value={option.value}>
              {option.value}
            </option>
          ))}
        </select>
      </label>

      <label className="form-field">
        <span>Schichtart</span>
        <select value={form.shiftType} onChange={updateField("shiftType")}>
          <option value="">— nicht angegeben —</option>
          {shiftTypes.map((option) => (
            <option key={option.id} value={option.value}>
              {option.value}
            </option>
          ))}
        </select>
      </label>

      <label className="form-field">
        <span>Anzahl benötigter Mitarbeiter *</span>
        <input
          type="number"
          min="1"
          value={form.requiredHeadcount}
          onChange={updateField("requiredHeadcount")}
          required
        />
      </label>

      <label className="form-field">
        <span>Priorität *</span>
        <select value={form.priority} onChange={updateField("priority")} required>
          <option value="">— auswählen —</option>
          {priorities.map((option) => (
            <option key={option.id} value={option.value}>
              {option.value}
            </option>
          ))}
        </select>
      </label>

      <label className="form-field">
        <span>Konditionen</span>
        <textarea value={form.conditions} onChange={updateField("conditions")} maxLength={500} />
      </label>

      {includeStatus && (
        <label className="form-field">
          <span>Status</span>
          <select value={form.statusId} onChange={updateField("statusId")}>
            {statusOptions.map((option) => (
              <option key={option.id} value={option.id}>
                {option.value}
              </option>
            ))}
          </select>
        </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>
  );
}
