'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { NetworkLog } from '@/types/monitor'
import { Download } from 'lucide-react'
import { toast } from 'sonner'

// Import modular components
import {
  NetworkLogService,
  NetworkLogStats,
  NetworkLogFilters,
  NetworkLogTable,
  NetworkLogDetailDialog,
  NetworkLogInfo
} from './components'

export default function NetworkLogPage() {
  const [logs, setLogs] = useState<NetworkLog[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [searchKeyword, setSearchKeyword] = useState('')
  const [methodFilter, setMethodFilter] = useState<string>('all')
  const [statusFilter, setStatusFilter] = useState<string>('all')
  const [showDetailDialog, setShowDetailDialog] = useState(false)
  const [selectedLog, setSelectedLog] = useState<NetworkLog | null>(null)
  const [isDetailLoading, setIsDetailLoading] = useState(false)

  useEffect(() => {
    loadLogs()
  }, [searchKeyword, methodFilter, statusFilter])

  const loadLogs = async () => {
    setIsLoading(true)
    try {
      const response = await NetworkLogService.getNetworkLogs({
        page: 1,
        pageSize: 100,
        filters: {
          searchKeyword,
          method: methodFilter,
          status: statusFilter
        }
      })

      if (response.success) {
        setLogs(response.data)
      } else {
        throw new Error(response.message || '加载网络日志失败')
      }
    } catch (error) {
      console.error('Failed to load network logs:', error)
      toast.error('加载网络日志失败，请稍后重试')
    } finally {
      setIsLoading(false)
    }
  }

  const handleViewDetail = async (log: NetworkLog) => {
    setSelectedLog(log)
    setShowDetailDialog(true)

    setIsDetailLoading(true)
    try {
      const response = await NetworkLogService.getNetworkLogDetail(log.id)
      if (response.success) {
        setSelectedLog(response.data)
      }
    } catch (error) {
      console.error('Failed to fetch log detail:', error)
    } finally {
      setIsDetailLoading(false)
    }
  }

  const handleExport = async () => {
    try {
      const blob = await NetworkLogService.exportNetworkLogs({
        searchKeyword,
        method: methodFilter,
        status: statusFilter
      })

      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `network_logs_${new Date().getTime()}.json`
      link.click()
      URL.revokeObjectURL(url)

      toast.success('导出成功')
    } catch (error) {
      console.error('Failed to export logs:', error)
      toast.error('导出失败，请稍后重试')
    }
  }

  
  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">网络日志</h2>
          <p className="text-muted-foreground">记录系统接收与发送的所有网络请求信息</p>
        </div>
        <Button onClick={handleExport} disabled={isLoading || logs.length === 0}>
          <Download className="w-4 h-4 mr-2" />
          导出日志
        </Button>
      </div>

      <NetworkLogStats logs={logs} isLoading={isLoading} />

      <NetworkLogFilters
        searchKeyword={searchKeyword}
        onSearchChange={setSearchKeyword}
        methodFilter={methodFilter}
        onMethodFilterChange={setMethodFilter}
        statusFilter={statusFilter}
        onStatusFilterChange={setStatusFilter}
      />

      <NetworkLogTable
        logs={logs}
        isLoading={isLoading}
        onViewDetail={handleViewDetail}
      />

      <NetworkLogDetailDialog
        log={selectedLog}
        isOpen={showDetailDialog}
        onClose={() => setShowDetailDialog(false)}
        isLoading={isDetailLoading}
      />

      <NetworkLogInfo />
    </div>
  )
}