import { useState, useCallback } from 'react'
import { useConfig } from './useConfig'
import type { DashboardStats, S2AAccount, AccountListParams, PaginatedResponse } from '../types'
import type { DashboardStatsResponse, AccountListResponse } from '../api/types'

export function useS2AApi() {
  const { s2aClient, isConnected } = useConfig()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const getDashboardStats = useCallback(async (): Promise<DashboardStats | null> => {
    if (!s2aClient) {
      setError('S2A 客户端未配置')
      return null
    }

    setLoading(true)
    setError(null)

    try {
      const response: DashboardStatsResponse = await s2aClient.getDashboardStats()
      return response
    } catch (err) {
      const message = err instanceof Error ? err.message : '获取统计数据失败'
      setError(message)
      return null
    } finally {
      setLoading(false)
    }
  }, [s2aClient])

  const getAccounts = useCallback(
    async (params: AccountListParams = {}): Promise<PaginatedResponse<S2AAccount> | null> => {
      if (!s2aClient) {
        setError('S2A 客户端未配置')
        return null
      }

      setLoading(true)
      setError(null)

      try {
        const response: AccountListResponse = await s2aClient.getAccounts(params)
        return {
          data: response.data,
          total: response.total,
          page: response.page,
          page_size: response.page_size,
          total_pages: Math.ceil(response.total / response.page_size),
        }
      } catch (err) {
        const message = err instanceof Error ? err.message : '获取账号列表失败'
        setError(message)
        return null
      } finally {
        setLoading(false)
      }
    },
    [s2aClient]
  )

  const createAccount = useCallback(
    async (data: {
      name: string
      token: string
      email?: string
      concurrency?: number
      priority?: number
      groupIds?: number[]
      proxyId?: number | null
    }): Promise<S2AAccount | null> => {
      if (!s2aClient) {
        setError('S2A 客户端未配置')
        return null
      }

      setLoading(true)
      setError(null)

      try {
        const response = await s2aClient.createAccount({
          name: data.name,
          platform: 'openai',
          type: 'access_token',
          credentials: {
            access_token: data.token,
            email: data.email,
          },
          concurrency: data.concurrency ?? 1,
          priority: data.priority ?? 0,
          group_ids: data.groupIds ?? [],
          proxy_id: data.proxyId ?? null,
          auto_pause_on_expired: true,
        })
        return response as S2AAccount
      } catch (err) {
        const message = err instanceof Error ? err.message : '创建账号失败'
        setError(message)
        return null
      } finally {
        setLoading(false)
      }
    },
    [s2aClient]
  )

  const deleteAccount = useCallback(
    async (id: number): Promise<boolean> => {
      if (!s2aClient) {
        setError('S2A 客户端未配置')
        return false
      }

      setLoading(true)
      setError(null)

      try {
        await s2aClient.deleteAccount(id)
        return true
      } catch (err) {
        const message = err instanceof Error ? err.message : '删除账号失败'
        setError(message)
        return false
      } finally {
        setLoading(false)
      }
    },
    [s2aClient]
  )

  const testAccount = useCallback(
    async (id: number): Promise<{ success: boolean; message?: string } | null> => {
      if (!s2aClient) {
        setError('S2A 客户端未配置')
        return null
      }

      setLoading(true)
      setError(null)

      try {
        const response = await s2aClient.testAccount(id)
        return response
      } catch (err) {
        const message = err instanceof Error ? err.message : '测试账号失败'
        setError(message)
        return null
      } finally {
        setLoading(false)
      }
    },
    [s2aClient]
  )

  return {
    loading,
    error,
    isConnected,
    getDashboardStats,
    getAccounts,
    createAccount,
    deleteAccount,
    testAccount,
    clearError: () => setError(null),
  }
}
