import { useState, useCallback } from 'react'
import type { AccountInput, CheckedAccount, AccountStatus } from '../types'
import { ChatGPTClient } from '../api/chatgpt'

interface CheckProgress {
  total: number
  checked: number
  results: {
    active: number
    banned: number
    token_expired: number
    error: number
  }
}

export function useAccountCheck() {
  const [accounts, setAccounts] = useState<CheckedAccount[]>([])
  const [checking, setChecking] = useState(false)
  const [progress, setProgress] = useState<CheckProgress>({
    total: 0,
    checked: 0,
    results: { active: 0, banned: 0, token_expired: 0, error: 0 },
  })

  const loadFromJson = useCallback((jsonData: AccountInput[]) => {
    const checkedAccounts: CheckedAccount[] = jsonData.map((account, index) => ({
      ...account,
      id: index,
      status: 'pending' as AccountStatus,
    }))
    setAccounts(checkedAccounts)
    setProgress({
      total: checkedAccounts.length,
      checked: 0,
      results: { active: 0, banned: 0, token_expired: 0, error: 0 },
    })
  }, [])

  const parseJsonFile = useCallback(
    async (file: File): Promise<{ success: boolean; error?: string }> => {
      try {
        const text = await file.text()
        const data = JSON.parse(text)

        if (!Array.isArray(data)) {
          return { success: false, error: 'JSON 文件必须是数组格式' }
        }

        // Validate each account
        for (let i = 0; i < data.length; i++) {
          const item = data[i]
          if (!item.account || !item.password || !item.token) {
            return {
              success: false,
              error: `第 ${i + 1} 条记录缺少必要字段 (account, password, token)`,
            }
          }
        }

        loadFromJson(data)
        return { success: true }
      } catch {
        return { success: false, error: 'JSON 解析失败，请检查文件格式' }
      }
    },
    [loadFromJson]
  )

  const startCheck = useCallback(
    async (concurrency: number = 20) => {
      if (accounts.length === 0 || checking) return

      setChecking(true)
      const client = new ChatGPTClient()
      const results = { active: 0, banned: 0, token_expired: 0, error: 0 }

      // Mark all as checking
      setAccounts((prev) => prev.map((acc) => ({ ...acc, status: 'checking' as AccountStatus })))

      await client.batchCheck(
        accounts.map((acc) => ({
          account: acc.account,
          password: acc.password,
          token: acc.token,
        })),
        {
          concurrency,
          onProgress: (checkedAccount, index) => {
            // Update results count
            const status = checkedAccount.status
            if (status === 'active') results.active++
            else if (status === 'banned') results.banned++
            else if (status === 'token_expired') results.token_expired++
            else results.error++

            // Update account in list
            setAccounts((prev) =>
              prev.map((acc, i) =>
                i === index
                  ? {
                      ...acc,
                      status: checkedAccount.status,
                      accountId: checkedAccount.accountId,
                      planType: checkedAccount.planType,
                      error: checkedAccount.error,
                    }
                  : acc
              )
            )

            // Update progress
            setProgress({
              total: accounts.length,
              checked: index + 1,
              results: { ...results },
            })
          },
        }
      )

      setChecking(false)
    },
    [accounts, checking]
  )

  const selectAll = useCallback(
    (status?: AccountStatus) => {
      return accounts.filter((acc) => !status || acc.status === status).map((acc) => acc.id)
    },
    [accounts]
  )

  const getSelectedAccounts = useCallback(
    (ids: number[]) => {
      return accounts.filter((acc) => ids.includes(acc.id))
    },
    [accounts]
  )

  const clearAccounts = useCallback(() => {
    setAccounts([])
    setProgress({
      total: 0,
      checked: 0,
      results: { active: 0, banned: 0, token_expired: 0, error: 0 },
    })
  }, [])

  return {
    accounts,
    checking,
    progress,
    loadFromJson,
    parseJsonFile,
    startCheck,
    selectAll,
    getSelectedAccounts,
    clearAccounts,
  }
}
