import { useEffect, useState } from "react";

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

export const emptyTimeEntryForm = {
  orderId: "",
  date: "",
  start: "",
  end: "",
  breakMinutes: 0,
  nightHours: 0,
  saturdayHours: 0,
  sundayHours: 0,
  holidayHours: 0,
};

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);
}

// TimeEntry.BreakDuration kommt vom generierten API-Client als "HH:mm:ss"-String (TimeSpan) -
// das Formular arbeitet mit Minuten als Zahl, weil das für die Eingabe praktikabler ist.
function breakDurationToMinutes(value) {
  if (!value) {
    return 0;
  }
  const [hours, minutes] = value.split(":").map(Number);
  return (hours || 0) * 60 + (minutes || 0);
}

function minutesToBreakDuration(minutes) {
  const total = Number(minutes) || 0;
  const hours = Math.floor(total / 60);
  const rest = total % 60;
  return `${String(hours).padStart(2, "0")}:${String(rest).padStart(2, "0")}:00`;
}

export function timeEntryToFormValues(timeEntry) {
  return {
    orderId: timeEntry.orderId ?? "",
    date: toDateInputValue(timeEntry.date),
    start: timeEntry.start?.slice(0, 5) ?? "",
    end: timeEntry.end?.slice(0, 5) ?? "",
    breakMinutes: breakDurationToMinutes(timeEntry.breakDuration),
    nightHours: timeEntry.nightHours ?? 0,
    saturdayHours: timeEntry.saturdayHours ?? 0,
    sundayHours: timeEntry.sundayHours ?? 0,
    holidayHours: timeEntry.holidayHours ?? 0,
  };
}

export function timeEntryFormToPayload(form) {
  return {
    orderId: form.orderId,
    date: form.date,
    start: `${form.start}:00`,
    end: `${form.end}:00`,
    breakDuration: minutesToBreakDuration(form.breakMinutes),
    nightHours: Number(form.nightHours) || 0,
    saturdayHours: Number(form.saturdayHours) || 0,
    sundayHours: Number(form.sundayHours) || 0,
    holidayHours: Number(form.holidayHours) || 0,
  };
}

export default function TimeEntryForm({ form, onChange }) {
  const [orders, setOrders] = useState([]);
  const [facilities, setFacilities] = useState([]);

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

    Promise.all([
      window.omsorg.orders.list({ pageSize: 200 }),
      window.omsorg.facilities.list({ pageSize: 200 }),
    ]).then(([ordersResult, facilitiesResult]) => {
      if (!cancelled) {
        setOrders(ordersResult.ok ? ordersResult.data?.items ?? [] : []);
        setFacilities(facilitiesResult.ok ? facilitiesResult.data?.items ?? [] : []);
      }
    });

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

  const facilityNameById = new Map(facilities.map((facility) => [facility.id, facility.name]));

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

  return (
    <div className="form-grid">
      <label className="form-field">
        <span>Auftrag *</span>
        <select value={form.orderId} onChange={updateField("orderId")} required>
          <option value="">— auswählen —</option>
          {orders.map((order) => (
            <option key={order.id} value={order.id}>
              Auftrag {order.id.slice(0, 8)} — {facilityNameById.get(order.facilityId) ?? "—"}
            </option>
          ))}
        </select>
      </label>

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

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

        <label className="form-field">
          <span>Ende *</span>
          <input type="time" value={form.end} onChange={updateField("end")} required />
        </label>
      </div>

      <label className="form-field">
        <span>Pause (Minuten)</span>
        <input type="number" min="0" value={form.breakMinutes} onChange={updateField("breakMinutes")} />
      </label>

      <div className="form-row">
        <label className="form-field">
          <span>Nachtstunden</span>
          <input type="number" min="0" step="0.25" value={form.nightHours} onChange={updateField("nightHours")} />
        </label>

        <label className="form-field">
          <span>Samstagsstunden</span>
          <input type="number" min="0" step="0.25" value={form.saturdayHours} onChange={updateField("saturdayHours")} />
        </label>
      </div>

      <div className="form-row">
        <label className="form-field">
          <span>Sonntagsstunden</span>
          <input type="number" min="0" step="0.25" value={form.sundayHours} onChange={updateField("sundayHours")} />
        </label>

        <label className="form-field">
          <span>Feiertagsstunden</span>
          <input type="number" min="0" step="0.25" value={form.holidayHours} onChange={updateField("holidayHours")} />
        </label>
      </div>
    </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>
  );
}
