/**
 * Audit Logs Page
 * View and filter system audit logs (admin only)
 */

import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { apiClientV2 } from '@/services/apiV2'
import type { AuditLog } from '@/types/apiV2'
import {
  FileText,
  RefreshCw,
  Filter,
  CheckCircle2,
  XCircle,
  Loader2,
  AlertCircle,
  Shield,
  ChevronLeft,
} from 'lucide-react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Badge } from '@/components/ui/badge'
import { Select } from '@/components/ui/select'

export default function AuditLogsPage() {
  const navigate = useNavigate()
  const [logs, setLogs] = useState<AuditLog[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  // Filters
  const [categoryFilter, setCategoryFilter] = useState<string>('all')
  const [successFilter, setSuccessFilter] = useState<string>('all')
  const [page, setPage] = useState(1)
  const [pageSize] = useState(50)
  const [total, setTotal] = useState(0)
  const [hasMore, setHasMore] = useState(false)

  // Fetch logs
  const fetchLogs = async () => {
    try {
      setLoading(true)
      setError('')

      const params: any = {
        page,
        page_size: pageSize,
      }

      if (categoryFilter !== 'all') {
        params.category = categoryFilter
      }

      if (successFilter !== 'all') {
        params.success = successFilter === 'true'
      }

      const response = await apiClientV2.getAuditLogs(params)

      setLogs(response.logs)
      setTotal(response.total)
      setHasMore(response.has_more)
    } catch (err: any) {
      console.error('Failed to fetch audit logs:', err)
      setError(err.response?.data?.detail || '載入審計日誌失敗')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchLogs()
  }, [categoryFilter, successFilter, page])

  // Reset to page 1 when filters change
  const handleFilterChange = () => {
    setPage(1)
  }

  // Format date
  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr)
    return date.toLocaleString('zh-TW')
  }

  // Get category badge
  const getCategoryBadge = (category: string) => {
    const variants: Record<string, { variant: any; label: string }> = {
      auth: { variant: 'default', label: '認證' },
      task: { variant: 'secondary', label: '任務' },
      file: { variant: 'secondary', label: '檔案' },
      admin: { variant: 'destructive', label: '管理' },
      system: { variant: 'secondary', label: '系統' },
    }

    const config = variants[category] || { variant: 'secondary', label: category }

    return <Badge variant={config.variant}>{config.label}</Badge>
  }

  return (
    <div className="container mx-auto p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <div className="flex items-center gap-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => navigate('/admin')}
              className="mr-2"
            >
              <ChevronLeft className="w-4 h-4 mr-1" />
              返回
            </Button>
            <Shield className="w-8 h-8 text-blue-600" />
            <h1 className="text-3xl font-bold text-gray-900">審計日誌</h1>
          </div>
          <p className="text-gray-600 mt-1">系統操作記錄與審計追蹤</p>
        </div>
        <Button onClick={() => fetchLogs()} variant="outline">
          <RefreshCw className="w-4 h-4 mr-2" />
          刷新
        </Button>
      </div>

      {/* Filters */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <Filter className="w-5 h-5" />
            篩選條件
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">類別</label>
              <Select
                value={categoryFilter}
                onChange={(e) => {
                  setCategoryFilter(e.target.value)
                  handleFilterChange()
                }}
                options={[
                  { value: 'all', label: '全部' },
                  { value: 'auth', label: '認證' },
                  { value: 'task', label: '任務' },
                  { value: 'file', label: '檔案' },
                  { value: 'admin', label: '管理' },
                  { value: 'system', label: '系統' },
                ]}
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">狀態</label>
              <Select
                value={successFilter}
                onChange={(e) => {
                  setSuccessFilter(e.target.value)
                  handleFilterChange()
                }}
                options={[
                  { value: 'all', label: '全部' },
                  { value: 'true', label: '成功' },
                  { value: 'false', label: '失敗' },
                ]}
              />
            </div>
          </div>

          {(categoryFilter !== 'all' || successFilter !== 'all') && (
            <div className="mt-4">
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setCategoryFilter('all')
                  setSuccessFilter('all')
                  handleFilterChange()
                }}
              >
                清除篩選
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Error Alert */}
      {error && (
        <div className="flex items-center gap-3 p-4 bg-red-50 border border-red-200 rounded-lg">
          <AlertCircle className="w-5 h-5 text-red-600" />
          <p className="text-red-600">{error}</p>
        </div>
      )}

      {/* Audit Logs List */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">審計日誌記錄</CardTitle>
          <CardDescription>
            共 {total} 筆記錄 {hasMore && `（顯示第 ${page} 頁）`}
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="w-8 h-8 animate-spin text-gray-400" />
            </div>
          ) : logs.length === 0 ? (
            <div className="text-center py-12 text-gray-500">
              <FileText className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>暫無審計日誌</p>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>時間</TableHead>
                    <TableHead>用戶</TableHead>
                    <TableHead>類別</TableHead>
                    <TableHead>操作</TableHead>
                    <TableHead>資源</TableHead>
                    <TableHead>狀態</TableHead>
                    <TableHead>錯誤訊息</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {logs.map((log) => (
                    <TableRow key={log.id}>
                      <TableCell className="text-sm text-gray-600">
                        {formatDate(log.created_at)}
                      </TableCell>
                      <TableCell>
                        <div>
                          <div className="font-medium">{log.user_email}</div>
                          <div className="text-xs text-gray-500">ID: {log.user_id}</div>
                        </div>
                      </TableCell>
                      <TableCell>{getCategoryBadge(log.category)}</TableCell>
                      <TableCell className="font-mono text-sm">{log.action}</TableCell>
                      <TableCell>
                        {log.resource_type ? (
                          <div className="text-sm">
                            <div className="text-gray-700">{log.resource_type}</div>
                            {log.resource_id && (
                              <div className="text-xs text-gray-500 font-mono">
                                {log.resource_id}
                              </div>
                            )}
                          </div>
                        ) : (
                          <span className="text-gray-400">-</span>
                        )}
                      </TableCell>
                      <TableCell>
                        {log.success ? (
                          <Badge variant="default" className="flex items-center gap-1 w-fit">
                            <CheckCircle2 className="w-3 h-3" />
                            成功
                          </Badge>
                        ) : (
                          <Badge variant="destructive" className="flex items-center gap-1 w-fit">
                            <XCircle className="w-3 h-3" />
                            失敗
                          </Badge>
                        )}
                      </TableCell>
                      <TableCell>
                        {log.error_message ? (
                          <span className="text-sm text-red-600">{log.error_message}</span>
                        ) : (
                          <span className="text-gray-400">-</span>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>

              {/* Pagination */}
              <div className="flex items-center justify-between mt-4">
                <div className="text-sm text-gray-600">
                  顯示 {(page - 1) * pageSize + 1} - {Math.min(page * pageSize, total)} / 共{' '}
                  {total} 筆
                </div>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setPage((p) => Math.max(1, p - 1))}
                    disabled={page === 1}
                  >
                    上一頁
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setPage((p) => p + 1)}
                    disabled={!hasMore}
                  >
                    下一頁
                  </Button>
                </div>
              </div>
            </>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
