Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

44.4 KB
Raw Blame
import cx from 'clsx'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import _debounce from 'lodash/debounce'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
import {
  TrashIcon,
  PencilIcon,
  PlusIcon,
  MagnifyingGlassIcon,
  ToggleLeftIcon,
  ToggleRightIcon,
  UsersIcon,
  PulseIcon,
  CaretDownIcon,
  CheckIcon,
  XIcon,
  WarningOctagonIcon,
  ArrowCounterClockwiseIcon,
} from '@phosphor-icons/react'
import {
  useState,
  useEffect,
  useMemo,
  useRef,
  useCallback,
  Suspense,
  use,
} from 'react'
import { Trans, useTranslation } from 'react-i18next'
import { Link } from '~/ui/Link'
import {
  useLocation,
  useFetcher,
  useLoaderData,
  useRevalidator,
} from 'react-router'
import { toast } from 'sonner'

import type {
  FeatureFlagsResponse,
  ProjectFeatureFlag,
  FeatureFlagStats,
  FeatureFlagProfile,
  FeatureFlagStaleReason,
  FeatureFlagStatus,
} from '~/api/api.server'
import {
  useFeatureFlagStatsProxy,
  useFeatureFlagProfilesProxy,
} from '~/hooks/useAnalyticsProxy'
import { DOCS_URL } from '~/lib/constants'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
import {
  useViewProjectContext,
  useRefreshTriggers,
} from '~/pages/Project/View/ViewProject'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import type {
  ProjectLoaderData,
  ProjectViewActionData,
} from '~/routes/projects.$id'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'
import Input from '~/ui/Input'
import Spin from '~/ui/icons/Spin'
import LoadingBar from '~/ui/LoadingBar'
import Modal from '~/ui/Modal'
import StatusPage from '~/ui/StatusPage'
import { Switch } from '~/ui/Switch'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
import { nFormatter } from '~/utils/generic'
import { getProfileDisplayName, ProfileAvatar } from '~/utils/profileAvatars'
import routes from '~/utils/routes'

import FeatureFlagSettingsModal from './FeatureFlagSettingsModal'
import { LoaderView } from '../../View/components/LoaderView'

dayjs.extend(relativeTime)

const FEATURE_FLAGS_DOCS_URL = `${DOCS_URL}/analytics-dashboard/feature-flags`
const DEFAULT_FEATURE_FLAGS_TAKE = 20
const DEFAULT_FEATURE_FLAG_PROFILES_TAKE = 15

const STATUS_BADGE: Record<
  FeatureFlagStatus,
  { colour: 'red' | 'yellow' | 'green' | 'slate' | 'sky'; labelKey: string }
> = {
  enabled: { colour: 'green', labelKey: 'featureFlags.enabled' },
  disabled: { colour: 'slate', labelKey: 'featureFlags.disabled' },
  scheduled: { colour: 'sky', labelKey: 'featureFlags.scheduled' },
  killed: { colour: 'red', labelKey: 'featureFlags.killed' },
  stale: { colour: 'yellow', labelKey: 'featureFlags.stale' },
}

const STALE_REASON_LABEL_KEYS: Record<FeatureFlagStaleReason, string> = {
  not_evaluated_recently: 'featureFlags.staleReasonNotEvaluated',
  permanent_rollout: 'featureFlags.staleReasonPermanentRollout',
  targeting_unchanged: 'featureFlags.staleReasonTargetingUnchanged',
  completed_experiment: 'featureFlags.staleReasonCompletedExperiment',
}

interface FeatureFlagProfileRowProps {
  profile: FeatureFlagProfile
  timeFormat: '12-hour' | '24-hour'
}

const FeatureFlagProfileRow = ({
  profile,
  timeFormat,
}: FeatureFlagProfileRowProps) => {
  const {
    t,
    i18n: { language },
  } = useTranslation('common')
  const location = useLocation()

  const displayName = useMemo(() => {
    return getProfileDisplayName(profile.profileId, profile.isIdentified)
  }, [profile.profileId, profile.isIdentified])

  const lastEvaluatedText = useMemo(() => {
    return dayjs(profile.lastEvaluated)
      .toDate()
      .toLocaleDateString(language, {
        day: 'numeric',
        month: 'short',
        hour: 'numeric',
        minute: 'numeric',
        hourCycle: timeFormat === '12-hour' ? 'h12' : 'h23',
      })
  }, [profile.lastEvaluated, language, timeFormat])

  const params = new URLSearchParams(location.search)
  params.set('tab', 'profiles')
  params.set('profileId', profile.profileId)

  return (
    <Link to={{ search: params.toString() }}>
      <li className='relative mb-2 flex cursor-pointer items-center justify-between gap-x-4 overflow-hidden rounded-lg border border-gray-200 bg-white px-3 py-2.5 transition-colors hover:bg-gray-100 dark:border-slate-700/50 dark:bg-slate-900/50 dark:hover:bg-slate-700/50'>
        <div className='flex min-w-0 items-center gap-x-3'>
          {/* Avatar */}
          <ProfileAvatar
            profileId={profile.profileId}
            size={32}
            className='shrink-0'
          />

          <div className='min-w-0 flex-auto'>
            <div className='flex min-w-0 items-center gap-2'>
              <Text size='sm' weight='semibold' truncate>
                {displayName}
              </Text>
              {Boolean(profile.isIdentified) && (
                <Badge
                  label={t('project.identified')}
                  colour='indigo'
                  className='text-[0.625rem] leading-3'
                />
              )}
            </div>
            <Text as='p' size='xs' colour='muted' className='mt-0.5'>
              {t('featureFlags.xEvaluations', {
                count: profile.evaluationCount,
              })}{' '}
              · {lastEvaluatedText}
            </Text>
          </div>
        </div>
        <div className='flex shrink-0 items-center gap-x-2'>
          {/* Result indicator */}
          <Badge
            label={
              <span className='flex items-center gap-1'>
                {profile.lastResult ? (
                  <CheckIcon className='size-3' />
                ) : (
                  <XIcon className='size-3' />
                )}
                {profile.lastResult ? 'true' : 'false'}
              </span>
            }
            colour={profile.lastResult ? 'green' : 'slate'}
            className='text-[0.625rem] leading-3'
          />
        </div>
      </li>
    </Link>
  )
}

