import { useEffect, useState } from "react";

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

const CONFLICT_LABELS = {
  Qualification: "Qualifikation",
  Absence: "Abwesenheit",
  WorkingHours: "Arbeitszeit",
  Overlap: "Überschneidung",
  Contract: "Vertrag"
};

function conflictLabel(conflict) {
  return `${CONFLICT_LABELS[conflict.type] ?? conflict.type}: ${conflict.message}`;
}

function errorMessage(result) {
  if (result.status === 403) {
    return "Keine Berechtigung, Zuweisungen zu erstellen.";
  }
  if (result.status === 404) {
    return typeof result.data === "string" ? result.data : "Mitarbeiter oder Auftrag nicht gefunden.";
  }
  if (result.status === 400) {
    const msg = typeof result.data === "string" ? result.data : result.data?.error;
    if (msg === "invalid_date_range") {
      return "Das Enddatum muss nach oder gleich dem Startdatum sein.";
    }
    if (msg === "date_outside_order_range") {
      return "Der Zeitraum liegt außerhalb der Auftragsspanne.";
    }
    return msg || "Eingaben prüfen.";
  }
  if (result.status === 409) {
    const msg = typeof result.data === "string" ? result.data : result.data?.error;
    if (msg === "overlapping_assignment") {
      return "Dieser Mitarbeiter ist bereits in diesem Zeitraum diesem Auftrag zugewiesen.";
    }
    if (msg === "validation_conflict") {
      const conflicts = result.data?.conflicts ?? [];
      return conflicts.length > 0
        ? conflicts.map(conflictLabel).join(" | ")
        : "Zuweisung durch eine Konfliktprüfung blockiert.";
    }
    return "Zeitraum-Konflikt: Überprüfe die Verfügbarkeit.";
  }
  return "Zuweisung konnte nicht erstellt werden.";
}

