import { useCallback, useEffect, useState } from "react";
import { Plus, Trash2 } from "lucide-react";
import OmsorgButton from "../../components/ui/OmsorgButton";
import { useAuth } from "../../app/AuthContext";
import { MODULE_OPTIONS, ACTION_OPTIONS, EFFECT_OPTIONS, SCOPE_OPTIONS } from "./permissionOptions";

function labelFor(options, value) {
  return options.find((option) => option.value === value)?.label ?? value;
}

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

  const [users, setUsers] = useState([]);
  const [selectedUserId, setSelectedUserId] = useState(null);
  const [overrides, setOverrides] = useState([]);
  const [isLoadingUsers, setIsLoadingUsers] = useState(true);
  const [isLoadingOverrides, setIsLoadingOverrides] = useState(false);
  const [error, setError] = useState(null);

  const [newModule, setNewModule] = useState(MODULE_OPTIONS[0].value);
  const [newAction, setNewAction] = useState(ACTION_OPTIONS[0].value);
  const [newEffect, setNewEffect] = useState(EFFECT_OPTIONS[0].value);
  const [newScope, setNewScope] = useState(SCOPE_OPTIONS[0].value);
  const [isAdding, setIsAdding] = useState(false);
  const [addError, setAddError] = useState(null);

  useEffect(() => {
    async function loadUsers() {
      setIsLoadingUsers(true);
      const result = await window.omsorg.users.list();
      if (result.ok) {
        const data = result.data ?? [];
        setUsers(data);
        setSelectedUserId((current) => current ?? data[0]?.id ?? null);
      } else {
        setError("Nutzer konnten nicht geladen werden.");
      }
      setIsLoadingUsers(false);
    }
    loadUsers();
  }, []);

  const loadOverrides = useCallback(async (userId) => {
    if (!userId) return;
    setIsLoadingOverrides(true);
    setError(null);
    const result = await window.omsorg.users.listPermissionOverrides(userId);
    if (result.ok) {
      setOverrides(result.data ?? []);
    } else {
      setError("Rechte-Ausnahmen konnten nicht geladen werden.");
    }
    setIsLoadingOverrides(false);
  }, []);

  useEffect(() => {
    loadOverrides(selectedUserId);
  }, [selectedUserId, loadOverrides]);

  async function handleAddOverride(event) {
    event.preventDefault();
    setIsAdding(true);
    setAddError(null);

    const result = await window.omsorg.users.addPermissionOverride(selectedUserId, {
      module: newModule,
      action: newAction,
      effect: newEffect,
      scope: newScope,
    });

    setIsAdding(false);
    if (!result.ok) {
      setAddError("Override konnte nicht gespeichert werden.");
      return;
    }

    await loadOverrides(selectedUserId);
  }

  async function handleDelete(overrideId) {
    await window.omsorg.users.deletePermissionOverride(selectedUserId, overrideId);
    await loadOverrides(selectedUserId);
  }

  return (
    <div className="settings-overrides-panel">
      {isLoadingUsers && <p>Lädt...</p>}
      {error && <p className="login-error">{error}</p>}

      {!isLoadingUsers && (
        <div className="settings-roles-layout">
          <div className="settings-roles-list">
            <ul>
              {users.map((user) => (
                <li key={user.id}>
                  <button
                    type="button"
                    className={user.id === selectedUserId ? "settings-role-item settings-role-item--active" : "settings-role-item"}
                    onClick={() => setSelectedUserId(user.id)}
                  >
                    {user.username}
                  </button>
                </li>
              ))}
            </ul>
          </div>

          <div className="settings-roles-detail">
            {!selectedUserId && <p>Kein Nutzer ausgewählt.</p>}

            {selectedUserId && (
              <>
                {isLoadingOverrides && <p>Lädt...</p>}

                {!isLoadingOverrides && overrides.length === 0 && <p>Keine individuellen Rechte-Ausnahmen.</p>}

                {!isLoadingOverrides && overrides.length > 0 && (
                  <ul className="debug-sessions-list">
                    {overrides.map((o) => (
                      <li key={o.id} className="debug-sessions-row">
                        <div>
                          <strong>
                            {labelFor(MODULE_OPTIONS, o.module)} · {labelFor(ACTION_OPTIONS, o.action)}
                          </strong>
                          <p className="debug-sessions-meta">
                            {labelFor(EFFECT_OPTIONS, o.effect)} · {labelFor(SCOPE_OPTIONS, o.scope)}
                          </p>
                        </div>
                        {canEdit && (
                          <OmsorgButton icon={Trash2} variant="danger" onClick={() => handleDelete(o.id)}>
                            Entfernen
                          </OmsorgButton>
                        )}
                      </li>
                    ))}
                  </ul>
                )}

                {canEdit && (
                  <form onSubmit={handleAddOverride} className="settings-new-override-form">
                    <select value={newModule} onChange={(event) => setNewModule(event.target.value)}>
                      {MODULE_OPTIONS.map((option) => (
                        <option key={option.value} value={option.value}>
                          {option.label}
                        </option>
                      ))}
                    </select>
                    <select value={newAction} onChange={(event) => setNewAction(event.target.value)}>
                      {ACTION_OPTIONS.map((option) => (
                        <option key={option.value} value={option.value}>
                          {option.label}
                        </option>
                      ))}
                    </select>
                    <select value={newEffect} onChange={(event) => setNewEffect(event.target.value)}>
                      {EFFECT_OPTIONS.map((option) => (
                        <option key={option.value} value={option.value}>
                          {option.label}
                        </option>
                      ))}
                    </select>
                    <select value={newScope} onChange={(event) => setNewScope(event.target.value)}>
                      {SCOPE_OPTIONS.map((option) => (
                        <option key={option.value} value={option.value}>
                          {option.label}
                        </option>
                      ))}
                    </select>
                    <OmsorgButton icon={Plus} type="submit" variant="secondary" disabled={isAdding}>
                      Override hinzufügen
                    </OmsorgButton>
                  </form>
                )}
                {addError && <p className="login-error">{addError}</p>}
              </>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