interface FeatureFlagRowProps {
  flag: ProjectFeatureFlag
  stats: FeatureFlagStats | null
  statsLoading: boolean
  isExpanded: boolean
  profiles: FeatureFlagProfile[]
  profilesLoading: boolean
  canLoadMoreProfiles: boolean
  resultFilter: boolean
  onDelete: (id: string) => void
  onEdit: (id: string) => void
  onToggle: (id: string, enabled: boolean) => void
  onKill: (id: string) => void
  onReleaseKillSwitch: (id: string) => void
  onToggleExpand: (id: string) => void
  onLoadMoreProfiles: (id: string) => void
  onResultFilterChange: (id: string, filter: boolean) => void
  timeFormat: '12-hour' | '24-hour'
}

const FeatureFlagRow = ({
  flag,
  stats,
  statsLoading,
  isExpanded,
  profiles,
  profilesLoading,
  canLoadMoreProfiles,
  resultFilter,
  onDelete,
  onEdit,
  onToggle,
  onKill,
  onReleaseKillSwitch,
  onToggleExpand,
  onLoadMoreProfiles,
  onResultFilterChange,
  timeFormat,
}: FeatureFlagRowProps) => {
  const {
    t,
    i18n: { language },
  } = useTranslation()
  const location = useLocation()
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const [showKillModal, setShowKillModal] = useState(false)
  const [showReleaseModal, setShowReleaseModal] = useState(false)

  const targetingRulesCount = flag.targetingRules?.length || 0
  const experimentSearch = useMemo(() => {
    if (!flag.experimentId) return ''
    const params = new URLSearchParams(location.search)
    params.set('tab', 'experiments')
    params.set('experimentId', flag.experimentId)
    return params.toString()
  }, [flag.experimentId, location.search])
  const statusMeta = STATUS_BADGE[flag.status] || STATUS_BADGE.disabled
  const scheduledAtText = useMemo(() => {
    if (!flag.scheduledChange?.applyAt) return null

    return dayjs(flag.scheduledChange.applyAt)
      .toDate()
      .toLocaleDateString(language, {
        day: 'numeric',
        month: 'short',
        hour: 'numeric',
        minute: 'numeric',
        hourCycle: timeFormat === '12-hour' ? 'h12' : 'h23',
      })
  }, [flag.scheduledChange?.applyAt, language, timeFormat])
  const scheduledDetails = useMemo(() => {
    const details: string[] = []

    if (!flag.scheduledChange) return ''

    if (flag.scheduledChange.enabled !== undefined) {
      details.push(
        flag.scheduledChange.enabled
          ? t('featureFlags.scheduledEnable')
          : t('featureFlags.scheduledDisable'),
      )
    }

    if (flag.scheduledChange.rolloutPercentage !== undefined) {
      details.push(
        t('featureFlags.scheduledRollout', {
          percentage: flag.scheduledChange.rolloutPercentage,
        }),
      )
    }

    return details.join(', ')
  }, [flag.scheduledChange, t])
  const staleReasons = useMemo(
    () =>
      (flag.staleReasons || [])
        .map((reason) => t(STALE_REASON_LABEL_KEYS[reason] || reason))
        .join(', '),
    [flag.staleReasons, t],
  )
  const toggleActionLabel = flag.enabled
    ? t('featureFlags.disable')
    : t('featureFlags.enable')
  const killSwitchActionLabel = flag.killSwitchActive
    ? t('featureFlags.releaseKillSwitch')
    : t('featureFlags.killSwitch')

  return (
    <>
      <li className='relative mb-2 overflow-hidden rounded-lg border border-gray-200 bg-gray-50 transition-colors dark:border-slate-800/60 dark:bg-slate-900/25'>
        {/* Main row - clickable to expand */}
        <div
          onClick={() => onToggleExpand(flag.id)}
          onKeyDown={(e) => {
            if (e.target !== e.currentTarget) return
            if (e.key === 'Enter' || e.key === ' ') {
              e.preventDefault()
              onToggleExpand(flag.id)
            }
          }}
          // eslint-disable-next-line jsx-a11y/prefer-tag-over-role -- contains nested interactive elements
          role='button'
          tabIndex={0}
          className='flex cursor-pointer justify-between gap-x-4 px-4 py-3 transition-colors hover:bg-gray-200/70 sm:px-5 dark:hover:bg-slate-900/60'
        >
          <div className='flex min-w-0 gap-x-4'>
            <div className='min-w-0 flex-auto'>
              <div className='flex items-center gap-x-2'>
                <Text
                  as='p'
                  weight='semibold'
                  truncate
                  className='flex items-center gap-x-1.5'
                >
                  <ToggleRightIcon className='size-4 text-indigo-600 dark:text-indigo-500' />
                  <span>{flag.key}</span>
                </Text>
                {flag.status !== 'enabled' ? (
                  <Badge
                    label={t(statusMeta.labelKey)}
                    colour={statusMeta.colour}
                    className='text-[0.625rem] leading-3'
                  />
                ) : null}
                {flag.status !== 'stale' && flag.staleReasons?.length > 0 ? (
                  <Badge
                    label={t('featureFlags.stale')}
                    colour='yellow'
                    className='text-[0.625rem] leading-3'
                  />
                ) : null}
                {flag.flagType === 'rollout' ? (
                  <Badge
                    label={`${flag.rolloutPercentage}%`}
                    colour='sky'
                    className='text-[0.625rem] leading-3'
                  />
                ) : null}
                {flag.experimentId ? (
                  <Link
                    to={{ search: experimentSearch }}
                    onClick={(event) => event.stopPropagation()}
                    className='inline-flex'
                  >
                    <Badge
                      label={t('featureFlags.experimentLinked')}
                      colour='indigo'
                      className='text-[0.625rem] leading-3'
                    />
                  </Link>
                ) : null}
              </div>
              {flag.description ? (
                <Text className='mt-1' as='p' size='sm' colour='secondary'>
                  {flag.description}
                </Text>
              ) : null}
              {flag.experimentId ? (
                <Text className='mt-1' as='p' size='xs' colour='muted'>
                  {t('featureFlags.experimentLinkedHint')}
                </Text>
              ) : null}
              {flag.killSwitchActive ? (
                <Text className='mt-1' as='p' size='xs' colour='error'>
                  {t('featureFlags.killSwitchActiveHint', {
                    value: flag.killSwitchValue ? 'true' : 'false',
                  })}
                </Text>
              ) : null}
              {flag.scheduledChange && scheduledAtText ? (
                <Text className='mt-1' as='p' size='xs' colour='muted'>
                  {t('featureFlags.scheduledFor', {
                    date: scheduledAtText,
                  })}
                  {scheduledDetails
                    ? ` · ${t('featureFlags.scheduledChangeSummary', {
                        details: scheduledDetails,
                      })}`
                    : ''}
                </Text>
              ) : null}
              {staleReasons ? (
                <Text className='mt-1' as='p' size='xs' colour='muted'>
                  {t('featureFlags.staleReasons', {
                    reasons: staleReasons,
                  })}
                </Text>
              ) : null}
              {targetingRulesCount > 0 ? (
                <Text className='mt-1' as='p' size='xs' colour='muted'>
                  {t('featureFlags.targetingRulesCount', {
                    count: targetingRulesCount,
                  })}
                </Text>
              ) : null}
              {/* Mobile stats */}
              <div className='mt-2 flex h-9 items-center gap-x-3 text-xs leading-5 text-gray-500 sm:hidden dark:text-gray-300'>
                {statsLoading ? (
                  <div className='flex size-9 items-center justify-center'>
                    <Spin className='m-0 size-5' />
                  </div>
                ) : stats ? (
                  <>
                    <span className='flex items-center gap-1'>
                      <PulseIcon className='size-3' />
                      {nFormatter(stats.evaluations, 1)}{' '}
                      {t('featureFlags.evaluations').toLowerCase()}
                    </span>
                    <span className='flex items-center gap-1'>
                      <UsersIcon className='size-3' />
                      {nFormatter(stats.profileCount, 1)}
                    </span>
                  </>
                ) : (
                  <Text as='p' size='xs' colour='muted'>
                    {t('featureFlags.noStats')}
                  </Text>
                )}
              </div>
            </div>
          </div>
          <div className='flex shrink-0 items-center gap-x-4'>
            {/* Desktop stats */}
            <div className='hidden h-11 sm:flex sm:items-center sm:gap-x-4'>
              {statsLoading ? (
                <div className='flex size-11 items-center justify-center'>
                  <Spin className='m-0 size-5' />
                </div>
              ) : stats ? (
                <>
                  <div className='flex flex-col items-end'>
                    <Text as='p' size='sm' weight='semibold'>
                      {nFormatter(stats.evaluations, 1)}
                    </Text>
                    <Text as='p' size='xs' colour='muted'>
                      {t('featureFlags.evaluations')}
                    </Text>
                  </div>
                  <div className='flex flex-col items-end'>
                    <Text as='p' size='sm' weight='semibold'>
                      {nFormatter(stats.profileCount, 1)}
                    </Text>
                    <Text as='p' size='xs' colour='muted'>
                      {t('featureFlags.users')}
                    </Text>
                  </div>
                  <div className='flex flex-col items-end'>
                    <Text
                      as='p'
                      size='sm'
                      weight='semibold'
                      className='text-green-600 dark:text-green-400'
                    >
                      {stats.truePercentage}%
                    </Text>
                    <Text as='p' size='xs' colour='muted'>
                      {t('featureFlags.trueRate')}
                    </Text>
                  </div>
                </>
              ) : (
                <Text as='p' size='sm' colour='muted'>
                  {t('featureFlags.noStats')}
                </Text>
              )}
            </div>
            <div className='flex items-center gap-1'>
              <Tooltip
                text={toggleActionLabel}
                ariaLabel={toggleActionLabel}
                asChild
                disableHoverableContent
                tooltipNode={
                  <button
                    type='button'
                    aria-disabled={flag.killSwitchActive}
                    onClick={(e) => {
                      e.preventDefault()
                      e.stopPropagation()
                      if (flag.killSwitchActive) return
                      onToggle(flag.id, !flag.enabled)
                    }}
                    aria-label={toggleActionLabel}
                    className={cx(
                      'inline-flex size-8 items-center justify-center rounded-md border border-transparent transition-colors aria-disabled:cursor-not-allowed aria-disabled:opacity-40',
                      flag.enabled
                        ? 'text-green-600 hover:border-green-300 hover:bg-green-50 dark:text-green-400 hover:dark:border-green-700/80 dark:hover:bg-green-900/30'
                        : 'text-gray-400 hover:border-gray-300 hover:bg-gray-50 dark:text-gray-500 hover:dark:border-slate-700/80 dark:hover:bg-slate-900',
                    )}
                  >
                    {flag.enabled ? (
                      <ToggleRightIcon className='size-5' aria-hidden />
                    ) : (
                      <ToggleLeftIcon className='size-5' aria-hidden />
                    )}
                  </button>
                }
              />
              <Tooltip
                text={killSwitchActionLabel}
                ariaLabel={killSwitchActionLabel}
                asChild
                disableHoverableContent
                tooltipNode={
                  <button
                    type='button'
                    onClick={(e) => {
                      e.preventDefault()
                      e.stopPropagation()
                      if (flag.killSwitchActive) {
                        setShowReleaseModal(true)
                      } else {
                        setShowKillModal(true)
                      }
                    }}
                    aria-label={killSwitchActionLabel}
                    className={cx(
                      'inline-flex size-8 items-center justify-center rounded-md border border-transparent transition-colors',
                      flag.killSwitchActive
                        ? 'text-sky-600 hover:border-sky-300 hover:bg-sky-50 dark:text-sky-300 hover:dark:border-sky-700/80 dark:hover:bg-sky-900/30'
                        : 'text-red-600 hover:border-red-300 hover:bg-red-50 dark:text-red-400 hover:dark:border-red-700/80 dark:hover:bg-red-900/30',
                    )}
                  >
                    {flag.killSwitchActive ? (
                      <ArrowCounterClockwiseIcon
                        className='size-4'
                        aria-hidden
                      />
                    ) : (
                      <WarningOctagonIcon className='size-4' aria-hidden />
                    )}
                  </button>
                }
              />
              <Tooltip
                text={t('common.edit')}
                ariaLabel={t('common.edit')}
                asChild
                disableHoverableContent
                tooltipNode={
                  <button
                    type='button'
                    onClick={(e) => {
                      e.preventDefault()
                      e.stopPropagation()
                      onEdit(flag.id)
                    }}
                    aria-label={t('common.edit')}
                    className='inline-flex size-8 items-center justify-center rounded-md border border-transparent text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-400 hover:dark:border-slate-700/80 dark:hover:bg-slate-900 dark:hover:text-slate-300'
                  >
                    <PencilIcon className='size-4' aria-hidden />
                  </button>
                }
              />
              <Tooltip
                text={t('common.delete')}
                ariaLabel={t('common.delete')}
                asChild
                disableHoverableContent
                tooltipNode={
                  <button
                    type='button'
                    onClick={(e) => {
                      e.preventDefault()
                      e.stopPropagation()
                      setShowDeleteModal(true)
                    }}
                    aria-label={t('common.delete')}
                    className='inline-flex size-8 items-center justify-center rounded-md border border-transparent text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-400 hover:dark:border-slate-700/80 dark:hover:bg-slate-900 dark:hover:text-slate-300'
                  >
                    <TrashIcon className='size-4' aria-hidden />
                  </button>
                }
              />
              <CaretDownIcon
                className={cx(
                  'size-5 text-gray-500 transition-transform dark:text-gray-400',
                  {
                    'rotate-180': isExpanded,
                  },
                )}
              />
            </div>
          </div>
        </div>

        {/* Expanded profiles section */}
        {isExpanded ? (
          <div className='border-t border-gray-200 px-4 py-3 sm:px-5 dark:border-slate-700'>
            {/* Result filter toggle */}
            <div className='mb-3 flex items-center gap-2'>
              <Switch
                checked={resultFilter}
                onChange={(checked) => onResultFilterChange(flag.id, checked)}
              />
              <Text as='span' size='xs' colour='muted'>
                {t('featureFlags.served')}
              </Text>
            </div>

            {profilesLoading && profiles.length === 0 ? (
              <div className='flex h-[120px] items-center justify-center'>
                <Spin className='size-8' />
              </div>
            ) : profiles.length === 0 ? (
              <div className='flex h-[120px] items-center justify-center'>
                <Text as='p' colour='muted'>
                  {t('featureFlags.noProfiles')}
                </Text>
              </div>
            ) : (
              <>
                <ul>
                  {_map(profiles, (profile) => (
                    <FeatureFlagProfileRow
                      key={profile.profileId}
                      profile={profile}
                      timeFormat={timeFormat}
                    />
                  ))}
                </ul>
                <InfiniteScrollTrigger
                  hasMore={canLoadMoreProfiles}
                  isLoading={profilesLoading}
                  onLoadMore={() => onLoadMoreProfiles(flag.id)}
                  disabled={profilesLoading}
                />
              </>
            )}
          </div>
        ) : null}
      </li>
      <Modal
        onClose={() => setShowDeleteModal(false)}
        onSubmit={() => {
          onDelete(flag.id)
          setShowDeleteModal(false)
        }}
        submitText={t('featureFlags.delete')}
        closeText={t('common.close')}
        title={t('featureFlags.deleteConfirmTitle')}
        message={t('featureFlags.deleteConfirmMessage')}
        submitType='danger'
        type='error'
        isOpened={showDeleteModal}
      />
      <Modal
        onClose={() => setShowKillModal(false)}
        onSubmit={() => {
          onKill(flag.id)
          setShowKillModal(false)
        }}
        submitText={t('featureFlags.killSwitchSubmit')}
        closeText={t('common.close')}
        title={t('featureFlags.killSwitchConfirmTitle')}
        message={t('featureFlags.killSwitchConfirmMessage')}
        submitType='danger'
        type='warning'
        isOpened={showKillModal}
      />
      <Modal
        onClose={() => setShowReleaseModal(false)}
        onSubmit={() => {
          onReleaseKillSwitch(flag.id)
          setShowReleaseModal(false)
        }}
        submitText={t('featureFlags.releaseKillSwitchSubmit')}
        closeText={t('common.close')}
        title={t('featureFlags.releaseKillSwitchConfirmTitle')}
        message={t('featureFlags.releaseKillSwitchConfirmMessage')}
        type='info'
        isOpened={showReleaseModal}
      />
    </>
  )
}

