import {
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from 'react'
import * as DropdownMenu from '@radix-ui/react-dropdown-menu'
import { useApolloClient, useMutation } from '@apollo/client/react'
import {
  Check,
  ChevronDown,
  CircleHelp,
  Clock,
  Lock,
  Pencil,
  Power,
  PowerOff,
  Settings2,
  Smartphone,
  Unlock,
  X,
} from 'lucide-react'

import { BluetoothIcon } from '../../../../assets/icons/Bluetooth'
import { GpsIcon } from '../../../../assets/icons/Gps'
import { CameraIcon } from '../../../../assets/icons/Camera'
import { SimIcon } from '../../../../assets/icons/Sim'
import {
  CHANGE_ORGANISATION_POLICY_MUTATION,
  GET_ORGANISATION_QUERY,
} from '../../../../entities/employee/api/employee.graphql'
import type {
  ChangeOrganisationData,
  ChangeOrganisationPolicyVariables,
  ComponentUseOption,
  GetOrganisationData,
  GetOrganisationVariables,
  GroupUsePolicyOption,
  Organisation,
  OrganisationPolicy,
  ServiceUseOption,
} from '../../../../entities/employee/model/types'
import {
  Notification,
  type NotificationVariant,
} from '../../../../widgets/Notification/Notification'
import { DurationPicker } from '../DurationPicker/DurationPicker'

import './OrganisationPolicyCard.scss'

type PolicyOptionKey = 'bluetooth' | 'gps' | 'camera' | 'sim' | 'speaker'
type PolicyKey = /* 'wifi' |  */ PolicyOptionKey
type EditableStateKey =
  | 'bluetoothEditable'
  | 'gpsEditable'
  | 'cameraEditable'
  | 'simEditable'
type PolicyKind = 'service' | 'component'
type PolicyValue = ServiceUseOption | ComponentUseOption
type PolicyModePrototypeValue = 'enabled' | 'disabled'

type TimePickerValue = {
  days: number
  hours: number
  minutes: number
}

export type OrganisationPolicyDraft = {
  bluetooth: ServiceUseOption
  gps: ServiceUseOption
  camera: ComponentUseOption
  sim: ServiceUseOption
  speaker: ComponentUseOption
  bluetoothEditable: boolean
  gpsEditable: boolean
  cameraEditable: boolean
  simEditable: boolean
  offlineTimeThreshold: number
}

type PolicyItem = {
  key: PolicyOptionKey
  editableKey?: EditableStateKey
  kind: PolicyKind
  label: string
  icon: ReactNode
  disabled?: boolean
}

type OrganisationPolicyCardProps = {
  organisation?: Organisation
  value?: OrganisationPolicyDraft
  onChange?: (policy: OrganisationPolicyDraft) => void
  disabled?: boolean
  title?: string
  description?: string
  variant?: 'page' | 'form'
}

type PolicyNotification = {
  id: number
  variant: NotificationVariant
  title: string
  description?: string
} | null

const MINUTE_MS = 60 * 1000
const HOUR_MS = 60 * MINUTE_MS
const DAY_MS = 24 * HOUR_MS
const DEFAULT_OFFLINE_TIME_THRESHOLD = 7 * DAY_MS
const SERVICE_POLICY_OPTION_ORDER: ServiceUseOption[] = [
  'Disabled',
  'Unspecified',
  'Enabled',
]
const COMPONENT_POLICY_OPTION_ORDER: ComponentUseOption[] = [
  'Disallowed',
  'Allowed',
]
const DEFAULT_SERVICE_POLICY_OPTION: ServiceUseOption = 'Enabled'
const DEFAULT_COMPONENT_POLICY_OPTION: ComponentUseOption = 'Allowed'

export const defaultOrganisationPolicyDraft: OrganisationPolicyDraft = {
  bluetooth: DEFAULT_SERVICE_POLICY_OPTION,
  gps: DEFAULT_SERVICE_POLICY_OPTION,
  camera: DEFAULT_COMPONENT_POLICY_OPTION,
  sim: DEFAULT_SERVICE_POLICY_OPTION,
  speaker: DEFAULT_COMPONENT_POLICY_OPTION,
  bluetoothEditable: true,
  gpsEditable: true,
  cameraEditable: true,
  simEditable: true,
  offlineTimeThreshold: DEFAULT_OFFLINE_TIME_THRESHOLD,
}

const policyOptionFullLabels: Record<PolicyValue, string> = {
  Disabled: 'Выключено',
  Unspecified: 'Свободно',
  Enabled: 'Включено',
  Allowed: 'Включено',
  Disallowed: 'Выключено',
}

const policyOptionDescriptions: Record<PolicyValue, string> = {
  Disabled: 'Опция отключена групповой политикой.',
  Unspecified: 'Групповая политика не фиксирует значение. Можно настроить ниже по иерархии.',
  Enabled: 'Опция включена групповой политикой.',
  Allowed: 'Компонент разрешен групповой политикой.',
  Disallowed: 'Компонент запрещен групповой политикой.',
}

const policyItems: PolicyItem[] = [
  /* {
    key: 'wifi',
    label: 'Wi-Fi',
    icon: <WifiIcon />,
    disabled: true,
  }, */
  {
    key: 'bluetooth',
    editableKey: 'bluetoothEditable',
    kind: 'service',
    label: 'Bluetooth',
    icon: <BluetoothIcon />,
  },
  {
    key: 'gps',
    editableKey: 'gpsEditable',
    kind: 'service',
    label: 'GPS',
    icon: <GpsIcon />,
  },
  {
    key: 'camera',
    editableKey: 'cameraEditable',
    kind: 'component',
    label: 'Камера',
    icon: <CameraIcon />,
  },
  {
    key: 'sim',
    editableKey: 'simEditable',
    kind: 'service',
    label: 'SIM-карта',
    icon: <SimIcon />,
  }/* ,
  {
    key: 'speaker',
    kind: 'component',
    label: 'Динамик',
    icon: <VolumeIcon />,
    disabled: true,
  }, */
]

const editableOptions = [
  {
    value: true,
    title: 'Разрешено',
    description: 'Можно менять на смартфоне и на странице устройства.',
    icon: <Unlock size={16} />,
  },
  {
    value: false,
    title: 'Зафиксировано',
    description: 'Изменение запрещено, опция фиксируется групповой политикой.',
    icon: <Lock size={16} />,
  },
]

function normalizeOfflineThreshold(value?: number | null) {
  if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
    return DEFAULT_OFFLINE_TIME_THRESHOLD
  }

  return value
}

