"use client"

import { useState, useEffect } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { History, Trash2, RefreshCw, User, FileText, Image, Settings, Globe, Filter } from "lucide-react"
import { format } from "date-fns"
import { useFamily } from "@/context/family-context"
import { useSession } from "next-auth/react"
import { useDialog } from "@/components/ui/alert-dialog-custom"

// 定义日志类型
interface ActivityLog {
  id: string
  action: "CREATE" | "UPDATE" | "DELETE" | "IMPORT" | "EXPORT"
  entityType: "MEMBER" | "PHOTO" | "STORY" | "SETTINGS"
  entityId?: string | null
  entityName?: string | null
  changes?: any
  timestamp: string
  userId: string
  user?: {
    name?: string | null
    email?: string | null
  }
  tree?: {
    name: string
  }
}

const actionLabels: Record<string, string> = {
  CREATE: "创建",
  UPDATE: "更新",
  DELETE: "删除",
  IMPORT: "导入",
  EXPORT: "导出",
}

const actionColors: Record<string, string> = {
  CREATE: "bg-green-500",
  UPDATE: "bg-blue-500",
  DELETE: "bg-red-500",
  IMPORT: "bg-purple-500",
  EXPORT: "bg-orange-500",
}

const entityTypeLabels: Record<string, string> = {
  MEMBER: "成员",
  PHOTO: "照片",
  STORY: "故事",
  SETTINGS: "设置",
}

const entityTypeIcons: Record<string, any> = {
  MEMBER: User,
  PHOTO: Image,
  STORY: FileText,
  SETTINGS: Settings,
}

interface FamilyTree {
  id: string
  name: string
  ownerId: string
  currentUserRole?: "OWNER" | "EDITOR" | "VIEWER"
}

