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

export default function RolesPanel() {
  const { hasPermission } = useAuth();
  const canCreate = hasPermission("UserManagement", "Create");
  const canEdit = hasPermission("UserManagement", "Edit");
  const canDelete = hasPermission("UserManagement", "Delete");

  const [roles, setRoles] = useState([]);
  const [selectedRoleId, setSelectedRoleId] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [newRoleName, setNewRoleName] = useState("");
  const [isCreating, setIsCreating] = useState(false);
  const [createError, setCreateError] = useState(null);
  const [deletingRoleId, setDeletingRoleId] = useState(null);
  const [deleteError, setDeleteError] = useState(null);

  const loadRoles = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    const result = await window.omsorg.roles.list();
    if (result.ok) {
      const data = result.data ?? [];
      setRoles(data);
      setSelectedRoleId((current) => current ?? data[0]?.id ?? null);
    } else {
      setError("Rollen konnten nicht geladen werden.");
    }
    setIsLoading(false);
  }, []);

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

  async function handleCreateRole(event) {
    event.preventDefault();
    if (!newRoleName.trim()) {
      setCreateError("Name ist erforderlich.");
      return;
    }

    setIsCreating(true);
    setCreateError(null);
    const result = await window.omsorg.roles.create({ name: newRoleName.trim() });
    setIsCreating(false);

    if (!result.ok) {
      setCreateError(result.status === 409 ? "Diese Rolle existiert bereits." : "Rolle konnte nicht angelegt werden.");
      return;
    }

    setNewRoleName("");
    await loadRoles();
    setSelectedRoleId(result.data.id);
  }

  async function handleDeleteRole(role) {
    if (!window.confirm(`Rolle "${role.name}" wirklich löschen?`)) {
      return;
    }

    setDeletingRoleId(role.id);
    setDeleteError(null);
    const result = await window.omsorg.roles.delete(role.id);
    setDeletingRoleId(null);

    if (!result.ok) {
      setDeleteError(
        result.status === 409
          ? typeof result.data === "string"
            ? result.data
            : "Diese Rolle ist noch Benutzern zugewiesen und kann nicht gelöscht werden."
          : "Rolle konnte nicht gelöscht werden."
      );
      return;
    }

    if (selectedRoleId === role.id) {
      setSelectedRoleId(null);
    }
    await loadRoles();
  }

  const selectedRole = roles.find((role) => role.id === selectedRoleId);

  return (
    <div className="settings-roles-panel">
      <div className="settings-panel-heading">
        <h4>Rollen</h4>

        {canCreate && (
          <form onSubmit={handleCreateRole} className="settings-new-role-form">
            <input
              type="text"
              placeholder="Neue Rolle"
              value={newRoleName}
              onChange={(event) => setNewRoleName(event.target.value)}
            />
            <OmsorgButton icon={Plus} type="submit" variant="secondary" disabled={isCreating}>
              Anlegen
            </OmsorgButton>
          </form>
        )}
      </div>
      {createError && <p className="login-error">{createError}</p>}
      {deleteError && <p className="login-error">{deleteError}</p>}

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

      {!isLoading && !error && (
        <div className="settings-roles-layout">
          <div className="settings-roles-list">
            <ul>
              {roles.map((role) => (
                <li key={role.id} className="settings-role-item-row">
                  <button
                    type="button"
                    className={role.id === selectedRoleId ? "settings-role-item settings-role-item--active" : "settings-role-item"}
                    onClick={() => setSelectedRoleId(role.id)}
                  >
                    {role.name}
                  </button>

                  {canDelete && (
                    <OmsorgButton
                      variant="secondary"
                      icon={Trash2}
                      onClick={() => handleDeleteRole(role)}
                      disabled={deletingRoleId === role.id}
                    />
                  )}
                </li>
              ))}
            </ul>
          </div>

          <div className="settings-roles-detail">
            {selectedRole ? (
              <RolePermissionMatrix roleId={selectedRole.id} roleName={selectedRole.name} canEdit={canEdit} />
            ) : (
              <p>Keine Rolle ausgewählt.</p>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
