import { useState, useEffect, useCallback } from 'react'
import { User, Stream, StreamPlatform, StudioScene, ChatMessage, ApiResponse } from '../lib/types'
import { MockAPI } from '../lib/mockApi'

export function useAuth() {
  const [user, setUser] = useState<User | null>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [isAuthenticated, setIsAuthenticated] = useState(false)

  const login = async (email: string, password: string): Promise<ApiResponse<User>> => {
    setIsLoading(true)
    try {
      const result = await MockAPI.login(email, password)
      if (result.success && result.data) {
        setUser(result.data)
        setIsAuthenticated(true)
        localStorage.setItem('user', JSON.stringify(result.data))
      }
      return result
    } finally {
      setIsLoading(false)
    }
  }

  const register = async (userData: Partial<User>): Promise<ApiResponse<User>> => {
    setIsLoading(true)
    try {
      const result = await MockAPI.register(userData)
      if (result.success && result.data) {
        setUser(result.data)
        setIsAuthenticated(true)
        localStorage.setItem('user', JSON.stringify(result.data))
      }
      return result
    } finally {
      setIsLoading(false)
    }
  }

  const logout = () => {
    setUser(null)
    setIsAuthenticated(false)
    localStorage.removeItem('user')
  }

  useEffect(() => {
    const savedUser = localStorage.getItem('user')
    if (savedUser) {
      try {
        const userData = JSON.parse(savedUser)
        setUser(userData)
        setIsAuthenticated(true)
      } catch (error) {
        localStorage.removeItem('user')
      }
    }
  }, [])

  return {
    user,
    isAuthenticated,
    isLoading,
    login,
    register,
    logout
  }
}

export function useStreams() {
  const [streams, setStreams] = useState<Stream[]>([])
  const [currentStream, setCurrentStream] = useState<Stream | null>(null)
  const [isLoading, setIsLoading] = useState(false)

  const fetchStreams = async () => {
    setIsLoading(true)
    try {
      const result = await MockAPI.getStreams()
      if (result.success && result.data) setStreams(result.data)
    } finally {
      setIsLoading(false)
    }
  }

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

  return { streams, currentStream, isLoading, fetchStreams, setCurrentStream }
}

export function usePlatforms() {
  const [platforms, setPlatforms] = useState<StreamPlatform[]>([])
  const [isLoading, setIsLoading] = useState(false)

  const fetchPlatforms = async () => {
    setIsLoading(true)
    try { const result = await MockAPI.getPlatforms(); if (result.success && result.data) setPlatforms(result.data) }
    finally { setIsLoading(false) }
  }

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

  return { platforms, isLoading, fetchPlatforms }
}

export function useStudio() {
  const [scenes, setScenes] = useState<StudioScene[]>([])
  const [activeScene, setActiveScene] = useState<StudioScene | null>(null)
  const [isLoading, setIsLoading] = useState(false)

  const fetchScenes = async () => {
    setIsLoading(true)
    try {
      const result = await MockAPI.getScenes()
      if (result.success && result.data) {
        setScenes(result.data)
        const active = result.data.find((s: StudioScene) => s.isActive)
        setActiveScene(active || null)
      }
    } finally { setIsLoading(false) }
  }

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

  return { scenes, activeScene, isLoading, fetchScenes }
}

export function useChat(streamId: string) {
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [isLoading, setIsLoading] = useState(false)

  const fetchMessages = useCallback(async () => {
    if (!streamId) return
    setIsLoading(true)
    try { const result = await MockAPI.getChatMessages(streamId); if (result.success && result.data) setMessages(result.data) }
    finally { setIsLoading(false) }
  }, [streamId])

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

  return { messages, isLoading, fetchMessages }
}

export function useTheme() {
  const [theme, setTheme] = useState<'light'|'dark'>('light')
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light'
    setTheme(newTheme)
    localStorage.setItem('theme', newTheme)
    if (newTheme === 'dark') document.documentElement.classList.add('dark')
    else document.documentElement.classList.remove('dark')
  }

  useEffect(() => {
    const saved = (localStorage.getItem('theme') as 'light'|'dark') || 'light'
    setTheme(saved)
    if (saved === 'dark') document.documentElement.classList.add('dark')
  }, [])

  return { theme, toggleTheme }
}
