import { useCallback, useEffect, useState } from "react";
import { Save } from "lucide-react";
import OmsorgButton from "../../components/ui/OmsorgButton";
import { useAuth } from "../../app/AuthContext";

const CHECKS = [
  { key: "qualificationMode", label: "Qualifikation" },
  { key: "absenceMode", label: "Abwesenheit (Verfügbarkeit)" },
  { key: "workingHoursMode", label: "Arbeitszeit" },
  { key: "overlapMode", label: "Überschneidung" },
  { key: "contractMode", label: "Vertrag" }
];

export default function AssignmentValidationSettingsPanel() {
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("Configuration", "Edit");

  const [settings, setSettings] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState(null);
  const [saved, setSaved] = useState(false);

  const load = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    const result = await window.omsorg.assignmentValidationSettings.get();
    if (result.ok) {
      setSettings(result.data);
    } else {
      setError("Einstellungen konnten nicht geladen werden.");
    }
    setIsLoading(false);
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  function handleChange(key, value) {
    setSaved(false);
    setSettings((current) => ({ ...current, [key]: value }));
  }

  async function handleSave() {
    setIsSaving(true);
    setError(null);
    setSaved(false);
    const result = await window.omsorg.assignmentValidationSettings.update(settings);
    if (result.ok) {
      setSettings(result.data);
      setSaved(true);
    } else {
      setError("Speichern fehlgeschlagen.");
    }
    setIsSaving(false);
  }

  return (
    <div className="settings-roles-panel">
      <div className="settings-panel-heading">
        <h4>Zuweisungsprüfung (FR-EM-3)</h4>
      </div>
      <p style={{ color: "var(--omsorg-text-secondary)", fontSize: "0.9rem", marginTop: 0 }}>
        Legt je Prüfung fest, ob eine Mitarbeiterzuweisung bei einem Konflikt blockiert wird
        ("Error") oder nur ein Hinweis erscheint, die Zuweisung aber trotzdem angelegt wird
        ("Warning").
      </p>

      {isLoading && <p>Lädt...</p>}
      {error && <p className="login-error">{error}</p>}

      {!isLoading && settings && (
        <>
          <div className="settings-permission-matrix settings-permission-matrix-scroll">
            <table>
              <thead>
                <tr>
                  <th>Prüfung</th>
                  <th>Modus</th>
                </tr>
              </thead>
              <tbody>
                {CHECKS.map(({ key, label }) => (
                  <tr key={key}>
                    <td>{label}</td>
                    <td>
                      <select
                        value={settings[key]}
                        onChange={(e) => handleChange(key, e.target.value)}
                        disabled={!canEdit || isSaving}
                      >
                        <option value="Warning">Warning (nur Hinweis)</option>
                        <option value="Error">Error (blockiert)</option>
                      </select>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {canEdit && (
            <div style={{ marginTop: "1rem", display: "flex", alignItems: "center", gap: "0.75rem" }}>
              <OmsorgButton variant="primary" icon={Save} onClick={handleSave} disabled={isSaving}>
                {isSaving ? "Speichert..." : "Speichern"}
              </OmsorgButton>
              {saved && <span style={{ color: "var(--omsorg-turquoise)" }}>Gespeichert.</span>}
            </div>
          )}
        </>
      )}
    </div>
  );
}
