import { useState, useEffect, useRef, useCallback } from 'react'
import { apiClient } from '@/api/client'
import { t } from '@/lib/i18n'

interface SupportSessionState {
  active: boolean
  sessionId?: string
  mode?: 'provision' | 'configure'
  expiresAt?: string
  startedAt?: string
}

interface CommandLog {
  actionId: string
  method: string
  endpoint: string
  status: 'completed' | 'failed'
  timestamp: string
}

export function useSupportSession() {
  const [session, setSession] = useState<SupportSessionState>({ active: false })
  const [loading, setLoading] = useState(false)
  const [polling, setPolling] = useState(false)
  const [commandLog, setCommandLog] = useState<CommandLog[]>([])
  const [error, setError] = useState<string | null>(null)
  const pollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)

  const checkStatus = useCallback(async () => {
    try {
      const res = await apiClient.get<{ success: boolean; data: SupportSessionState }>('support/status')
      if (res.success) {
        setSession(res.data)
        return res.data.active
      }
    } catch {
      // Status check failed silently
    }
    return false
  }, [])

  useEffect(() => {
    checkStatus()
  }, [checkStatus])

  const startSession = async (mode: 'provision' | 'configure') => {
    setLoading(true)
    setError(null)
    try {
      const res = await apiClient.post<{ success: boolean; data: { sessionId: string; expiresAt: string; mode: string } }>('support/start', { mode })
      if (res.success) {
        setSession({
          active: true,
          sessionId: res.data.sessionId,
          mode: mode,
          expiresAt: res.data.expiresAt,
          startedAt: new Date().toISOString(),
        })
        setCommandLog([])
        startPolling()
      }
    } catch (err: any) {
      const msg = err?.message || err?.data?.message || t('Failed to start support session')
      setError(msg)
    } finally {
      setLoading(false)
    }
  }

  const endSession = async () => {
    setLoading(true)
    setError(null)
    stopPolling()
    try {
      await apiClient.post('support/end')
      setSession({ active: false })
    } catch {
      setError(t('Failed to end support session. Please try again.'))
      try {
        const status = await apiClient.get<{ success: boolean; data: SupportSessionState }>('support/status')
        if (status.data?.active) {
          setSession({ active: true })
        } else {
          setSession({ active: false })
        }
      } catch {
        setSession({ active: true })
      }
    } finally {
      setLoading(false)
    }
  }

  const pollAndExecute = useCallback(async () => {
    if (polling) return
    setPolling(true)
    try {
      const res = await apiClient.post<{
        success: boolean
        data: {
          commands_executed: number
          session_ended?: boolean
          results?: Array<{ actionId: string; status: string; result: unknown }>
        }
      }>('support/poll')

      if (res.success) {
        if (res.data.session_ended) {
          setSession({ active: false })
          stopPolling()
          return
        }

        if (res.data.results && res.data.results.length > 0) {
          const newLogs: CommandLog[] = res.data.results.map((r: any) => ({
            actionId: r.actionId,
            method: r.method || '',
            endpoint: r.endpoint || '',
            status: r.status as 'completed' | 'failed',
            timestamp: new Date().toISOString(),
          }))
          setCommandLog((prev) => [...prev, ...newLogs])
        }
      }
    } catch (err: any) {
      if (err?.code === 'no_session') {
        setSession({ active: false })
        stopPolling()
      }
    } finally {
      setPolling(false)
    }
  }, [polling])

  const startPolling = useCallback(() => {
    stopPolling()
    pollIntervalRef.current = setInterval(() => {
      pollAndExecute()
    }, 3000)
  }, [pollAndExecute])

  const stopPolling = useCallback(() => {
    if (pollIntervalRef.current) {
      clearInterval(pollIntervalRef.current)
      pollIntervalRef.current = null
    }
  }, [])

  // Start polling if session is already active on mount
  useEffect(() => {
    if (session.active) {
      startPolling()
    }
    return () => stopPolling()
  }, [session.active, startPolling, stopPolling])

  return {
    session,
    loading,
    polling,
    commandLog,
    error,
    startSession,
    endSession,
    checkStatus,
  }
}
