import {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react'
import {
  Link,
  useNavigate,
  useOutletContext,
  useParams,
  useLocation,
  useSearchParams,
} from 'react-router-dom'
import { useQuery, useMutation } from '@apollo/client/react'
import { Lock, Pencil, Store, Trash2 } from 'lucide-react'

import SimpleBar from "simplebar-react";
import "simplebar-react/dist/simplebar.min.css";
import type SimpleBarCore from 'simplebar-core'

import {
  DELETE_ORGANISATION_MUTATION,
  GET_ORGANISATION_QUERY,
  GET_USERS_QUERY,
} from '../../entities/employee/api/employee.graphql'
import { GET_PHONES_QUERY } from '../../entities/device/api/device.graphql'
import type {
  Employee,
  GetOrganisationData,
  GetOrganisationVariables,
  GetUsersData,
  GetUsersVariables,
  Organisation,
  DeleteOrganisationData,
  DeleteOrganisationVariables,
} from '../../entities/employee/model/types'
import type {
  Device as OrganisationDevice,
  DeviceNetworkStatus,
  GetPhonesData,
  GetPhonesVariables,
} from '../../entities/device/model/types'
import { ConfirmDangerDialog } from '../../widgets/ConfirmDangerDialog/ConfirmDangerDialog'
import { EmployeesPagination } from '../EmployeesPage/components/EmployeesPagination/EmployeesPagination'
import {
  EmployeesToolbar,
  usersSortOptions,
} from '../EmployeesPage/components/EmployeesToolbar/EmployeesToolbar'
import {
  DevicesToolbar,
  devicesSortOptions,
} from '../DevicesPage/components/DevicesToolbar/DevicesToolbar'
import { getPaginationItems } from '../EmployeesPage/lib/getPaginationItems'
import { OrganisationPolicyCard } from './components/OrganisationPolicyCard/OrganisationPolicyCard'
import { WifiIcon } from '../../assets/icons/Wifi'
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 { VolumeIcon } from '../../assets/icons/Volume'
import {
  TableSkeleton,
  type TableSkeletonColumn,
} from '../../shared/ui/TableSkeleton/TableSkeleton'
import { RevealContent } from '../../shared/ui/RevealContent/RevealContent'
import { isPhonePolicyOptionEnabled } from '../../entities/device/lib/phonePolicy'
import { EmptyState } from '../../shared/ui/EmptyState/EmptyState'
import type { AppLayoutOutletContext } from '../../app/layouts/AppLayout'
import {
  useDeferredModalPayload,
} from '../../shared/lib/lazyMount'
import { AddOrganisationModal } from '../EmployeesPage/components/AddOrganisationModal/AddOrganisationModal'
import { AddEmployeeModal } from '../EmployeesPage/components/AddEmployeeModal/AddEmployeeModal'
import { AddDeviceModal } from '../DevicesPage/components/AddDeviceModal/AddDeviceModal'

import './OrganisationPage.scss'

type OrganisationTable = 'employees' | 'devices'

const organisationEmployeesSkeletonColumns: TableSkeletonColumn[] = [
  { width: '42px', headerWidth: '34px' },
  { width: '72%', headerWidth: '54px' },
  { width: '74%', headerWidth: '118px' },
  { variant: 'pill', headerWidth: '54px' },
  { variant: 'actions', headerWidth: '64px' },
]

const organisationDevicesSkeletonColumns: TableSkeletonColumn[] = [
  { width: '36px', headerWidth: '28px' },
  { variant: 'stack', lines: 3, width: '76%', headerWidth: '118px' },
  { variant: 'pill', headerWidth: '92px' },
  { variant: 'pill', headerWidth: '72px' },
  { variant: 'icons', headerWidth: '72px' },
]

function getEmployeeFullName(employee: Employee) {
  return [employee.lastName, employee.firstName, employee.middleName]
    .filter(Boolean)
    .join(' ')
}

function getEmployeeRoleLabel(role: string) {
  if (role === 'Admin') return 'Администратор'
  if (role === 'User') return 'Пользователь'

  return role
}

function getDeviceConditionLabel(needMaintenance?: boolean) {
  return needMaintenance ? 'Требует ТО' : 'Исправно'
}

function getDeviceConditionClass(needMaintenance?: boolean) {
  return needMaintenance ? 'devices-status--red' : 'devices-status--green'
}

function getDeviceConditionDotClass(needMaintenance?: boolean) {
  return needMaintenance ? 'devices-dot--red' : 'devices-dot--green'
}

function getDeviceNetworkLabel(status?: DeviceNetworkStatus) {
  if (status === 'Online') return 'В сети'
  if (status === 'Lost') return 'Потерян'

  return 'Не в сети'
}

function getDeviceNetworkClass(status?: DeviceNetworkStatus) {
  if (status === 'Online') return 'devices-status--green'
  if (status === 'Lost') return 'devices-status--red'

  return 'devices-status--gray'
}

function getDeviceNetworkDotClass(status?: DeviceNetworkStatus) {
  if (status === 'Online') return 'devices-dot--green'
  if (status === 'Lost') return 'devices-dot--red'

  return 'devices-dot--gray'
}

function getOrganisationInitials(name: string) {
  const words = name.trim().split(/\s+/).filter(Boolean)

  if (words.length === 0) return 'ОР'

  return words
    .slice(0, 2)
    .map((word) => word[0])
    .join('')
    .toUpperCase()
}

function formatCreationDate(timestamp?: number) {
  if (!timestamp) return 'Дата создания не указана'

  return `${new Intl.DateTimeFormat('ru-RU', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  }).format(new Date(timestamp))}`
}

function getLogoSrc(logoUrl?: string | null, version = 0) {
  if (!logoUrl) return ''

  if (!version) return logoUrl

  const separator = logoUrl.includes('?') ? '&' : '?'

  return `${logoUrl}${separator}v=${version}`
}

export function OrganisationPage() {
  const { setNavbarBreadcrumbs } =
    useOutletContext<AppLayoutOutletContext>()
  const location = useLocation()
  const employeesBackPath =
    (location.state as { fromEmployeesPath?: string } | null)
      ?.fromEmployeesPath ?? '/employees?section=organisations'
  const [searchParams, setSearchParams] = useSearchParams()
  const navigate = useNavigate()
  const { organisationId } = useParams()
  const [logoVersion, setLogoVersion] = useState(0)

  const [editingOrganisation, setEditingOrganisation] =
    useState<Organisation | null>(null)
  const [deletingOrganisation, setDeletingOrganisation] =
    useState<Organisation | null>(null)
  const [editingEmployee, setEditingEmployee] = useState<Employee | null>(null)
  const [deletingEmployee, setDeletingEmployee] = useState<Employee | null>(null)
  const [isAddEmployeeOpen, setIsAddEmployeeOpen] = useState(false)
  const [isAddDeviceOpen, setIsAddDeviceOpen] = useState(false)
  const renderEditingOrganisation =
    useDeferredModalPayload(editingOrganisation)
  const renderDeletingOrganisation =
    useDeferredModalPayload(deletingOrganisation)
  const renderEditingEmployee = useDeferredModalPayload(editingEmployee)
  const renderDeletingEmployee = useDeferredModalPayload(deletingEmployee)
  const employeesTableRef = useRef<SimpleBarCore | null>(null)
  const devicesTableRef = useRef<SimpleBarCore | null>(null)

  const activeTable = useMemo<OrganisationTable>(() => {
    return searchParams.get('orgTable') === 'devices'
      ? 'devices'
      : 'employees'
  }, [searchParams])

  const employeesCurrentPage = Number(searchParams.get('employeesPage') ?? 0)
  const devicesCurrentPage = Number(searchParams.get('devicesPage') ?? 0)
  const employeeSearch = searchParams.get('employeesQuery') ?? ''
  const deviceSearch = searchParams.get('devicesQuery') ?? ''

  const employeeSort = useMemo(() => {
    return usersSortOptions.find(
      (option) => option.value === searchParams.get('employeesSort'),
    ) ?? usersSortOptions[0]
  }, [searchParams])

  const deviceSort = useMemo(() => {
    return devicesSortOptions.find(
      (option) => option.value === searchParams.get('devicesSort'),
    ) ?? devicesSortOptions[0]
  }, [searchParams])

  const [debouncedEmployeeSearch, setDebouncedEmployeeSearch] = useState('')
  const [debouncedDeviceSearch, setDebouncedDeviceSearch] = useState('')

  const {
    data: organisationData,
    loading: organisationLoading,
    error: organisationError,
    refetch: refetchOrganisation,
  } = useQuery<GetOrganisationData, GetOrganisationVariables>(
    GET_ORGANISATION_QUERY,
    {
      variables: {
        id: organisationId ?? '',
      },
      skip: !organisationId,
      fetchPolicy: 'network-only',
    },
  )

  const [deleteOrganisation, { loading: isDeletingOrganisation }] =
    useMutation<DeleteOrganisationData, DeleteOrganisationVariables>(
      DELETE_ORGANISATION_MUTATION,
    )

  useEffect(() => {
    const timeoutId = window.setTimeout(() => {
      setDebouncedEmployeeSearch(employeeSearch.trim())
    }, 350)

    return () => {
      window.clearTimeout(timeoutId)
    }
  }, [employeeSearch])

  useEffect(() => {
    const timeoutId = window.setTimeout(() => {
      setDebouncedDeviceSearch(deviceSearch.trim())
    }, 350)

    return () => {
      window.clearTimeout(timeoutId)
    }
  }, [deviceSearch])

  const employeesQueryVariables = useMemo<GetUsersVariables>(() => ({
    page: employeesCurrentPage,
    query: debouncedEmployeeSearch || undefined,
    orgs: organisationId ? [organisationId] : undefined,
    roles: undefined,
    sortDirection: employeeSort.sortDirection,
    sortField: employeeSort.sortField,
  }), [
    debouncedEmployeeSearch,
    employeeSort.sortDirection,
    employeeSort.sortField,
    employeesCurrentPage,
    organisationId,
  ])

  const devicesQueryVariables = useMemo<GetPhonesVariables>(() => ({
    page: devicesCurrentPage,
    query: debouncedDeviceSearch || undefined,
    orgs: organisationId ? [organisationId] : undefined,
    sortDirection: deviceSort.sortDirection,
    sortField: deviceSort.sortField,
  }), [
    debouncedDeviceSearch,
    deviceSort.sortDirection,
    deviceSort.sortField,
    devicesCurrentPage,
    organisationId,
  ])

  const {
    data: usersData,
    previousData: previousUsersData,
    loading: usersLoading,
    error: usersError,
    refetch: refetchUsers,
  } = useQuery<GetUsersData, GetUsersVariables>(GET_USERS_QUERY, {
    variables: employeesQueryVariables,
    skip: !organisationId,
    fetchPolicy: 'network-only',
    notifyOnNetworkStatusChange: true,
  })

  const {
    data: devicesData,
    previousData: previousDevicesData,
    loading: devicesLoading,
    error: devicesError,
  } = useQuery<GetPhonesData, GetPhonesVariables>(GET_PHONES_QUERY, {
    variables: devicesQueryVariables,
    skip: !organisationId,
    fetchPolicy: 'network-only',
    notifyOnNetworkStatusChange: true,
    pollInterval: 15000,
  })

  const organisation = organisationData?.getOrganisation ?? null

  useEffect(() => {
    if (!organisation) {
      setNavbarBreadcrumbs([])
      return
    }

    setNavbarBreadcrumbs([{ label: organisation.name }])

    return () => {
      setNavbarBreadcrumbs([])
    }
  }, [organisation, setNavbarBreadcrumbs])

  const usersResponse = usersData?.getUsers ?? previousUsersData?.getUsers
  const employees = usersResponse?.page ?? []
  const employeesTotalPages = usersResponse?.totalPages ?? 0
  const isEmployeesInitialLoading = usersLoading && !usersResponse
  const isEmployeesUpdating = usersLoading && Boolean(usersResponse)
  const shouldShowEmployeesError = Boolean(usersError) && employees.length === 0
  const hasPrevEmployeesPage = employeesCurrentPage > 0
  const hasNextEmployeesPage =
    employeesTotalPages > 0 &&
    employeesCurrentPage < employeesTotalPages - 1
  const employeesPaginationItems = useMemo(
    () => getPaginationItems(employeesCurrentPage, employeesTotalPages),
    [employeesCurrentPage, employeesTotalPages],
  )

  const devicesResponse =
    devicesData?.getPhones ?? previousDevicesData?.getPhones
  const devices = devicesResponse?.page ?? []
  const devicesTotalPages = devicesResponse?.totalPages ?? 0
  const isDevicesInitialLoading = devicesLoading && !devicesResponse
  const isDevicesUpdating = devicesLoading && Boolean(devicesResponse)
  const shouldShowDevicesError = Boolean(devicesError) && devices.length === 0
  const hasPrevDevicesPage = devicesCurrentPage > 0
  const hasNextDevicesPage =
    devicesTotalPages > 0 && devicesCurrentPage < devicesTotalPages - 1
  const devicesPaginationItems = useMemo(
    () => getPaginationItems(devicesCurrentPage, devicesTotalPages),
    [devicesCurrentPage, devicesTotalPages],
  )

  const organisationInitials = useMemo(() => {
    if (!organisation) return 'ОР'

    return getOrganisationInitials(organisation.name)
  }, [organisation])

  const organisationLogoSrc = useMemo(() => {
    return getLogoSrc(organisation?.logoUrl, logoVersion)
  }, [organisation?.logoUrl, logoVersion])

  useEffect(() => {
    const recalculateTables = () => {
      employeesTableRef.current?.recalculate()
      devicesTableRef.current?.recalculate()
    }

    const frameId = window.requestAnimationFrame(recalculateTables)
    const transitionTimerId = window.setTimeout(recalculateTables, 360)

    return () => {
      window.cancelAnimationFrame(frameId)
      window.clearTimeout(transitionTimerId)
    }
  }, [
    activeTable,
    employees.length,
    devices.length,
    isEmployeesInitialLoading,
    isDevicesInitialLoading,
  ])

  const updateEmployeesSearchParams = useCallback((
    updates: Record<string, string | null>,
  ) => {
    setSearchParams(
      (prev) => {
        const next = new URLSearchParams(prev)

        Object.entries(updates).forEach(([key, value]) => {
          if (value === null || value === '') {
            next.delete(key)
            return
          }

          next.set(key, value)
        })

        return next
      },
      {
        replace: true,
      },
    )
  }, [setSearchParams])

  const setEmployeesPage = useCallback((page: number) => {
    updateEmployeesSearchParams({
      employeesPage: page > 0 ? String(page) : null,
    })
  }, [updateEmployeesSearchParams])

  const refetchFirstEmployeesPage = useCallback(async () => {
    updateEmployeesSearchParams({
      employeesPage: null,
    })

    await refetchUsers({
      ...employeesQueryVariables,
      page: 0,
    })
  }, [employeesQueryVariables, refetchUsers, updateEmployeesSearchParams])

  const setActiveTable = useCallback((table: OrganisationTable) => {
    updateEmployeesSearchParams({
      orgTable: table === 'devices' ? 'devices' : null,
    })
  }, [updateEmployeesSearchParams])

  const handleNextEmployeesPage = useCallback(() => {
    if (!hasNextEmployeesPage || usersLoading) return

    setEmployeesPage(employeesCurrentPage + 1)
  }, [employeesCurrentPage, hasNextEmployeesPage, setEmployeesPage, usersLoading])

  const handlePrevEmployeesPage = useCallback(() => {
    if (!hasPrevEmployeesPage || usersLoading) return

    setEmployeesPage(Math.max(0, employeesCurrentPage - 1))
  }, [employeesCurrentPage, hasPrevEmployeesPage, setEmployeesPage, usersLoading])

  const handleJumpPrevEmployeesPage = useCallback(() => {
    if (usersLoading) return

    setEmployeesPage(Math.max(0, employeesCurrentPage - 5))
  }, [employeesCurrentPage, setEmployeesPage, usersLoading])

  const handleJumpNextEmployeesPage = useCallback(() => {
    if (usersLoading) return

    setEmployeesPage(
      Math.min(employeesTotalPages - 1, employeesCurrentPage + 5),
    )
  }, [employeesCurrentPage, employeesTotalPages, setEmployeesPage, usersLoading])

  const setDevicesPage = useCallback((page: number) => {
    updateEmployeesSearchParams({
      devicesPage: page > 0 ? String(page) : null,
    })
  }, [updateEmployeesSearchParams])

  const handleNextDevicesPage = useCallback(() => {
    if (!hasNextDevicesPage || devicesLoading) return

    setDevicesPage(devicesCurrentPage + 1)
  }, [devicesCurrentPage, devicesLoading, hasNextDevicesPage, setDevicesPage])

  const handlePrevDevicesPage = useCallback(() => {
    if (!hasPrevDevicesPage || devicesLoading) return

    setDevicesPage(Math.max(0, devicesCurrentPage - 1))
  }, [devicesCurrentPage, devicesLoading, hasPrevDevicesPage, setDevicesPage])

  const handleJumpPrevDevicesPage = useCallback(() => {
    if (devicesLoading) return

    setDevicesPage(Math.max(0, devicesCurrentPage - 5))
  }, [devicesCurrentPage, devicesLoading, setDevicesPage])

  const handleJumpNextDevicesPage = useCallback(() => {
    if (devicesLoading) return

    setDevicesPage(
      Math.min(devicesTotalPages - 1, devicesCurrentPage + 5),
    )
  }, [devicesCurrentPage, devicesLoading, devicesTotalPages, setDevicesPage])

  const handleConfirmDeleteOrganisation = useCallback(async () => {
    if (!deletingOrganisation) return

    try {
      await deleteOrganisation({
        variables: {
          id: String(deletingOrganisation.id),
        },
      })

      setDeletingOrganisation(null)
      navigate(employeesBackPath, {
        replace: true,
      })
    } catch (error) {
      console.error('Не удалось удалить организацию', error)
    }
  }, [
    deleteOrganisation,
    deletingOrganisation,
    employeesBackPath,
    navigate,
  ])

  const handleConfirmDeleteEmployee = useCallback(() => {
    if (!deletingEmployee) return

    setDeletingEmployee(null)
  }, [deletingEmployee])

  const handleEditOrganisation = useCallback(() => {
    if (!organisation) return

    setEditingOrganisation(organisation)
  }, [organisation])

  const handleDeleteOrganisation = useCallback(() => {
    if (!organisation) return

    setDeletingOrganisation(organisation)
  }, [organisation])

  const handleEmployeeSearchChange = useCallback((value: string) => {
    updateEmployeesSearchParams({
      employeesQuery: value || null,
      employeesPage: null,
    })
  }, [updateEmployeesSearchParams])

  const handleEmployeeSortChange = useCallback((
    option: typeof usersSortOptions[number],
  ) => {
    updateEmployeesSearchParams({
      employeesSort:
        option.value === usersSortOptions[0].value
          ? null
          : option.value,
      employeesPage: null,
    })
  }, [updateEmployeesSearchParams])

  const handleDeviceSearchChange = useCallback((value: string) => {
    updateEmployeesSearchParams({
      devicesQuery: value || null,
      devicesPage: null,
    })
  }, [updateEmployeesSearchParams])

  const handleDeviceSortChange = useCallback((
    option: typeof devicesSortOptions[number],
  ) => {
    updateEmployeesSearchParams({
      devicesSort:
        option.value === devicesSortOptions[0].value
          ? null
          : option.value,
      devicesPage: null,
    })
  }, [updateEmployeesSearchParams])

  const handleOpenAddEmployee = useCallback(() => {
    setIsAddEmployeeOpen(true)
  }, [])

  const handleOpenAddDevice = useCallback(() => {
    setIsAddDeviceOpen(true)
  }, [])

  const handleNoopToggleFilters = useCallback(() => undefined, [])

  const handleEditOrganisationOpenChange = useCallback((open: boolean) => {
    if (!open) {
      setEditingOrganisation(null)
    }
  }, [])

  const handleEditEmployeeOpenChange = useCallback((open: boolean) => {
    if (!open) {
      setEditingEmployee(null)
    }
  }, [])

  const handleDeleteEmployeeOpenChange = useCallback((open: boolean) => {
    if (!open) {
      setDeletingEmployee(null)
    }
  }, [])

  const handleDeleteOrganisationOpenChange = useCallback((open: boolean) => {
    if (!open) {
      setDeletingOrganisation(null)
    }
  }, [])

  const handleEditOrganisationSuccess = useCallback(async () => {
    await refetchOrganisation()
    setLogoVersion((currentVersion) => currentVersion + 1)
  }, [refetchOrganisation])

  const handleShowEmployeesTable = useCallback(() => {
    if (activeTable === 'employees') return

    setActiveTable('employees')
  }, [activeTable, setActiveTable])

  const handleShowDevicesTable = useCallback(() => {
    if (activeTable === 'devices') return

    setActiveTable('devices')
  }, [activeTable, setActiveTable])

  if (!organisationId) {
    return (
      <section className="organisation-page">
        <EmptyState
          className="organisation-page__empty"
          variant="not-found"
          title="Некорректный ID организации"
          description="Проверьте ссылку или вернитесь к списку организаций."
        >
          <Link to="/employees">
            Вернуться к списку
          </Link>
        </EmptyState>
      </section>
    )
  }

  return (
    <section className="organisation-page">
      {organisationLoading && !organisation && (
        <div className="organisation-page__empty">Загрузка организации...</div>
      )}

      {organisationError && (
        <div className="organisation-page__empty organisation-page__empty--error">
          Не удалось загрузить организацию
        </div>
      )}

      {!organisationLoading && !organisationError && !organisation && (
        <EmptyState
          className="organisation-page__empty"
          variant="not-found"
          title="Организация не найдена"
          description="Возможно, организация была удалена или ссылка устарела."
        >
          <Link to="/employees">
            Вернуться к списку
          </Link>
        </EmptyState>
      )}

      {organisation && (
        <>
          <div className="organisation-page__top">
            <div className='organisation-container-info'>
              <div className="organisation-card">
                <div className="organisation-card__main">
                  <div className={`organisation-card__avatar ${organisationLogoSrc ? 'transparent-backdrop' : ''}`} aria-hidden="true">
                    {organisationLogoSrc ? (
                      <img src={organisationLogoSrc} alt="" />
                    ) : (
                      <span>{organisationInitials}</span>
                    )}
                  </div>

                  <div className="organisation-card__info">
                    <h2>
                      {organisation.name}
                    </h2>
                    <p>
                      <span>ID: {organisation.id}</span>, создана {formatCreationDate(organisation.creationDate)}</p>
                    <div className="organisation-card__actions">
                      <button
                        className="organisation-action-btn organisation-action-btn--edit"
                        type="button"
                        onClick={handleEditOrganisation}
                      >
                        <Pencil size={16} />
                        Редактировать
                      </button>

                      <button
                        className="organisation-action-btn organisation-action-btn--delete"
                        type="button"
                        onClick={handleDeleteOrganisation}
                      >
                        <Trash2 size={16} />
                        Удалить
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              <OrganisationPolicyCard organisation={organisation} />
            </div>
            <div className="organisation-tables-card">
              {activeTable === 'employees' ? (
                <EmployeesToolbar
                  addButtonText="Добавить сотрудника"
                  searchValue={employeeSearch}
                  onSearchChange={handleEmployeeSearchChange}
                  sortOptions={usersSortOptions}
                  selectedSort={employeeSort}
                  onSortChange={handleEmployeeSortChange}
                  showSort
                  onAdd={handleOpenAddEmployee}
                />
              ) : (
                <DevicesToolbar
                  isFiltersOpen={false}
                  showFilters={false}
                  onToggleFilters={handleNoopToggleFilters}
                  onAddDevice={handleOpenAddDevice}
                  search={deviceSearch}
                  onSearchChange={handleDeviceSearchChange}
                  sortField={deviceSort.sortField}
                  sortDirection={deviceSort.sortDirection}
                  onSortChange={handleDeviceSortChange}
                />
              )}

              <div className="organisation-tables-carousel">
                <div
                  className={`organisation-tables-track ${
                    activeTable === 'devices' ? 'is-devices' : ''
                  }`}
                >
                  <div className="organisation-table-slide">
                    <div className="employees-table-shadow">
                      <SimpleBar
                        ref={employeesTableRef}
                        className={`organisation-employees-table-card ${
                          isEmployeesUpdating ? 'is-updating' : ''
                        }`}
                      >
                        <RevealContent
                          loading={isEmployeesInitialLoading}
                          fallback={
                            <TableSkeleton
                              className="organisation-employees-table"
                              columns={organisationEmployeesSkeletonColumns}
                            />
                          }
                        >
                          {shouldShowEmployeesError && (
                            <div className="organisation-page__state organisation-page__state--error">
                              Не удалось загрузить сотрудников
                            </div>
                          )}

                          {!usersError && employees.length === 0 && (
                            <EmptyState
                              className="organisation-page__state"
                              variant="no-items"
                              title="Сотрудников пока нет"
                              description="Добавьте сотрудника или привяжите существующего к организации."
                            />
                          )}

                          {employees.length > 0 && (
                            <table className="organisation-employees-table">
                            <thead>
                              <tr>
                                <th>ID</th>
                                <th>ФИО</th>
                                <th>Организация</th>
                                <th>Роль</th>
                                <th></th>
                              </tr>
                            </thead>

                            <tbody>
                              {employees.map((employee) => (
                                <tr key={employee.id}>
                                  <td>{employee.id}</td>

                                  <td>
                                    <div className="organisation-employee-person">
                                      <span>
                                        {getEmployeeFullName(employee) || 'ФИО не указано'}
                                      </span>
                                    </div>
                                  </td>

                                  <td>
                                    <span className="organisation-employee-org">
                                      {employee.org?.name || organisation.name}
                                    </span>
                                  </td>

                                  <td>
                                    <span
                                      className={
                                        employee.role === 'Admin'
                                          ? 'organisation-employee-role organisation-employee-role--admin'
                                          : 'organisation-employee-role'
                                      }
                                    >
                                      {getEmployeeRoleLabel(employee.role)}
                                    </span>
                                  </td>

                                  <td>
                                    <div className="organisation-employee-actions">
                                      <button
                                        className="organisation-employee-action-btn organisation-employee-action-btn--edit"
                                        type="button"
                                        aria-label="Редактировать сотрудника"
                                        title="Редактировать"
                                        onClick={(event) => {
                                          event.stopPropagation()
                                          setEditingEmployee(employee)
                                        }}
                                      >
                                        <Pencil size={16} />
                                      </button>

                                      <button
                                        className="organisation-employee-action-btn organisation-employee-action-btn--delete"
                                        type="button"
                                        aria-label="Удалить сотрудника"
                                        title="Удалить"
                                        onClick={(event) => {
                                          event.stopPropagation()
                                          setDeletingEmployee(employee)
                                        }}
                                      >
                                        <Trash2 size={16} />
                                      </button>
                                    </div>
                                  </td>
                                </tr>
                              ))}
                            </tbody>
                            </table>
                          )}
                        </RevealContent>
                      </SimpleBar>
                    </div>
                  </div>

                  <div className="organisation-table-slide">
                    <div className="employees-table-shadow">
                      <SimpleBar
                        ref={devicesTableRef}
                        className={`organisation-employees-table-card ${
                          isDevicesUpdating ? 'is-updating' : ''
                        }`}
                      >
                        <RevealContent
                          loading={isDevicesInitialLoading}
                          fallback={
                            <TableSkeleton
                              className="organisation-devices-table"
                              columns={organisationDevicesSkeletonColumns}
                            />
                          }
                        >
                          {shouldShowDevicesError && (
                            <div className="organisation-page__state organisation-page__state--error">
                              Не удалось загрузить смартфоны
                            </div>
                          )}

                          {!devicesError && devices.length === 0 && (
                            <EmptyState
                              className="organisation-page__state"
                              variant="no-items"
                              title="Смартфонов пока нет"
                              description="К этой организации пока не прикреплены смартфоны."
                            />
                          )}

                          {devices.length > 0 && (
                            <table className="organisation-devices-table">
                            <thead>
                              <tr>
                                <th>ID</th>
                                <th>Информация</th>
                                <th>Состояние</th>
                                <th>Связь</th>
                                <th>Статусы</th>
                              </tr>
                            </thead>

                            <tbody>
                              {devices.map((device: OrganisationDevice) => (
                                <tr
                                  key={device.id}
                                  className="organisation-devices-table__row"
                                  onClick={() => navigate(`/devices/${device.id}`)}
                                >
                                  <td className="organisation-devices-table__id">
                                    {device.id}
                                  </td>

                                  <td>
                                    <div className="organisation-device-info">
                                      <div className="organisation-device-info__number">
                                        {device.serial || '—'}
                                      </div>

                                      <div className="organisation-device-info__imei">
                                        IMEI: {device.imei || '—'}
                                      </div>

                                      <div className="organisation-device-info__imei">
                                        IMEI 2: {device.imei2 || '—'}
                                      </div>
                                    </div>
                                  </td>

                                  <td>
                                    <div
                                      className={`organisation-device-status ${getDeviceConditionClass(
                                        device.techState?.needMaintenance,
                                      )}`}
                                    >
                                      <span
                                        className={`organisation-device-dot ${getDeviceConditionDotClass(
                                          device.techState?.needMaintenance,
                                        )}`}
                                      />

                                      {getDeviceConditionLabel(
                                        device.techState?.needMaintenance,
                                      )}
                                    </div>
                                  </td>

                                  <td>
                                    <div
                                      className={`organisation-device-status ${getDeviceNetworkClass(
                                        device.networkStatus,
                                      )}`}
                                    >
                                      <span
                                        className={`organisation-device-dot ${getDeviceNetworkDotClass(
                                          device.networkStatus,
                                        )}`}
                                      />

                                      {getDeviceNetworkLabel(device.networkStatus)}
                                    </div>
                                  </td>

                                  <td>
                                    <div className="organisation-device-icons">
                                      <GpsIcon
                                        className={
                                          isPhonePolicyOptionEnabled(
                                            device.policy?.GPS ??
                                              device.policy?.canUseGPS,
                                          )
                                            ? 'is-active'
                                            : ''
                                        }
                                      />

                                      <WifiIcon />

                                      <BluetoothIcon
                                        className={
                                          isPhonePolicyOptionEnabled(
                                            device.policy?.bluetooth ??
                                              device.policy?.canUseBluetooth,
                                          )
                                            ? 'is-active'
                                            : ''
                                        }
                                      />

                                      <Lock
                                        className={
                                          device.policy?.locked
                                            ? 'is-danger'
                                            : ''
                                        }
                                        size={16}
                                      />

                                      <CameraIcon
                                        className={
                                          isPhonePolicyOptionEnabled(
                                            device.policy?.camera ??
                                              device.policy?.canUseCamera,
                                          )
                                            ? 'is-active'
                                            : ''
                                        }
                                      />

                                      <SimIcon
                                        className={
                                          isPhonePolicyOptionEnabled(
                                            device.policy?.sim ??
                                              device.policy?.canUseSim,
                                          )
                                            ? 'is-active'
                                            : ''
                                        }
                                      />

                                      <VolumeIcon />

                                      <Store size={16} />
                                    </div>
                                  </td>
                                </tr>
                              ))}
                            </tbody>
                            </table>
                          )}
                        </RevealContent>
                      </SimpleBar>
                    </div>
                  </div>
                </div>
              </div>

              <div className="organisation-tables-footer">
                <div className="organisation-table-tabs">
                  <button
                    className={activeTable === 'employees' ? 'is-active' : ''}
                    type="button"
                    onClick={handleShowEmployeesTable}
                  >
                    Сотрудники
                  </button>

                  <button
                    className={activeTable === 'devices' ? 'is-active' : ''}
                    type="button"
                    onClick={handleShowDevicesTable}
                  >
                    Смартфоны
                  </button>
                </div>

                <div className="organisation-tables-pagination">
                  {activeTable === 'employees' && employeesTotalPages > 1 && (
                    <EmployeesPagination
                      currentPage={employeesCurrentPage}
                      loading={usersLoading}
                      items={employeesPaginationItems}
                      hasPrevPage={hasPrevEmployeesPage}
                      hasNextPage={hasNextEmployeesPage}
                      onPrev={handlePrevEmployeesPage}
                      onNext={handleNextEmployeesPage}
                      onJumpPrev={handleJumpPrevEmployeesPage}
                      onJumpNext={handleJumpNextEmployeesPage}
                      onPageChange={setEmployeesPage}
                    />
                  )}

                  {activeTable === 'devices' && devicesTotalPages > 1 && (
                    <EmployeesPagination
                      currentPage={devicesCurrentPage}
                      loading={devicesLoading}
                      items={devicesPaginationItems}
                      hasPrevPage={hasPrevDevicesPage}
                      hasNextPage={hasNextDevicesPage}
                      onPrev={handlePrevDevicesPage}
                      onNext={handleNextDevicesPage}
                      onJumpPrev={handleJumpPrevDevicesPage}
                      onJumpNext={handleJumpNextDevicesPage}
                      onPageChange={setDevicesPage}
                    />
                  )}
                </div>
              </div>
            </div>

          </div>



          <AddOrganisationModal
            open={Boolean(editingOrganisation)}
            mode="edit"
            organisation={editingOrganisation ?? renderEditingOrganisation}
            onOpenChange={handleEditOrganisationOpenChange}
            onSuccess={handleEditOrganisationSuccess}
          />

          <AddEmployeeModal
            open={isAddEmployeeOpen}
            mode="create"
            initialOrganisation={{
              id: organisation.id,
              name: organisation.name,
            }}
            onOpenChange={setIsAddEmployeeOpen}
            onSuccess={refetchFirstEmployeesPage}
          />

          <AddEmployeeModal
            open={Boolean(editingEmployee)}
            mode="edit"
            employee={editingEmployee ?? renderEditingEmployee}
            initialOrganisation={{
              id: organisation.id,
              name: organisation.name,
            }}
            onOpenChange={handleEditEmployeeOpenChange}
            onSuccess={refetchFirstEmployeesPage}
          />

          <AddDeviceModal
            open={isAddDeviceOpen}
            onOpenChange={setIsAddDeviceOpen}
          />

          <ConfirmDangerDialog
            open={Boolean(deletingEmployee)}
            title="Удалить сотрудника?"
            description={
              renderDeletingEmployee
                ? `Сотрудник «${getEmployeeFullName(
                    renderDeletingEmployee,
                  )}» будет удалён из системы. Это действие нельзя будет отменить.`
                : ''
            }
            confirmText="Удалить"
            onOpenChange={handleDeleteEmployeeOpenChange}
            onConfirm={handleConfirmDeleteEmployee}
          />

          <ConfirmDangerDialog
            open={Boolean(deletingOrganisation)}
            title="Удалить организацию?"
            description={
              renderDeletingOrganisation
                ? `Организация «${renderDeletingOrganisation.name}» будет удалена из системы. Это действие нельзя будет отменить.`
                : ''
            }
            confirmText="Удалить"
            isLoading={isDeletingOrganisation}
            onOpenChange={handleDeleteOrganisationOpenChange}
            onConfirm={handleConfirmDeleteOrganisation}
          />
        </>
      )}
    </section>
  )
}