export default function CreateAssignmentDialog({ orderId, order, onClose, onCreated }) {
  const [employees, setEmployees] = useState([]);
  const [selectedEmployeeId, setSelectedEmployeeId] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [note, setNote] = useState("");
  const [error, setError] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isLoadingEmployees, setIsLoadingEmployees] = useState(true);
  const [liveConflicts, setLiveConflicts] = useState([]);
  const [isChecking, setIsChecking] = useState(false);

  useEffect(() => {
    async function loadEmployees() {
      const result = await window.omsorg.employees.list({ status: "Aktiv", pageSize: 200 });
      if (result.ok) {
        setEmployees(result.data?.items ?? []);
      }
      setIsLoadingEmployees(false);
    }
    loadEmployees();
  }, []);

  // Live-Vorschau: sobald Mitarbeiter + gültiger Zeitraum feststehen, dieselben FR-EM-3-Prüfungen
  // wie beim Speichern laufen lassen (debounced), damit Warnings/Errors schon vor dem Klick auf
  // "Speichern" sichtbar sind, nicht erst danach.
  useEffect(() => {
    setError("");

    if (!selectedEmployeeId || !startDate || !endDate || endDate < startDate) {
      setLiveConflicts([]);
      return;
    }

    let cancelled = false;
    setIsChecking(true);
    const timer = setTimeout(async () => {
      const result = await window.omsorg.assignments.checkConflicts({
        orderId,
        employeeId: selectedEmployeeId,
        startDate,
        endDate
      });
      if (!cancelled) {
        setLiveConflicts(result.ok ? result.data ?? [] : []);
        setIsChecking(false);
      }
    }, 400);

    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [orderId, selectedEmployeeId, startDate, endDate]);

  const hasBlockingConflict = liveConflicts.some((c) => c.severity === "Error");

  const orderStartDate = order?.startDate ? new Date(order.startDate).toISOString().split("T")[0] : "";
  const orderEndDate = order?.endDate ? new Date(order.endDate).toISOString().split("T")[0] : "";

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");

    if (!selectedEmployeeId) {
      setError("Bitte wähle einen Mitarbeiter.");
      return;
    }
    if (!startDate) {
      setError("Bitte wähle ein Startdatum.");
      return;
    }
    if (!endDate) {
      setError("Bitte wähle ein Enddatum.");
      return;
    }
    if (endDate < startDate) {
      setError("Das Enddatum muss nach oder gleich dem Startdatum sein.");
      return;
    }

    setIsSubmitting(true);
    const result = await window.omsorg.assignments.create({
      orderId,
      employeeId: selectedEmployeeId,
      startDate,
      endDate,
      note: note || null
    });

    if (result.ok) {
      onCreated(result.data?.conflicts ?? []);
    } else {
      setError(errorMessage(result));
    }
    setIsSubmitting(false);
  };

  return (
    <ModalPortal>
      <div className="modal-overlay" role="dialog" aria-modal="true" aria-label="Zuweisung hinzufügen">
        <div className="modal-panel">
          <h2>Zuweisung hinzufügen</h2>

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

            <div className="form-group">
              <label htmlFor="employee-select">Mitarbeiter *</label>
              <select
                id="employee-select"
                value={selectedEmployeeId}
                onChange={(e) => setSelectedEmployeeId(e.target.value)}
                disabled={isLoadingEmployees || isSubmitting}
                required
              >
                <option value="">— Bitte wähle einen Mitarbeiter —</option>
                {employees.map((emp) => (
                  <option key={emp.id} value={emp.id}>
                    {emp.firstName} {emp.lastName}
                  </option>
                ))}
              </select>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1rem" }}>
              <div className="form-group">
                <label htmlFor="start-date">Startdatum *</label>
                <input
                  id="start-date"
                  type="date"
                  value={startDate}
                  onChange={(e) => {
                    setStartDate(e.target.value);
                    if (endDate && e.target.value > endDate) {
                      setEndDate(e.target.value);
                    }
                  }}
                  min={orderStartDate}
                  max={orderEndDate || undefined}
                  disabled={isSubmitting}
                  required
                />
              </div>

              <div className="form-group">
                <label htmlFor="end-date">Enddatum *</label>
                <input
                  id="end-date"
                  type="date"
                  value={endDate}
                  onChange={(e) => setEndDate(e.target.value)}
                  min={startDate || orderStartDate}
                  max={orderEndDate || undefined}
                  disabled={isSubmitting}
                  required
                />
              </div>
            </div>

            {isChecking && <p style={{ color: "var(--omsorg-text-secondary)", fontSize: "0.85rem" }}>Prüfe Konflikte...</p>}

            {!isChecking && liveConflicts.length > 0 && (
              <div className={hasBlockingConflict ? "assignment-conflicts assignment-conflicts--error" : "assignment-conflicts assignment-conflicts--warning"}>
                {liveConflicts.map((c, i) => (
                  <p key={i}>
                    {c.severity === "Error" ? "⛔" : "⚠"} {CONFLICT_LABELS[c.type] ?? c.type}: {c.message}
                  </p>
                ))}
              </div>
            )}

            <div className="form-group">
              <label htmlFor="note">Notiz (optional)</label>
              <textarea
                id="note"
                value={note}
                onChange={(e) => setNote(e.target.value)}
                placeholder="z.B. Springer, spezielle Anforderungen..."
                disabled={isSubmitting}
                rows={3}
              />
            </div>

            <div style={{ display: "flex", gap: "0.75rem", justifyContent: "flex-end", marginTop: "1.5rem" }}>
              <button
                type="button"
                onClick={onClose}
                disabled={isSubmitting}
                className="button-link"
              >
                Abbrechen
              </button>
              <OmsorgButton type="submit" variant="primary" disabled={isSubmitting || hasBlockingConflict}>
                {isSubmitting ? "Wird gespeichert..." : "Speichern"}
              </OmsorgButton>
            </div>
          </form>
        </div>

        <style>{`
          .assignment-conflicts {
            border-radius: 4px;
            padding: 0.75rem;
            margin: 0.5rem 0 1rem 0;
          }

          .assignment-conflicts p {
            margin: 0.25rem 0;
            font-size: 0.9rem;
          }

          .assignment-conflicts--warning {
            background-color: rgba(240, 195, 109, 0.12);
            border: 1px solid rgba(240, 195, 109, 0.45);
            color: #f0c36d;
          }

          .assignment-conflicts--error {
            background-color: rgba(242, 139, 139, 0.12);
            border: 1px solid rgba(242, 139, 139, 0.45);
            color: #f28b8b;
          }
        `}</style>
      </div>
    </ModalPortal>
  );
}
