'use client'

import { useState, useEffect, useCallback } from 'react'
import type { EmailAccount, MailStats, SyncStatus } from './types'

export interface UseMailDataReturn {
  stats: MailStats | null
  accounts: EmailAccount[]
  syncStatus: SyncStatus | null
  loading: boolean
  error: string | null
  fetchData: () => Promise<void>
}

export function useMailData(): UseMailDataReturn {
  const [stats, setStats] = useState<MailStats | null>(null)
  const [accounts, setAccounts] = useState<EmailAccount[]>([])
  const [syncStatus, setSyncStatus] = useState<SyncStatus | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const fetchData = useCallback(async () => {
    try {
      setLoading(true)

      // Fetch stats via our proxy API (avoids CORS/mixed-content issues)
      const response = await fetch('/api/admin/mail')

      if (response.ok) {
        const data = await response.json()
        setStats(data.stats)
        setAccounts(data.accounts)
        setSyncStatus(data.syncStatus)
        setError(null)
      } else {
        const errorData = await response.json().catch(() => ({}))
        throw new Error(errorData.details || `API returned ${response.status}`)
      }
    } catch (err) {
      console.error('Failed to fetch mail data:', err)
      setError('Verbindung zum Mail-Service (Mailpit) fehlgeschlagen. Laeuft Mailpit auf Port 8025?')
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchData()

    // Refresh every 10 seconds if syncing
    const interval = setInterval(() => {
      if (syncStatus?.running) {
        fetchData()
      }
    }, 10000)

    return () => clearInterval(interval)
  }, [fetchData, syncStatus?.running])

  return { stats, accounts, syncStatus, loading, error, fetchData }
}