export function ActivityLogViewer() {
  const { currentTree } = useFamily()
  const { data: session } = useSession()
  const { showAlert, showConfirm, showPrompt } = useDialog()
  const [logs, setLogs] = useState<ActivityLog[]>([])
  const [trees, setTrees] = useState<FamilyTree[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [filterTreeId, setFilterTreeId] = useState<string>("all")
  const [clearing, setClearing] = useState(false)

  // 加载家族树列表
  useEffect(() => {
    fetch('/api/trees')
      .then(res => res.json())
      .then(data => {
        if (data.trees) {
          setTrees(data.trees)
        }
      })
      .catch(err => console.error("加载家族树列表失败:", err))
  }, [])

  // 当 currentTree 改变时，更新筛选
  useEffect(() => {
    if (currentTree?.id) {
      setFilterTreeId(currentTree.id)
    }
  }, [currentTree?.id])

  const loadLogs = async () => {
    setLoading(true)
    setError(null)
    try {
      let url = ""
      
      if (filterTreeId === "all") {
        url = `/api/user/activity-logs?limit=100`
      } else {
        url = `/api/trees/${filterTreeId}/activity-logs?limit=100`
      }

      const res = await fetch(url)
      if (!res.ok) throw new Error("获取日志失败")
      
      const data = await res.json()
      setLogs(data.logs || [])
    } catch (err) {
      console.error("加载日志失败:", err)
      setError(err instanceof Error ? err.message : "加载失败")
    } finally {
      setLoading(false)
    }
  }

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

  // 检查当前用户是否是选中家族树的所有者
  const isOwner = () => {
    if (filterTreeId === "all") return false
    const selectedTree = trees.find(t => t.id === filterTreeId)
    if (!selectedTree) return false
    
    // 检查是否是所有者
    return selectedTree.ownerId === session?.user?.id || selectedTree.currentUserRole === "OWNER"
  }

  const handleClearLogs = async () => {
    if (filterTreeId === "all") {
      await showAlert("请先选择一个具体的家族树再清空日志", "提示")
      return
    }

    const selectedTree = trees.find(t => t.id === filterTreeId)
    if (!selectedTree) {
      await showAlert("未找到选中的家族树", "错误")
      return
    }

    // 第一次确认
    const confirmMessage = `⚠️ 警告：即将清空"${selectedTree.name}"的所有操作日志！\n\n此操作将永久删除该家族树的所有历史记录，且不可恢复。\n\n确定要继续吗？`
    const confirmed = await showConfirm(confirmMessage, "清空操作日志", "destructive")
    if (!confirmed) {
      return
    }

    // 第二次确认
    const finalConfirm = await showPrompt(
      `请输入家族树名称"${selectedTree.name}"以确认清空操作：\n\n（此操作不可撤销）`,
      "",
      "确认清空"
    )
    
    if (finalConfirm !== selectedTree.name) {
      await showAlert("名称不匹配，操作已取消", "操作已取消")
      return
    }

    setClearing(true)
    try {
      const res = await fetch(`/api/trees/${filterTreeId}/activity-logs`, {
        method: 'DELETE',
      })

      if (!res.ok) {
        const error = await res.json()
        throw new Error(error.error || "清空失败")
      }

      const data = await res.json()
      await showAlert(data.message || "操作日志已清空", "成功")
      
      // 重新加载日志
      await loadLogs()
    } catch (err) {
      console.error("清空日志失败:", err)
      await showAlert("清空失败：" + (err instanceof Error ? err.message : "未知错误"), "错误")
    } finally {
      setClearing(false)
    }
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
              <CardTitle className="flex items-center gap-2">
                <History className="h-5 w-5" />
                操作日志
              </CardTitle>
              <CardDescription>
                查看家族树的变更记录
              </CardDescription>
            </div>
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="icon"
                onClick={loadLogs}
                disabled={loading || clearing}
                className="h-9 w-9"
                title="刷新日志"
              >
                <RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
              </Button>
              {isOwner() && (
                <Button
                  variant="destructive"
                  size="sm"
                  onClick={handleClearLogs}
                  disabled={loading || clearing}
                  className="gap-2"
                  title="清空当前家族树的操作日志（仅所有者可用）"
                >
                  <Trash2 className="h-4 w-4" />
                  {clearing ? "清空中..." : "清空日志"}
                </Button>
              )}
              <div className="w-[200px]">
                <Select value={filterTreeId} onValueChange={setFilterTreeId}>
                  <SelectTrigger>
                    <div className="flex items-center gap-2">
                      <Filter className="h-4 w-4 text-muted-foreground" />
                      <SelectValue placeholder="筛选家族树" />
                    </div>
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">所有家族树</SelectItem>
                    {trees.map(tree => (
                      <SelectItem key={tree.id} value={tree.id}>
                        {tree.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <ScrollArea className="h-[400px] pr-4">
            {error ? (
              <div className="text-center py-8 text-destructive">
                加载失败: {error}
              </div>
            ) : loading && logs.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                加载中...
              </div>
            ) : logs.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                暂无操作记录
              </div>
            ) : (
              <div className="space-y-3">
                {logs.map((log) => {
                  const EntityIcon = entityTypeIcons[log.entityType] || FileText
                  return (
                    <div
                      key={log.id}
                      className="flex items-start gap-3 p-3 bg-muted/50 rounded-lg hover:bg-muted transition-colors"
                    >
                      <div className={`p-2 rounded-full ${actionColors[log.action]} bg-opacity-10`}>
                        <EntityIcon className={`h-4 w-4 ${actionColors[log.action].replace('bg-', 'text-')}`} />
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1 flex-wrap">
                          <Badge variant="outline" className="text-xs">
                            {actionLabels[log.action] || log.action}
                          </Badge>
                          <Badge variant="secondary" className="text-xs">
                            {entityTypeLabels[log.entityType] || log.entityType}
                          </Badge>
                          {filterTreeId === "all" && log.tree && (
                            <Badge variant="outline" className="text-xs bg-blue-50 text-blue-700 border-blue-200">
                              {log.tree.name}
                            </Badge>
                          )}
                          {log.entityName && (
                            <span className="text-sm font-medium truncate">
                              {log.entityName}
                            </span>
                          )}
                        </div>
                        <div className="flex items-center justify-between">
                          <p className="text-xs text-muted-foreground">
                            {log.user?.name || log.user?.email || "未知用户"}
                          </p>
                          <p className="text-xs text-muted-foreground">
                            {format(new Date(log.timestamp), "yyyy-MM-dd HH:mm:ss")}
                          </p>
                        </div>
                        {log.changes && Object.keys(log.changes).length > 0 && (
                          <details className="mt-2">
                            <summary className="text-xs text-muted-foreground cursor-pointer hover:text-foreground">
                              查看变更详情
                            </summary>
                            <pre className="text-xs mt-1 p-2 bg-background rounded overflow-x-auto">
                              {JSON.stringify(log.changes, null, 2)}
                            </pre>
                          </details>
                        )}
                      </div>
                    </div>
                  )
                })}
              </div>
            )}
          </ScrollArea>
        </CardContent>
      </Card>
    </div>
  )
}

