import { useEffect, useState, useCallback } from 'react'
import { api, endpoints } from '../../api'
import type {
  AiRecognitionResponse,
  AiRecognitionSettings,
  AiRecognitionTelemetry,
} from '../../types'

type Status = 'idle' | 'loading' | 'ready' | 'saving' | 'error'

// Factory defaults — UI stays interactive when GET fails (no backend).
const FACTORY_AI_SETTINGS: AiRecognitionSettings = {
  framesToRecognize: 4,
  minSecondsBetween: 2,
  minConfidence: 25,
}

export function useAiSettings() {
  const [draft, setDraft] = useState<AiRecognitionSettings>(FACTORY_AI_SETTINGS)
  const [persisted, setPersisted] = useState<AiRecognitionSettings>(FACTORY_AI_SETTINGS)
  const [telemetry, setTelemetry] = useState<AiRecognitionTelemetry | null>(null)
  const [status, setStatus] = useState<Status>('idle')
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    setStatus('loading')
    api.get<AiRecognitionResponse>(endpoints.admin.aiSettings())
      .then(res => {
        if (cancelled) return
        setDraft(res.settings)
        setPersisted(res.settings)
        setTelemetry(res.telemetry)
        setStatus('ready')
      })
      .catch(() => {
        if (cancelled) return
        setStatus('error')
        setError('Failed to load AI settings')
      })
    return () => { cancelled = true }
  }, [])

  const save = useCallback(async () => {
    setStatus('saving')
    setError(null)
    try {
      const res = await api.patch<AiRecognitionResponse>(endpoints.admin.aiSettings(), draft)
      setDraft(res.settings)
      setPersisted(res.settings)
      setTelemetry(res.telemetry)
      setStatus('ready')
    } catch {
      setStatus('error')
      setError('Failed to save AI settings')
    }
  }, [draft])

  const reset = useCallback(() => {
    setDraft(persisted)
  }, [persisted])

  return { draft, setDraft, telemetry, status, error, save, reset } as const
}