interface FeatureFlagsViewProps {
  period: string
  from?: string
  to?: string
  timezone?: string
}

interface DeferredFeatureFlagsData {
  featureFlagsData: FeatureFlagsResponse | null
}

function FeatureFlagsDataResolver({
  children,
}: {
  children: (data: DeferredFeatureFlagsData) => React.ReactNode
}) {
  const { featureFlagsData: featureFlagsDataPromise } =
    useLoaderData<ProjectLoaderData>()
  const featureFlagsData = featureFlagsDataPromise
    ? use(featureFlagsDataPromise)
    : null
  return <>{children({ featureFlagsData })}</>
}

function FeatureFlagsViewWrapper(props: FeatureFlagsViewProps) {
  return (
    <Suspense fallback={<LoaderView />}>
      <FeatureFlagsDataResolver>
        {(deferredData) => (
          <FeatureFlagsViewInner {...props} deferredData={deferredData} />
        )}
      </FeatureFlagsDataResolver>
    </Suspense>
  )
}

interface FeatureFlagsViewInnerProps extends FeatureFlagsViewProps {
  deferredData: DeferredFeatureFlagsData
}

const FeatureFlagsViewInner = ({
  period,
  from = '',
  to = '',
  timezone,
  deferredData,
}: FeatureFlagsViewInnerProps) => {
  const { id } = useCurrentProject()
  const revalidator = useRevalidator()
  const { featureFlagsRefreshTrigger } = useRefreshTriggers()
  const { timeFormat } = useViewProjectContext()
  const { t } = useTranslation()
  const listFetcher = useFetcher<ProjectViewActionData>()
  const actionFetcher = useFetcher<ProjectViewActionData>()

  // Track if we're in search/pagination mode (not using loader data)
  const [isSearchMode, setIsSearchMode] = useState(false)
  const [total, setTotal] = useState(
    () => deferredData.featureFlagsData?.total || 0,
  )
  const [flags, setFlags] = useState<ProjectFeatureFlag[]>(
    () => deferredData.featureFlagsData?.results || [],
  )
  const [flagStats, setFlagStats] = useState<
    Record<string, FeatureFlagStats | null>
  >({})
  const [statsLoading, setStatsLoading] = useState<Record<string, boolean>>({})
  const [error, setError] = useState<string | null>(null)
  const [filterQuery, setFilterQuery] = useState('')
  const processedActionRef = useRef<string | null>(null)
  const flagsRequestModeRef = useRef<'replace' | 'append'>('replace')

  const isMountedRef = useRef(true)

  // Expanded flag state
  const [expandedFlagId, setExpandedFlagId] = useState<string | null>(null)
  const [flagProfiles, setFlagProfiles] = useState<
    Record<string, FeatureFlagProfile[]>
  >({})
  const [flagProfilesTotal, setFlagProfilesTotal] = useState<
    Record<string, number>
  >({})
  const [profilesLoading, setProfilesLoading] = useState<
    Record<string, boolean>
  >({})
  const [flagResultFilters, setFlagResultFilters] = useState<
    Record<string, boolean>
  >({})

  // Modal state
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [editingFlagId, setEditingFlagId] = useState<string | null>(null)

  const isLoading =
    revalidator.state === 'loading' || listFetcher.state !== 'idle'

  // Cleanup on unmount
  useEffect(() => {
    isMountedRef.current = true
    return () => {
      isMountedRef.current = false
    }
  }, [])

  // Sync state when loader provides new data
  useEffect(() => {
    if (
      deferredData.featureFlagsData &&
      revalidator.state === 'idle' &&
      !isSearchMode
    ) {
      setFlags(deferredData.featureFlagsData.results || [])
      setTotal(deferredData.featureFlagsData.total || 0)
    }
  }, [revalidator.state, deferredData.featureFlagsData, isSearchMode])

  const loadFlags = useCallback(
    (
      take: number,
      skip: number,
      search?: string,
      mode: 'replace' | 'append' = 'replace',
    ) => {
      if (listFetcher.state !== 'idle') {
        return
      }
      flagsRequestModeRef.current = mode
      setIsSearchMode(true)

      listFetcher.submit(
        {
          intent: 'get-project-feature-flags',
          take: String(take),
          skip: String(skip),
          search: search || '',
        },
        { method: 'POST' },
      )
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [listFetcher.submit],
  )

  // Handle list fetcher response
  useEffect(() => {
    if (
      listFetcher.data?.intent === 'get-project-feature-flags' &&
      listFetcher.state === 'idle'
    ) {
      if (isMountedRef.current) {
        if (listFetcher.data.success && listFetcher.data.data) {
          const result = listFetcher.data.data as {
            results: ProjectFeatureFlag[]
            total: number
          }
          if (flagsRequestModeRef.current === 'append') {
            setFlags((prev) => {
              const existingIds = new Set(prev.map((flag) => flag.id))
              const uniqueFlags = result.results.filter(
                (flag) => !existingIds.has(flag.id),
              )
              return [...prev, ...uniqueFlags]
            })
          } else {
            setFlags(result.results)
          }
          setTotal(result.total)
          setError(null)
        } else if (listFetcher.data.error) {
          setError(listFetcher.data.error)
        }
      }
    }
  }, [listFetcher.data, listFetcher.state])

  // Handle action fetcher responses (delete, update)
  useEffect(() => {
    if (!actionFetcher.data || actionFetcher.state !== 'idle') return

    const actionKey = `${actionFetcher.data.intent}-${JSON.stringify(actionFetcher.data.data)}`
    if (processedActionRef.current === actionKey) return
    processedActionRef.current = actionKey

    if (actionFetcher.data.intent === 'delete-feature-flag') {
      if (actionFetcher.data.success) {
        toast.success(t('featureFlags.deleted'))
        loadFlags(
          Math.max(flags.length, DEFAULT_FEATURE_FLAGS_TAKE),
          0,
          filterQuery || undefined,
        )
      } else if (actionFetcher.data.error) {
        toast.error(actionFetcher.data.error)
      }
    } else if (actionFetcher.data.intent === 'update-feature-flag') {
      if (actionFetcher.data.success && actionFetcher.data.data) {
        const updated = actionFetcher.data.data as ProjectFeatureFlag
        toast.success(
          updated.enabled
            ? t('featureFlags.flagEnabled')
            : t('featureFlags.flagDisabled'),
        )
        setFlags((prev) => prev.map((f) => (f.id === updated.id ? updated : f)))
      } else if (actionFetcher.data.error) {
        toast.error(actionFetcher.data.error)
      }
    } else if (actionFetcher.data.intent === 'kill-feature-flag') {
      if (actionFetcher.data.success && actionFetcher.data.data) {
        const updated = actionFetcher.data.data as ProjectFeatureFlag
        toast.success(t('featureFlags.killSwitchActivated'))
        setFlags((prev) => prev.map((f) => (f.id === updated.id ? updated : f)))
      } else if (actionFetcher.data.error) {
        toast.error(actionFetcher.data.error)
      }
    } else if (
      actionFetcher.data.intent === 'release-feature-flag-kill-switch'
    ) {
      if (actionFetcher.data.success && actionFetcher.data.data) {
        const updated = actionFetcher.data.data as ProjectFeatureFlag
        toast.success(t('featureFlags.killSwitchReleased'))
        setFlags((prev) => prev.map((f) => (f.id === updated.id ? updated : f)))
      } else if (actionFetcher.data.error) {
        toast.error(actionFetcher.data.error)
      }
    }
  }, [
    actionFetcher.data,
    actionFetcher.state,
    t,
    loadFlags,
    flags.length,
    filterQuery,
  ])

  // Debounced search to avoid excessive API calls
  const debouncedLoadFlags = useMemo(
    () =>
      _debounce((search: string) => {
        loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, 0, search || undefined)
      }, 300),
    [loadFlags],
  )

  // Handle search input change
  const handleSearchChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = e.target.value
      setFilterQuery(value)
      debouncedLoadFlags(value)
    },
    [debouncedLoadFlags],
  )

  // Cleanup debounce on unmount
  useEffect(() => {
    return () => {
      debouncedLoadFlags.cancel()
    }
  }, [debouncedLoadFlags])

  // Proxy hooks for stats and profiles
  const statsProxy = useFeatureFlagStatsProxy()
  const profilesProxy = useFeatureFlagProfilesProxy()

  const loadFlagStats = useCallback(
    async (flagId: string) => {
      setStatsLoading((prev) => ({ ...prev, [flagId]: true }))
      try {
        const stats = await statsProxy.fetchStats(flagId, {
          period,
          from,
          to,
          timezone,
        })
        if (isMountedRef.current) {
          setFlagStats((prev) => ({ ...prev, [flagId]: stats }))
        }
      } catch (err) {
        console.error('Failed to load flag stats:', err)
        if (isMountedRef.current) {
          setFlagStats((prev) => ({ ...prev, [flagId]: null }))
        }
      } finally {
        if (isMountedRef.current) {
          setStatsLoading((prev) => ({ ...prev, [flagId]: false }))
        }
      }
    },
    [period, from, to, timezone, statsProxy],
  )

  const loadFlagProfiles = useCallback(
    async (
      flagId: string,
      append = false,
      resultFilter?: boolean,
      options: { take?: number; limit?: number } = {},
    ) => {
      const existingProfiles = flagProfiles[flagId] || []
      const currentProfiles = append ? existingProfiles : []
      const skip = append ? currentProfiles.length : 0
      const filter = resultFilter ?? flagResultFilters[flagId] ?? true
      const apiFilter = filter ? 'true' : 'false'

      setProfilesLoading((prev) => ({ ...prev, [flagId]: true }))
      try {
        const result = await profilesProxy.fetchProfiles(flagId, {
          period,
          from,
          to,
          timezone,
          take: options.take || DEFAULT_FEATURE_FLAG_PROFILES_TAKE,
          skip,
          resultFilter: apiFilter,
        })
        if (isMountedRef.current && result) {
          const visibleProfiles =
            typeof options.limit === 'number'
              ? result.profiles.slice(0, options.limit)
              : result.profiles

          setFlagProfiles((prev) => ({
            ...prev,
            [flagId]: append
              ? [...currentProfiles, ...visibleProfiles]
              : visibleProfiles,
          }))
          setFlagProfilesTotal((prev) => ({ ...prev, [flagId]: result.total }))
        }
      } catch (err) {
        console.error('Failed to load flag profiles:', err)
        if (isMountedRef.current) {
          setFlagProfiles((prev) => ({
            ...prev,
            [flagId]: append ? currentProfiles : [],
          }))
          setFlagProfilesTotal((prev) => ({ ...prev, [flagId]: 0 }))
        }
      } finally {
        if (isMountedRef.current) {
          setProfilesLoading((prev) => ({ ...prev, [flagId]: false }))
        }
      }
    },
    [
      period,
      from,
      to,
      timezone,
      flagProfiles,
      flagResultFilters,
      profilesProxy,
    ],
  )

  const handleToggleExpand = useCallback(
    (flagId: string) => {
      if (expandedFlagId === flagId) {
        setExpandedFlagId(null)
      } else {
        setExpandedFlagId(flagId)
        if (!flagProfiles[flagId] && !profilesLoading[flagId]) {
          setFlagResultFilters((prev) => ({ ...prev, [flagId]: true }))
          loadFlagProfiles(flagId, false, true)
        }
      }
    },
    [expandedFlagId, flagProfiles, profilesLoading, loadFlagProfiles],
  )

  const handleLoadMoreProfiles = useCallback(
    (flagId: string) => {
      loadFlagProfiles(flagId, true)
    },
    [loadFlagProfiles],
  )

  const handleResultFilterChange = useCallback(
    (flagId: string, filter: boolean) => {
      setFlagResultFilters((prev) => ({ ...prev, [flagId]: filter }))
      setFlagProfiles((prev) => ({ ...prev, [flagId]: [] }))
      loadFlagProfiles(flagId, false, filter)
    },
    [loadFlagProfiles],
  )

  // Refresh feature flags data when refresh button is clicked
  useEffect(() => {
    if (featureFlagsRefreshTrigger > 0) {
      loadFlags(
        Math.max(flags.length, DEFAULT_FEATURE_FLAGS_TAKE),
        0,
        filterQuery || undefined,
      )
      setFlagStats({})
      if (expandedFlagId) {
        setFlagProfiles((prev) => ({ [expandedFlagId]: prev[expandedFlagId] }))
        const limit = Math.max(
          flagProfiles[expandedFlagId]?.length || 0,
          DEFAULT_FEATURE_FLAG_PROFILES_TAKE,
        )
        loadFlagProfiles(expandedFlagId, false, undefined, {
          take: limit,
          limit,
        })
      } else {
        setFlagProfiles({})
        setFlagProfilesTotal({})
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [featureFlagsRefreshTrigger])

  useEffect(() => {
    flags.forEach((flag) => {
      loadFlagStats(flag.id)
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [flags, period, from, to, timezone])

  useEffect(() => {
    if (expandedFlagId && flagProfiles[expandedFlagId]) {
      loadFlagProfiles(expandedFlagId)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [period, from, to, timezone])

  const handleNewFlag = () => {
    setEditingFlagId(null)
    setIsModalOpen(true)
  }

  const handleEditFlag = (flagId: string) => {
    setEditingFlagId(flagId)
    setIsModalOpen(true)
  }

  const handleCloseModal = () => {
    setIsModalOpen(false)
    setEditingFlagId(null)
  }

  const handleModalSuccess = () => {
    loadFlags(
      Math.max(flags.length, DEFAULT_FEATURE_FLAGS_TAKE),
      0,
      filterQuery || undefined,
    )
  }

  const handleDeleteFlag = useCallback(
    (flagId: string) => {
      processedActionRef.current = null
      actionFetcher.submit(
        { intent: 'delete-feature-flag', flagId },
        { method: 'POST' },
      )
    },
    [actionFetcher],
  )

  const handleToggleFlag = useCallback(
    (flagId: string, enabled: boolean) => {
      processedActionRef.current = null
      actionFetcher.submit(
        { intent: 'update-feature-flag', flagId, enabled: String(enabled) },
        { method: 'POST' },
      )
    },
    [actionFetcher],
  )

  const handleKillFlag = useCallback(
    (flagId: string) => {
      processedActionRef.current = null
      actionFetcher.submit(
        {
          intent: 'kill-feature-flag',
          flagId,
          killSwitchValue: 'false',
        },
        { method: 'POST' },
      )
    },
    [actionFetcher],
  )

  const handleReleaseKillSwitch = useCallback(
    (flagId: string) => {
      processedActionRef.current = null
      actionFetcher.submit(
        { intent: 'release-feature-flag-kill-switch', flagId },
        { method: 'POST' },
      )
    },
    [actionFetcher],
  )

  const canLoadMoreFlags = flags.length < total
  const loadMoreFlags = useCallback(() => {
    if (isLoading || !canLoadMoreFlags) {
      return
    }

    loadFlags(
      DEFAULT_FEATURE_FLAGS_TAKE,
      flags.length,
      filterQuery || undefined,
      'append',
    )
  }, [canLoadMoreFlags, filterQuery, flags.length, isLoading, loadFlags])

  if (error && !isLoading) {
    return (
      <StatusPage
        type='error'
        title={t('apiNotifications.somethingWentWrong')}
        description={t('apiNotifications.errorCode', { error })}
        actions={[
          {
            label: t('dashboard.reloadPage'),
            onClick: () => window.location.reload(),
            primary: true,
          },
          { label: t('notFoundPage.support'), to: routes.contact },
        ]}
      />
    )
  }

  return (
    <>
      <DashboardHeader showLiveVisitors />
      <div>
        {isLoading && !_isEmpty(flags) ? <LoadingBar /> : null}
        {_isEmpty(flags) && !filterQuery ? (
          <div className='mx-auto w-full max-w-2xl py-16 text-center'>
            <div className='mx-auto mb-6 flex size-14 items-center justify-center rounded-xl bg-gray-100 dark:bg-slate-900'>
              <ToggleRightIcon className='size-7 text-gray-700 dark:text-gray-200' />
            </div>
            <Text as='h3' size='xl' weight='medium' className='tracking-tight'>
              {t('featureFlags.title')}
            </Text>
            <Text
              as='p'
              size='sm'
              colour='secondary'
              className='mx-auto mt-2 max-w-md whitespace-pre-wrap'
            >
              <Trans
                t={t}
                i18nKey='featureFlags.description'
                components={{
                  docs: (
                    <a
                      href={FEATURE_FLAGS_DOCS_URL}
                      aria-label={t('ariaLabels.openFeatureFlagsGuide')}
                      className='font-medium underline decoration-dashed hover:decoration-solid'
                      target='_blank'
                      rel='noreferrer noopener'
                    />
                  ),
                }}
              />
            </Text>
            <div className='mt-6'>
              <Button size='lg' onClick={handleNewFlag}>
                <PlusIcon className='mr-1.5 size-4' />
                {t('featureFlags.add')}
              </Button>
            </div>
          </div>
        ) : (
          <>
            {/* Header with filter and add button */}
            <div className='mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between'>
              <Input
                type='search'
                aria-label={t('featureFlags.filterFlags')}
                placeholder={t('featureFlags.filterFlags')}
                value={filterQuery}
                onChange={handleSearchChange}
                className='sm:w-64'
                leadingIcon={<MagnifyingGlassIcon className='size-4' />}
              />
              <Button onClick={handleNewFlag}>
                <PlusIcon className='mr-1.5 size-4' />
                {t('featureFlags.addFlag')}
              </Button>
            </div>

            {/* Flags list */}
            <ul className='mt-4'>
              {_map(flags, (flag) => {
                const profiles = flagProfiles[flag.id] || []
                const profilesTotal = flagProfilesTotal[flag.id] || 0
                const canLoadMore = profiles.length < profilesTotal

                return (
                  <FeatureFlagRow
                    key={flag.id}
                    flag={flag}
                    stats={flagStats[flag.id] || null}
                    statsLoading={statsLoading[flag.id] || false}
                    isExpanded={expandedFlagId === flag.id}
                    profiles={profiles}
                    profilesLoading={profilesLoading[flag.id] || false}
                    canLoadMoreProfiles={canLoadMore}
                    resultFilter={flagResultFilters[flag.id] ?? true}
                    onDelete={handleDeleteFlag}
                    onEdit={handleEditFlag}
                    onToggle={handleToggleFlag}
                    onKill={handleKillFlag}
                    onReleaseKillSwitch={handleReleaseKillSwitch}
                    onToggleExpand={handleToggleExpand}
                    onLoadMoreProfiles={handleLoadMoreProfiles}
                    onResultFilterChange={handleResultFilterChange}
                    timeFormat={timeFormat}
                  />
                )
              })}
            </ul>

            {_isEmpty(flags) && filterQuery ? (
              <Text
                as='p'
                size='sm'
                colour='muted'
                className='py-8 text-center'
              >
                {t('featureFlags.noFlagsMatchFilter')}
              </Text>
            ) : null}
          </>
        )}
        <InfiniteScrollTrigger
          hasMore={canLoadMoreFlags}
          isLoading={isLoading}
          onLoadMore={loadMoreFlags}
          disabled={isLoading}
          className='mt-2'
        />

        <FeatureFlagSettingsModal
          isOpen={isModalOpen}
          onClose={handleCloseModal}
          onSuccess={handleModalSuccess}
          projectId={id}
          flagId={editingFlagId}
        />
      </div>
    </>
  )
}

const FeatureFlagsView = FeatureFlagsViewWrapper

export default FeatureFlagsView