function normalizeServiceOption(
  value?: ServiceUseOption | GroupUsePolicyOption | null,
  fallbackBoolean?: boolean | null,
): ServiceUseOption {
  if (value && SERVICE_POLICY_OPTION_ORDER.includes(value as ServiceUseOption)) {
    return value as ServiceUseOption
  }

  if (value === 'Allowed') return 'Enabled'
  if (value === 'Disallowed') return 'Disabled'
  if (value === 'Changeable') return 'Unspecified'

  if (typeof fallbackBoolean === 'boolean') {
    return fallbackBoolean ? 'Enabled' : 'Disabled'
  }

  return DEFAULT_SERVICE_POLICY_OPTION
}

function normalizeComponentOption(
  value?: ComponentUseOption | ServiceUseOption | GroupUsePolicyOption | null,
  fallbackBoolean?: boolean | null,
): ComponentUseOption {
  if (value && COMPONENT_POLICY_OPTION_ORDER.includes(value as ComponentUseOption)) {
    return value as ComponentUseOption
  }

  if (value === 'Enabled') return 'Allowed'
  if (value === 'Disabled') return 'Disallowed'

  if (typeof fallbackBoolean === 'boolean') {
    return fallbackBoolean ? 'Allowed' : 'Disallowed'
  }

  return DEFAULT_COMPONENT_POLICY_OPTION
}

function normalizeEditable(
  value?: boolean | null,
  legacyValue?: GroupUsePolicyOption | ServiceUseOption | ComponentUseOption | null,
) {
  if (typeof value === 'boolean') {
    return value
  }

  if (legacyValue === 'Changeable') {
    return true
  }

  if (legacyValue === 'Allowed' || legacyValue === 'Disallowed') {
    return false
  }

  return true
}

function getPolicyOptions(kind: PolicyKind): PolicyValue[] {
  return kind === 'service'
    ? SERVICE_POLICY_OPTION_ORDER
    : COMPONENT_POLICY_OPTION_ORDER
}

function getPolicyOptionIcon(option: PolicyValue, size = 14) {
  if (option === 'Unspecified') {
    return <Smartphone size={size} aria-hidden="true" />
  }

  if (option === 'Enabled' || option === 'Allowed') {
    return <Power size={size} aria-hidden="true" />
  }

  return <PowerOff size={size} aria-hidden="true" />
}

