import { useEffect, useRef, useCallback, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { queryOptions } from '@tanstack/react-query'
import { api } from '@/lib/api-client'
import { usePOSStore } from '@/stores/pos.store'
import { useStationStore } from '@/stores/station.store'
import { moduleListOptions } from '@/api/modules'
import { currentDrawerOptions } from '@/api/pos'
import { POSRegister } from '@/components/pos/pos-register'
import { POSLockScreen } from '@/components/pos/pos-lock-screen'
import { StationTopBar } from './station-top-bar'
import { RepairsStation } from '@/components/station-repairs/repairs-station'
import { LessonsStation } from '@/components/station-lessons/lessons-station'

interface Location {
  id: string
  name: string
}

interface AppConfigEntry {
  key: string
  value: string | null
}

function locationsOptions() {
  return queryOptions({
    queryKey: ['locations'],
    queryFn: () => api.get<{ data: Location[] }>('/v1/locations'),
  })
}

function configOptions(key: string) {
  return queryOptions({
    queryKey: ['config', key],
    queryFn: async (): Promise<string | null> => {
      try {
        const entry = await api.get<AppConfigEntry>(`/v1/config/${key}`)
        return entry.value
      } catch {
        return null
      }
    },
  })
}

export function StationShell() {
  const { locationId, setLocation, locked, lock, touchActivity, token, setDrawerSession } = usePOSStore()
  const { activeTab, setActiveTab } = useStationStore()

  // Fetch lock timeout from config
  const { data: lockTimeoutStr } = useQuery({
    ...configOptions('pos_lock_timeout'),
    enabled: !!token,
  })
  const lockTimeoutMinutes = parseInt(lockTimeoutStr ?? '15') || 15

  // Auto-lock timer
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)

  useEffect(() => {
    if (locked || lockTimeoutMinutes === 0) {
      if (timerRef.current) clearInterval(timerRef.current)
      return
    }

    timerRef.current = setInterval(() => {
      const { lastActivity, locked: isLocked } = usePOSStore.getState()
      if (!isLocked && Date.now() - lastActivity > lockTimeoutMinutes * 60_000) {
        lock()
      }
    }, 30_000)

    return () => {
      if (timerRef.current) clearInterval(timerRef.current)
    }
  }, [locked, lockTimeoutMinutes, lock])

  // Track activity
  const handleActivity = useCallback(() => {
    if (!locked) touchActivity()
  }, [locked, touchActivity])

  // Fetch locations
  const { data: locationsData } = useQuery({
    ...locationsOptions(),
    enabled: !!token,
  })
  const locations = locationsData?.data ?? []

  // Auto-select first location
  useEffect(() => {
    if (!locationId && locations.length > 0) {
      setLocation(locations[0].id)
    }
  }, [locationId, locations, setLocation])

  // Fetch enabled modules
  const { data: modulesData } = useQuery({
    ...moduleListOptions(),
    enabled: !!token,
  })
  const enabledModules = new Set(
    (modulesData?.data ?? []).filter((m) => m.enabled && m.licensed).map((m) => m.slug),
  )

  // Fetch permissions for current user
  const [permissions, setPermissions] = useState<string[]>([])
  const { data: permData } = useQuery({
    queryKey: ['me', 'permissions'],
    queryFn: () => api.get<{ permissions: string[] }>('/v1/me/permissions'),
    enabled: !!token,
  })
  useEffect(() => {
    if (permData?.permissions) setPermissions(permData.permissions)
  }, [permData])

  // Auto-select first available tab based on permissions + modules
  useEffect(() => {
    if (!token || !permData) return
    const perms = permData.permissions ?? []
    const tabs = [
      { key: 'pos' as const, perm: 'pos.view', mod: 'pos' },
      { key: 'repairs' as const, perm: 'repairs.view', mod: 'repairs' },
      { key: 'lessons' as const, perm: 'lessons.view', mod: 'lessons' },
    ]
    const available = tabs.filter(t => perms.includes(t.perm) && enabledModules.has(t.mod))
    if (available.length > 0 && !available.find(t => t.key === activeTab)) {
      setActiveTab(available[0].key)
    }
  }, [token, permData, enabledModules, activeTab, setActiveTab])

  // Fetch drawer for POS tab (needed in top bar)
  const { data: drawer } = useQuery({
    ...currentDrawerOptions(locationId),
    retry: false,
    enabled: !!locationId && !!token,
  })

  useEffect(() => {
    if (drawer?.id && drawer.status === 'open') {
      setDrawerSession(drawer.id)
    } else {
      setDrawerSession(null)
    }
  }, [drawer, setDrawerSession])

  const hasPermission = (perm: string) => permissions.includes(perm)

  return (
    <div
      className="relative flex flex-col h-full"
      onPointerDown={handleActivity}
      onKeyDown={handleActivity}
    >
      {locked && <POSLockScreen />}
      <StationTopBar
        locations={locations}
        locationId={locationId}
        onLocationChange={setLocation}
        drawer={drawer ?? null}
        permissions={permissions}
        enabledModules={enabledModules}
      />
      <div className="flex-1 min-h-0 overflow-hidden">
        {activeTab === 'pos' && enabledModules.has('pos') && hasPermission('pos.view') && (
          <POSRegister embedded />
        )}
        {activeTab === 'repairs' && enabledModules.has('repairs') && hasPermission('repairs.view') && (
          <RepairsStation permissions={permissions} />
        )}
        {activeTab === 'lessons' && enabledModules.has('lessons') && hasPermission('lessons.view') && (
          <LessonsStation permissions={permissions} />
        )}
      </div>
    </div>
  )
}
