import { useSearchParams } from 'react-router-dom'
import { useCallback, useMemo } from 'react'

import {
  EmployeesTabs,
  type EmployeesSection,
} from './components/EmployeesTabs/EmployeesTabs'
import { UsersSection } from './components/UsersSection/UsersSection'
import { OrganisationsSection } from './components/OrganisationsSection/OrganisationsSection'

import './EmployeesPage.scss'

export function EmployeesPage() {
  const [searchParams, setSearchParams] = useSearchParams()

  const activeSection = useMemo<EmployeesSection>(() => {
    return searchParams.get('section') === 'organisations'
      ? 'organisations'
      : 'users'
  }, [searchParams])

  const handleSectionChange = useCallback((section: EmployeesSection) => {
    if (activeSection === section) return

    setSearchParams(
      (prev) => {
        const next = new URLSearchParams(prev)
        next.set('section', section)

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

  return (
    <section className="employees-page">
      <EmployeesTabs
        activeSection={activeSection}
        onChange={handleSectionChange}
      />

      <div className="employees-page__section">
        {activeSection === 'users' ? (
          <UsersSection />
        ) : (
          <OrganisationsSection />
        )}
      </div>
    </section>
  )
}