function splitOfflineThreshold(value: number): TimePickerValue {
  const totalMinutes = Math.max(0, Math.round(value / MINUTE_MS))
  const days = Math.floor(totalMinutes / (24 * 60))
  const hours = Math.floor((totalMinutes - days * 24 * 60) / 60)
  const minutes = totalMinutes - days * 24 * 60 - hours * 60

  return {
    days,
    hours,
    minutes,
  }
}

export function mapOrganisationPolicyToDraft(
  policy?: OrganisationPolicy | OrganisationPolicyDraft | null,
): OrganisationPolicyDraft {
  const draftPolicy = policy as Partial<OrganisationPolicyDraft> | null | undefined
  const apiPolicy = policy as OrganisationPolicy | null | undefined

  return {
    bluetooth: normalizeServiceOption(
      draftPolicy?.bluetooth,
      apiPolicy?.canUseBluetooth,
    ),
    gps: normalizeServiceOption(
      draftPolicy?.gps ?? apiPolicy?.GPS,
      apiPolicy?.canUseGPS,
    ),
    camera: normalizeComponentOption(
      draftPolicy?.camera,
      apiPolicy?.canUseCamera,
    ),
    sim: normalizeServiceOption(
      draftPolicy?.sim,
      apiPolicy?.canUseSim,
    ),
    speaker: DEFAULT_COMPONENT_POLICY_OPTION,
    bluetoothEditable: normalizeEditable(
      draftPolicy?.bluetoothEditable,
      draftPolicy?.bluetooth,
    ),
    gpsEditable: normalizeEditable(
      draftPolicy?.gpsEditable,
      draftPolicy?.gps ?? apiPolicy?.GPS,
    ),
    cameraEditable: normalizeEditable(
      draftPolicy?.cameraEditable,
      draftPolicy?.camera,
    ),
    simEditable: normalizeEditable(
      draftPolicy?.simEditable,
      draftPolicy?.sim,
    ),
    offlineTimeThreshold: normalizeOfflineThreshold(
      draftPolicy?.offlineTimeThreshold ?? apiPolicy?.offlineTimeThreshold,
    ),
  }
}

export function mapOrganisationPolicyDraftToVariables(
  policy: OrganisationPolicyDraft,
) {
  return {
    bluetooth: policy.bluetooth,
    bluetoothEditable: policy.bluetoothEditable,
    camera: policy.camera,
    cameraEditable: policy.cameraEditable,
    GPS: policy.gps,
    gpsEditable: policy.gpsEditable,
    sim: policy.sim,
    simEditable: policy.simEditable,
    offlineTimeThreshold: policy.offlineTimeThreshold,
  }
}

function isPolicyChanged(
  current: OrganisationPolicyDraft,
  saved: OrganisationPolicyDraft,
) {
  return (
    current.bluetooth !== saved.bluetooth ||
    current.bluetoothEditable !== saved.bluetoothEditable ||
    current.gps !== saved.gps ||
    current.gpsEditable !== saved.gpsEditable ||
    current.camera !== saved.camera ||
    current.cameraEditable !== saved.cameraEditable ||
    current.sim !== saved.sim ||
    current.simEditable !== saved.simEditable ||
    current.offlineTimeThreshold !== saved.offlineTimeThreshold
  )
}

export function PolicyModePrototype() {
  const [mode, setMode] =
    useState<PolicyModePrototypeValue>('enabled')
  const [isEditable, setIsEditable] = useState(true)

  function renderSegment(
    segmentMode: PolicyModePrototypeValue,
    label: string,
  ) {
    const isActive = mode === segmentMode

    if (!isActive) {
      return (
        <button
          className="policy-mode-prototype-switch__segment"
          type="button"
          onClick={() => setMode(segmentMode)}
        >
          {label}
        </button>
      )
    }

    return (
      <div
        className="policy-mode-prototype-switch__segment is-active"
        aria-label={label}
      >
        <span
          className="policy-mode-prototype-switch__edit"
          aria-label="Редактируемость пользователем"
        >
          <button
            className={isEditable ? 'is-selected' : ''}
            type="button"
            onClick={() => setIsEditable(true)}
            aria-pressed={isEditable}
            title="Пользователь может изменить настройку на телефоне"
          >
            Можно
          </button>

          <button
            className={!isEditable ? 'is-selected' : ''}
            type="button"
            onClick={() => setIsEditable(false)}
            aria-pressed={!isEditable}
            title="Пользователь не может изменить настройку на телефоне"
          >
            Нельзя
          </button>
        </span>
      </div>
    )
  }

  return (
    <div className="policy-mode-prototype">
      <Settings2 />

      <div className="policy-mode-prototype__content">
        <span>Тестовый режим</span>

        <div
          className={`policy-mode-prototype-switch is-${mode}`}
          role="group"
          aria-label="Тестовый переключатель политики"
        >
          {renderSegment('disabled', 'Выкл')}
          {renderSegment('enabled', 'Вкл')}
        </div>
      </div>
    </div>
  )
}

