'use client'

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

// Import modular components
import {
  OperationLogService,
  OperationLogStats,
  OperationLogFilters,
  OperationLogTable,
  OperationLogDetailDialog,
  OperationLogInfo
} from './components'

export default function OperationLogPage() {
  const [logs, setLogs] = useState<OperationLog[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [searchKeyword, setSearchKeyword] = useState('')
  const [moduleFilter, setModuleFilter] = useState<string>('all')
  const [actionFilter, setActionFilter] = useState<string>('all')
  const [statusFilter, setStatusFilter] = useState<string>('all')
  const [showDetailDialog, setShowDetailDialog] = useState(false)
  const [selectedLog, setSelectedLog] = useState<OperationLog | null>(null)
  const [isDetailLoading, setIsDetailLoading] = useState(false)

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

  const loadLogs = async () => {
    setIsLoading(true)
    try {
      const response = await OperationLogService.getOperationLogs({
        page: 1,
        pageSize: 100,
        filters: {
          searchKeyword,
          module: moduleFilter,
          action: actionFilter,
          status: statusFilter
        }
      })

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

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

    setIsDetailLoading(true)
    try {
      const response = await OperationLogService.getOperationLogDetail(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 OperationLogService.exportOperationLogs({
        searchKeyword,
        module: moduleFilter,
        action: actionFilter,
        status: statusFilter
      })

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

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

  const handleRefresh = () => {
    loadLogs()
  }

  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>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleRefresh} disabled={isLoading}>
            刷新
          </Button>
          <Button onClick={handleExport} disabled={isLoading || logs.length === 0}>
            <Download className="w-4 h-4 mr-2" />
            导出日志
          </Button>
        </div>
      </div>

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

      <OperationLogFilters
        searchKeyword={searchKeyword}
        onSearchChange={setSearchKeyword}
        moduleFilter={moduleFilter}
        onModuleFilterChange={setModuleFilter}
        actionFilter={actionFilter}
        onActionFilterChange={setActionFilter}
        statusFilter={statusFilter}
        onStatusFilterChange={setStatusFilter}
      />

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

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

      <OperationLogInfo />
    </div>
  )
}