import { useState, useCallback } from 'react'
import { useConfig } from './useConfig'
import { useToast } from '../components/common'

interface PoolStatus {
    target: number
    current: number
    deficit: number
    last_check: string
    auto_add: boolean
    min_interval: number
    last_auto_add: string
    polling_enabled: boolean
    polling_interval: number
}

interface HealthCheckResult {
    account_id: number
    email: string
    status: string
    checked_at: string
    error?: string
}

export function useBackendApi() {
    const { config } = useConfig()
    const toast = useToast()
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState<string | null>(null)

    // 推断后端 API 地址 (S2A 在 8080, 后端 API 在 8088)
    const getBackendUrl = useCallback(() => {
        const s2aBase = config.s2a.apiBase
        return s2aBase.replace(/\/api.*$/, '').replace(/:8080/, ':8088')
    }, [config.s2a.apiBase])

    // 通用请求方法
    const request = useCallback(
        async <T>(endpoint: string, options: RequestInit = {}): Promise<T | null> => {
            setLoading(true)
            setError(null)
            try {
                const backendUrl = getBackendUrl()
                const response = await fetch(`${backendUrl}${endpoint}`, {
                    ...options,
                    headers: {
                        'Content-Type': 'application/json',
                        ...options.headers,
                    },
                })

                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`)
                }

                const data = await response.json()
                if (data.code !== 0) {
                    throw new Error(data.message || '请求失败')
                }

                return data.data as T
            } catch (e) {
                const msg = e instanceof Error ? e.message : '请求失败'
                setError(msg)
                toast.error(msg)
                return null
            } finally {
                setLoading(false)
            }
        },
        [getBackendUrl, toast]
    )

    // 健康检查
    const checkHealth = useCallback(async () => {
        return request<{ status: string; time: string }>('/api/health')
    }, [request])

    // 获取号池状态
    const getPoolStatus = useCallback(async () => {
        return request<PoolStatus>('/api/pool/status')
    }, [request])

    // 设置号池目标
    const setPoolTarget = useCallback(
        async (target: number, autoAdd: boolean, minInterval: number) => {
            return request('/api/pool/target', {
                method: 'POST',
                body: JSON.stringify({
                    target,
                    auto_add: autoAdd,
                    min_interval: minInterval,
                }),
            })
        },
        [request]
    )

    // 控制轮询
    const setPolling = useCallback(
        async (enabled: boolean, interval: number) => {
            return request('/api/pool/polling', {
                method: 'POST',
                body: JSON.stringify({ enabled, interval }),
            })
        },
        [request]
    )

    // 刷新号池状态
    const refreshPool = useCallback(async () => {
        return request('/api/pool/refresh', { method: 'POST' })
    }, [request])

    // 启动健康检查
    const startHealthCheck = useCallback(async () => {
        return request('/api/health-check/start', { method: 'POST' })
    }, [request])

    // 获取健康检查结果
    const getHealthCheckResults = useCallback(async () => {
        return request<HealthCheckResult[]>('/api/health-check/results')
    }, [request])

    // 获取本地账号
    const getLocalAccounts = useCallback(async () => {
        return request<Array<{
            email: string
            pooled: boolean
            pooled_at: string
            pool_id: number
            used: boolean
            used_at: string
        }>>('/api/accounts')
    }, [request])

    // 批量入库
    const poolAccounts = useCallback(
        async (emails: string[]) => {
            const result = await request<{ success: number; failed: number }>('/api/accounts/pool', {
                method: 'POST',
                body: JSON.stringify({ emails }),
            })
            if (result) {
                toast.success(`入库完成: 成功 ${result.success}, 失败 ${result.failed}`)
            }
            return result
        },
        [request, toast]
    )

    // Codex 授权
    const startCodexAuth = useCallback(
        async (email: string, password: string, proxy?: string) => {
            const result = await request('/api/codex/auth', {
                method: 'POST',
                body: JSON.stringify({ email, password, proxy }),
            })
            if (result) {
                toast.success('授权任务已启动')
            }
            return result
        },
        [request, toast]
    )

    return {
        loading,
        error,
        checkHealth,
        getPoolStatus,
        setPoolTarget,
        setPolling,
        refreshPool,
        startHealthCheck,
        getHealthCheckResults,
        getLocalAccounts,
        poolAccounts,
        startCodexAuth,
    }
}
