'use client'

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

// Import modular components
import {
  LoginLogStats,
  LoginLogFilters,
  LoginLogTable,
  LoginLogInfo
} from './components'

export default function LoginLogPage() {
  const [logs, setLogs] = useState<LoginLog[]>([])
  const [searchKeyword, setSearchKeyword] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('all')
  const [dateRange, setDateRange] = useState<string>('all')

  useEffect(() => {
    loadLogs()
  }, [])

  const loadLogs = () => {
    // 强制重新加载mock数据以解决显示问题
    localStorage.removeItem('smart_agriculture_login_logs')

    const mockLogs: LoginLog[] = [
        {
          id: 'log-1',
          userId: 'user-1',
          username: 'admin',
          loginTime: '2024-10-21T09:30:00',
          ipAddress: '192.168.1.100',
          device: 'Windows 11',
          browser: 'Chrome 118',
          os: 'Windows',
          location: '北京市海淀区',
          status: 'success',
          sessionId: 'sess-001',
        },
        {
          id: 'log-2',
          userId: 'user-2',
          username: 'zhangsan',
          loginTime: '2024-10-21T10:15:00',
          ipAddress: '192.168.1.101',
          device: 'macOS 14',
          browser: 'Safari 17',
          os: 'macOS',
          location: '上海市浦东新区',
          status: 'success',
          sessionId: 'sess-002',
        },
        {
          id: 'log-3',
          userId: 'user-3',
          username: 'lisi',
          loginTime: '2024-10-21T11:20:00',
          ipAddress: '192.168.1.102',
          device: 'Android 13',
          browser: 'Chrome Mobile 118',
          os: 'Android',
          location: '广州市天河区',
          status: 'failed',
          failReason: '密码错误',
        },
        {
          id: 'log-4',
          userId: 'user-1',
          username: 'admin',
          loginTime: '2024-10-21T14:45:00',
          ipAddress: '192.168.1.100',
          device: 'Windows 11',
          browser: 'Chrome 118',
          os: 'Windows',
          location: '北京市海淀区',
          status: 'success',
          sessionId: 'sess-003',
        },
        {
          id: 'log-5',
          userId: 'user-4',
          username: 'wangwu',
          loginTime: '2024-10-21T15:30:00',
          ipAddress: '192.168.1.103',
          device: 'iOS 17',
          browser: 'Safari 17',
          os: 'iOS',
          location: '深圳市南山区',
          status: 'failed',
          failReason: '账号被锁定',
        },
        {
          id: 'log-6',
          userId: 'user-5',
          username: 'zhaoliu',
          loginTime: '2024-10-21T16:20:00',
          ipAddress: '192.168.1.104',
          device: 'Windows 10',
          browser: 'Edge 118',
          os: 'Windows',
          location: '杭州市西湖区',
          status: 'success',
          sessionId: 'sess-004',
        },
        {
          id: 'log-7',
          userId: 'user-6',
          username: 'chenqi',
          loginTime: '2024-10-21T17:10:00',
          ipAddress: '192.168.1.105',
          device: 'Ubuntu 22.04',
          browser: 'Firefox 119',
          os: 'Linux',
          location: '成都市武侯区',
          status: 'success',
          sessionId: 'sess-005',
        },
      ]
      localStorage.setItem('smart_agriculture_login_logs', JSON.stringify(mockLogs))
      setLogs(mockLogs)
  }

  const filteredLogs = logs.filter(log => {
    const matchKeyword = !searchKeyword ||
      log.username.includes(searchKeyword) ||
      log.ipAddress.includes(searchKeyword) ||
      (log.location && log.location.includes(searchKeyword))

    const matchStatus = statusFilter === 'all' || log.status === statusFilter

    let matchDate = true
    if (dateRange !== 'all') {
      const logDate = new Date(log.loginTime)
      const now = new Date()
      const diffDays = Math.floor((now.getTime() - logDate.getTime()) / (1000 * 60 * 60 * 24))

      switch (dateRange) {
        case 'today':
          matchDate = diffDays === 0
          break
        case 'week':
          matchDate = diffDays <= 7
          break
        case 'month':
          matchDate = diffDays <= 30
          break
      }
    }

    return matchKeyword && matchStatus && matchDate
  })

  const handleExport = () => {
    const dataStr = JSON.stringify(filteredLogs, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(dataBlob)
    const link = document.createElement('a')
    link.href = url
    link.download = `login_logs_${new Date().getTime()}.json`
    link.click()
    toast.success('导出成功')
  }

  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}>
          <Download className="w-4 h-4 mr-2" />
          导出日志
        </Button>
      </div>

      {/* 统计卡片 */}
      <LoginLogStats logs={logs} />

      {/* 搜索和筛选 */}
      <LoginLogFilters
        searchKeyword={searchKeyword}
        onSearchChange={setSearchKeyword}
        statusFilter={statusFilter}
        onStatusFilterChange={setStatusFilter}
        dateRange={dateRange}
        onDateRangeChange={setDateRange}
      />

      {/* 日志列表 */}
      <LoginLogTable logs={filteredLogs} />

      {/* 使用说明 */}
      <LoginLogInfo />
    </div>
  )
}