export function OrganisationPolicyCard({
  organisation,
  value,
  onChange,
  disabled = false,
  title = 'Групповая политика',
  description = 'Применяется при авторизации на устройстве',
  variant = 'page',
}: OrganisationPolicyCardProps) {
  const client = useApolloClient()
  const isFormVariant = variant === 'form'
  const initialPolicy = useMemo(
    () =>
      value
        ? mapOrganisationPolicyToDraft(value)
        : mapOrganisationPolicyToDraft(organisation?.policy),
    [organisation?.policy, value],
  )

  const [policyState, setPolicyState] = useState(initialPolicy)
  const [savedPolicyState, setSavedPolicyState] = useState(initialPolicy)
  const [isSaving, setIsSaving] = useState(false)
  const [isEditing, setIsEditing] = useState(false)
  const [saveError, setSaveError] = useState(false)
  const [notification, setNotification] =
    useState<PolicyNotification>(null)

  const [changeOrganisation] = useMutation<
    ChangeOrganisationData,
    ChangeOrganisationPolicyVariables
  >(CHANGE_ORGANISATION_POLICY_MUTATION)

  const offlinePickerValue = splitOfflineThreshold(
    policyState.offlineTimeThreshold,
  )
  const hasChanges =
    !isFormVariant && isPolicyChanged(policyState, savedPolicyState)
  const hasHeaderActionsOpen = !isFormVariant && (isEditing || hasChanges)
  const isPolicyEditing = isFormVariant || isEditing
  const isInteractionDisabled = disabled || isSaving

  useEffect(() => {
    setPolicyState(initialPolicy)
    setSavedPolicyState(initialPolicy)
    setSaveError(false)
    if (!isFormVariant) {
      setIsEditing(false)
    }
  }, [initialPolicy, isFormVariant])

  function showNotification(
    variant: NotificationVariant,
    title: string,
    description?: string,
  ) {
    setNotification({
      id: Date.now(),
      variant,
      title,
      description,
    })
  }

  function commitPolicyDraft(nextPolicy: OrganisationPolicyDraft) {
    setPolicyState(nextPolicy)
    onChange?.(nextPolicy)
    setSaveError(false)
  }

  function handlePolicyOptionChange(
    key: PolicyKey,
    option: PolicyValue,
    disabled?: boolean,
  ) {
    if (disabled || !isPolicyEditing || isInteractionDisabled) return

    commitPolicyDraft({
      ...policyState,
      [key]: option,
    })
  }

  function handleEditableChange(key: EditableStateKey, value: boolean) {
    if (!isPolicyEditing || isInteractionDisabled) return

    commitPolicyDraft({
      ...policyState,
      [key]: value,
    })
  }

  function handleOfflinePickerChange(totalMinutes: number) {
    if (!isPolicyEditing || isInteractionDisabled) return

    commitPolicyDraft({
      ...policyState,
      offlineTimeThreshold: Math.max(0, totalMinutes) * MINUTE_MS,
    })
  }

  function handleReset() {
    if (isFormVariant || ((!isEditing && !hasChanges) || isSaving)) return

    setPolicyState(savedPolicyState)
    setSaveError(false)
    setIsEditing(false)
  }

  function handleEditClick() {
    if (isFormVariant) return
    setIsEditing(true)
  }

  async function handleConfirmClick() {
    if (isFormVariant || isSaving) return

    if (!hasChanges) {
      setIsEditing(false)
      setSaveError(false)
      return
    }

    await handleSave()
  }

  async function handleSave() {
    if (!organisation || !hasChanges || isSaving) return

    const requestedPolicy = policyState

    setIsSaving(true)
    setSaveError(false)

    try {
      await changeOrganisation({
        variables: {
          id: String(organisation.id),
          name: organisation.name,
          ...mapOrganisationPolicyDraftToVariables(requestedPolicy),
        },
      })

      const result = await client.query<
        GetOrganisationData,
        GetOrganisationVariables
      >({
        query: GET_ORGANISATION_QUERY,
        variables: {
          id: String(organisation.id),
        },
        fetchPolicy: 'network-only',
      })

      const refreshedPolicy = mapOrganisationPolicyToDraft(
        result.data?.getOrganisation?.policy,
      )

      setPolicyState(refreshedPolicy)
      setSavedPolicyState(refreshedPolicy)

      if (isPolicyChanged(requestedPolicy, refreshedPolicy)) {
        setSaveError(true)
        showNotification(
          'error',
          'Политика не изменилась',
          'Сервер ответил без ошибки, но после повторной загрузки вернулась прежняя политика.',
        )
        return
      }

      showNotification('success', 'Политика сохранена')
      setIsEditing(false)
    } catch {
      setSaveError(true)
      showNotification(
        'error',
        'Не удалось сохранить политику',
        'Изменения остались в черновике. Попробуйте снова после исправления бэка.',
      )
    } finally {
      setIsSaving(false)
    }
  }

  return (
    <div
      className={`organisation-policy-card organisation-policy-card--${variant} ${
        hasHeaderActionsOpen ? 'is-editing' : ''
      } ${isPolicyEditing ? 'is-policy-editing' : ''}`}
    >
      <div className="organisation-policy-card__header">
        <div>
          <div className="organisation-policy-card__title">
            <h3>{title}</h3>

            <span
              className="organisation-policy-card__help"
              tabIndex={0}
              aria-label="Пояснение значений групповой политики"
            >
              <CircleHelp size={16} />

              <span className="organisation-policy-card__help-tooltip" role="tooltip">
                <span className="organisation-policy-card__help-row">
                  {getPolicyOptionIcon('Disabled', 15)}
                  <span>
                    <b>Выключено</b>
                    <small>Опция отключена групповой политикой.</small>
                  </span>
                </span>
                <span className="organisation-policy-card__help-row">
                  {getPolicyOptionIcon('Unspecified', 15)}
                  <span>
                    <b>Свободно</b>
                    <small>Групповая политика не фиксирует значение. Можно настроить ниже по иерархии.</small>
                  </span>
                </span>
                <span className="organisation-policy-card__help-row">
                  {getPolicyOptionIcon('Enabled', 15)}
                  <span>
                    <b>Включено</b>
                    <small>Опция включена групповой политикой.</small>
                  </span>
                </span>
              </span>
            </span>
          </div>

          <p>{description}</p>
        </div>

        {!isFormVariant && (
          <div className="device-permissions__header-actions">
            <button
              className="device-permissions__icon-btn device-permissions__icon-btn--reset"
              type="button"
              disabled={(!isEditing && !hasChanges) || isSaving}
              onClick={handleReset}
              aria-label="Отменить редактирование"
            >
              <X size={18} />
            </button>

            <button
              className="device-permissions__icon-btn device-permissions__icon-btn--edit"
              type="button"
              disabled={isSaving}
              onClick={
                hasHeaderActionsOpen ? handleConfirmClick : handleEditClick
              }
              aria-label={
                hasHeaderActionsOpen
                  ? 'Сохранить изменения'
                  : 'Редактировать опции'
              }
            >
              {hasHeaderActionsOpen ? <Check size={18} /> : <Pencil size={18} />}
            </button>
          </div>
        )}
      </div>

      <div className="organisation-policy-card__list">
        {policyItems.map((item) => {
          const option = policyState[item.key]
          const options = getPolicyOptions(item.kind)
          const editableKey = item.editableKey
          const editableValue = editableKey ? policyState[editableKey] : true
          const selectedEditableOption =
            editableOptions.find(
              (editableOption) => editableOption.value === editableValue,
            ) ?? editableOptions[0]
          const isDisabled =
            item.disabled || !isPolicyEditing || isInteractionDisabled

          return (
            <div
              className={`organisation-policy-item ${
                item.disabled ? 'is-disabled' : ''
              }`}
              key={item.key}
              aria-disabled={item.disabled}
            >
              {item.icon}

              <div className="organisation-policy-item__content">
                <span className="organisation-policy-item__label">
                  {item.label}
                </span>

                <div className="organisation-policy-item__controls">
                  {editableKey && (
                    <DropdownMenu.Root>
                      <DropdownMenu.Trigger asChild>
                        <button
                          className={`organisation-policy-editability ${
                            editableValue ? 'is-editable' : 'is-fixed'
                          }`}
                          type="button"
                          disabled={isDisabled}
                          aria-label={`${item.label}: ${selectedEditableOption.title}`}
                        >
                          <div className='icon-title'>
                            {selectedEditableOption.icon}
                            <span>{selectedEditableOption.title}</span>
                          </div>
                          <ChevronDown size={14} />
                        </button>
                      </DropdownMenu.Trigger>

                      <DropdownMenu.Portal>
                        <DropdownMenu.Content
                          className="organisation-policy-editability-menu"
                          align="end"
                          sideOffset={6}
                        >
                          {editableOptions.map((editableOption) => (
                            <DropdownMenu.Item
                              key={String(editableOption.value)}
                              className={`organisation-policy-editability-menu__item ${
                                editableValue === editableOption.value
                                  ? 'is-selected'
                                  : ''
                              }`}
                              onSelect={() =>
                                handleEditableChange(
                                  editableKey,
                                  editableOption.value,
                                )
                              }
                            >
                              <span className="organisation-policy-editability-menu__icon">
                                {editableOption.icon}
                              </span>

                              <span className="organisation-policy-editability-menu__text">
                                <strong>{editableOption.title}</strong>
                                <small>{editableOption.description}</small>
                              </span>

                              {editableValue === editableOption.value && (
                                <Check
                                  className="organisation-policy-editability-menu__check"
                                  size={16}
                                />
                              )}
                            </DropdownMenu.Item>
                          ))}
                        </DropdownMenu.Content>
                      </DropdownMenu.Portal>
                    </DropdownMenu.Root>
                  )}

                  <div
                    className={`organisation-policy-switch organisation-policy-switch--${item.kind} is-${option.toLowerCase()} ${
                      isDisabled ? 'is-disabled' : ''
                    }`}
                    role="radiogroup"
                    aria-label={`${item.label}: ${policyOptionFullLabels[option]}`}
                    aria-disabled={isDisabled}
                  >
                    <span
                      className="organisation-policy-switch__thumb"
                      aria-hidden="true"
                    />

                    {options.map((policyOption) => {
                      const isActive = option === policyOption

                      return (
                        <button
                          className={`organisation-policy-switch__option ${
                            isActive ? 'is-active' : ''
                          }`}
                          key={policyOption}
                          type="button"
                          role="radio"
                          aria-checked={isActive}
                          aria-disabled={isDisabled}
                          aria-label={`${policyOptionFullLabels[policyOption]}: ${policyOptionDescriptions[policyOption]}`}
                          tabIndex={isDisabled ? -1 : 0}
                          onClick={() => {
                            if (!isDisabled && !isActive) {
                              handlePolicyOptionChange(
                                item.key,
                                policyOption,
                                item.disabled,
                              )
                            }
                          }}
                        >
                          <span className="organisation-policy-switch__label">
                            {getPolicyOptionIcon(policyOption)}
                          </span>
                        </button>
                      )
                    })}
                  </div>
                </div>
              </div>
            </div>
          )
        })}
      </div>

      {/* <PolicyModePrototype /> */}

      <div className={`offline-threshold`}>
        <Clock className={`offline-threshold-svg ${isPolicyEditing ? '' : 'is-disabled'}`} />

        <div className="offline-threshold__content">
          {/* <span>Блокировка без сети</span> */}
          <span className={`offline-threshold__title ${isPolicyEditing ? '' : 'is-disabled'}`}>
            <label>Вне сети</label>
            <span
              className="offline-threshold__help"
              tabIndex={0}
              aria-label="Блокирует устройства организации, если они не выходили в сеть дольше заданного времени."
              aria-describedby="offline-threshold-tooltip"
            >
              <CircleHelp />

              <span
                className="offline-threshold__tooltip"
                id="offline-threshold-tooltip"
                role="tooltip"
              >
                Блокирует устройства организации, если они не выходили в
                сеть дольше заданного времени.
              </span>
            </span>
          </span>

          <DurationPicker
            className="offline-threshold__picker"
            value={offlinePickerValue}
            isEditing={isPolicyEditing}
            disabled={isInteractionDisabled}
            onChange={({ totalMinutes }) => {
              handleOfflinePickerChange(totalMinutes)
            }}
          />
        </div>
      </div>

      {!isFormVariant && (
        <div className="organisation-policy-card__footer">
          {saveError && (
            <div className="organisation-policy-card__error">
              Не удалось сохранить групповую политику
            </div>
          )}
        </div>
      )}

      {!isFormVariant && notification && (
        <Notification
          key={notification.id}
          variant={notification.variant}
          title={notification.title}
          description={notification.description}
          onClose={() => setNotification(null)}
        />
      )}
    </div>
  )
}
