import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Badge } from '../ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { OperationLog as OperationLogType } from '../../types/monitor';
import { Search, Download, FileText, Eye, Activity } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function OperationLog() {
  const [logs, setLogs] = useState<OperationLogType[]>([]);
  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<OperationLogType | null>(null);

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

  const loadLogs = () => {
    const data = localStorage.getItem('smart_agriculture_operation_logs');
    if (data) {
      setLogs(JSON.parse(data));
    } else {
      const mockLogs: OperationLogType[] = [
        {
          id: 'op-1',
          userId: 'user-1',
          username: 'admin',
          operationTime: '2024-10-14T09:35:00',
          module: 'user',
          action: 'create',
          description: '创建用户账号: zhangsan',
          ipAddress: '192.168.1.100',
          requestUrl: '/api/users',
          requestMethod: 'POST',
          requestParams: JSON.stringify({ username: 'zhangsan', name: '张三' }),
          duration: 150,
          status: 'success',
        },
        {
          id: 'op-2',
          userId: 'user-2',
          username: 'zhangsan',
          operationTime: '2024-10-14T10:20:00',
          module: 'machinery',
          action: 'update',
          description: '更新农机信息: 约翰迪尔拖拉机',
          ipAddress: '192.168.1.101',
          requestUrl: '/api/machinery/123',
          requestMethod: 'PUT',
          duration: 89,
          status: 'success',
        },
        {
          id: 'op-3',
          userId: 'user-3',
          username: 'lisi',
          operationTime: '2024-10-14T11:25:00',
          module: 'role',
          action: 'delete',
          description: '删除角色: 临时操作员',
          ipAddress: '192.168.1.102',
          requestUrl: '/api/roles/456',
          requestMethod: 'DELETE',
          duration: 120,
          status: 'failed',
          errorMessage: '该角色下仍有关联用户，无法删除',
        },
        {
          id: 'op-4',
          userId: 'user-1',
          username: 'admin',
          operationTime: '2024-10-14T14:50:00',
          module: 'system',
          action: 'update',
          description: '修改系统配置: 会话超时时间',
          ipAddress: '192.168.1.100',
          requestUrl: '/api/system/settings',
          requestMethod: 'PUT',
          duration: 95,
          status: 'success',
        },
        {
          id: 'op-5',
          userId: 'user-2',
          username: 'zhangsan',
          operationTime: '2024-10-14T15:35:00',
          module: 'task',
          action: 'create',
          description: '创建作业任务: 小麦播种作业',
          ipAddress: '192.168.1.101',
          requestUrl: '/api/tasks',
          requestMethod: 'POST',
          duration: 180,
          status: 'success',
        },
        {
          id: 'op-6',
          userId: 'user-1',
          username: 'admin',
          operationTime: '2024-10-14T16:15:00',
          module: 'user',
          action: 'export',
          description: '导出用户列表数据',
          ipAddress: '192.168.1.100',
          requestUrl: '/api/users/export',
          requestMethod: 'GET',
          duration: 1250,
          status: 'success',
        },
      ];
      localStorage.setItem('smart_agriculture_operation_logs', JSON.stringify(mockLogs));
      setLogs(mockLogs);
    }
  };

  const filteredLogs = logs.filter(log => {
    const matchKeyword = !searchKeyword ||
      log.username.includes(searchKeyword) ||
      log.description.includes(searchKeyword) ||
      log.module.includes(searchKeyword);

    const matchModule = moduleFilter === 'all' || log.module === moduleFilter;
    const matchAction = actionFilter === 'all' || log.action === actionFilter;
    const matchStatus = statusFilter === 'all' || log.status === statusFilter;

    return matchKeyword && matchModule && matchAction && matchStatus;
  });

  const handleViewDetail = (log: OperationLogType) => {
    setSelectedLog(log);
    setShowDetailDialog(true);
  };

  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 = `operation_logs_${new Date().getTime()}.json`;
    link.click();
    toast.success('导出成功');
  };

  const getModuleLabel = (module: string) => {
    const labels: Record<string, string> = {
      user: '用户管理',
      role: '角色管理',
      permission: '权限管理',
      machinery: '农机管理',
      driver: '驾驶员管理',
      task: '任务管理',
      system: '系统配置',
      other: '其他',
    };
    return labels[module] || module;
  };

  const getActionLabel = (action: string) => {
    const labels: Record<string, string> = {
      create: '新增',
      update: '修改',
      delete: '删除',
      view: '查看',
      export: '导出',
      import: '导入',
      login: '登录',
      logout: '登出',
    };
    return labels[action] || action;
  };

  const getActionBadge = (action: string) => {
    const colors: Record<string, string> = {
      create: 'bg-green-100 text-green-700',
      update: 'bg-blue-100 text-blue-700',
      delete: 'bg-red-100 text-red-700',
      view: 'bg-gray-100 text-gray-700',
      export: 'bg-purple-100 text-purple-700',
      import: 'bg-yellow-100 text-yellow-700',
    };
    return colors[action] || 'bg-gray-100 text-gray-700';
  };

  const stats = [
    {
      label: '总操作数',
      value: logs.length,
      color: 'text-blue-600',
    },
    {
      label: '成功操作',
      value: logs.filter(l => l.status === 'success').length,
      color: 'text-green-600',
    },
    {
      label: '失败操作',
      value: logs.filter(l => l.status === 'failed').length,
      color: 'text-red-600',
    },
    {
      label: '平均耗时',
      value: logs.length > 0
        ? Math.round(logs.reduce((sum, l) => sum + (l.duration || 0), 0) / logs.length) + 'ms'
        : '0ms',
      color: 'text-purple-600',
    },
  ];

  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>

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {stats.map((stat, index) => (
          <Card key={index} className="p-4">
            <div className="text-sm text-muted-foreground">{stat.label}</div>
            <div className={`mt-2 ${stat.color}`}>{stat.value}</div>
          </Card>
        ))}
      </div>

      {/* 搜索和筛选 */}
      <Card className="p-4">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              placeholder="搜索用户名、操作描述..."
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              className="pl-10"
            />
          </div>
          <Select value={moduleFilter} onValueChange={setModuleFilter}>
            <SelectTrigger>
              <SelectValue placeholder="操作模块" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部模块</SelectItem>
              <SelectItem value="user">用户管理</SelectItem>
              <SelectItem value="role">角色管理</SelectItem>
              <SelectItem value="permission">权限管理</SelectItem>
              <SelectItem value="machinery">农机管理</SelectItem>
              <SelectItem value="driver">驾驶员管理</SelectItem>
              <SelectItem value="task">任务管理</SelectItem>
              <SelectItem value="system">系统配置</SelectItem>
            </SelectContent>
          </Select>
          <Select value={actionFilter} onValueChange={setActionFilter}>
            <SelectTrigger>
              <SelectValue placeholder="操作类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部类型</SelectItem>
              <SelectItem value="create">新增</SelectItem>
              <SelectItem value="update">修改</SelectItem>
              <SelectItem value="delete">删除</SelectItem>
              <SelectItem value="view">查看</SelectItem>
              <SelectItem value="export">导出</SelectItem>
              <SelectItem value="import">导入</SelectItem>
            </SelectContent>
          </Select>
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger>
              <SelectValue placeholder="操作状态" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部状态</SelectItem>
              <SelectItem value="success">成功</SelectItem>
              <SelectItem value="failed">失败</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 日志列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>操作人</TableHead>
              <TableHead>操作时间</TableHead>
              <TableHead>模块</TableHead>
              <TableHead>操作</TableHead>
              <TableHead>描述</TableHead>
              <TableHead>耗时</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredLogs.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8} className="text-center text-muted-foreground py-8">
                  暂无操作日志
                </TableCell>
              </TableRow>
            ) : (
              filteredLogs.map((log) => (
                <TableRow key={log.id}>
                  <TableCell>{log.username}</TableCell>
                  <TableCell className="text-muted-foreground text-sm">
                    {new Date(log.operationTime).toLocaleString('zh-CN')}
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">{getModuleLabel(log.module)}</Badge>
                  </TableCell>
                  <TableCell>
                    <Badge className={getActionBadge(log.action)}>
                      {getActionLabel(log.action)}
                    </Badge>
                  </TableCell>
                  <TableCell className="max-w-xs truncate">{log.description}</TableCell>
                  <TableCell className="text-sm">
                    {log.duration ? `${log.duration}ms` : '-'}
                  </TableCell>
                  <TableCell>
                    {log.status === 'success' ? (
                      <Badge className="bg-green-100 text-green-700">成功</Badge>
                    ) : (
                      <Badge className="bg-red-100 text-red-700">失败</Badge>
                    )}
                  </TableCell>
                  <TableCell>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleViewDetail(log)}
                    >
                      <Eye className="w-4 h-4" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              <div className="flex items-center gap-2">
                <FileText className="w-5 h-5 text-green-600" />
                操作日志详情
              </div>
            </DialogTitle>
            <DialogDescription className="sr-only">
              查看操作日志详细信息
            </DialogDescription>
          </DialogHeader>
          {selectedLog && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-muted-foreground">操作人</p>
                  <p className="mt-1">{selectedLog.username}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">操作时间</p>
                  <p className="mt-1">{new Date(selectedLog.operationTime).toLocaleString('zh-CN')}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">操作模块</p>
                  <p className="mt-1">{getModuleLabel(selectedLog.module)}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">操作类型</p>
                  <p className="mt-1">{getActionLabel(selectedLog.action)}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">IP地址</p>
                  <p className="mt-1">
                    <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                      {selectedLog.ipAddress}
                    </code>
                  </p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">耗时</p>
                  <p className="mt-1">{selectedLog.duration}ms</p>
                </div>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">操作描述</p>
                <p className="mt-1">{selectedLog.description}</p>
              </div>
              {selectedLog.requestUrl && (
                <div>
                  <p className="text-sm text-muted-foreground">请求URL</p>
                  <p className="mt-1">
                    <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                      {selectedLog.requestMethod} {selectedLog.requestUrl}
                    </code>
                  </p>
                </div>
              )}
              {selectedLog.requestParams && (
                <div>
                  <p className="text-sm text-muted-foreground">请求参数</p>
                  <pre className="mt-1 p-3 bg-gray-50 rounded text-xs overflow-x-auto">
                    {JSON.stringify(JSON.parse(selectedLog.requestParams), null, 2)}
                  </pre>
                </div>
              )}
              {selectedLog.errorMessage && (
                <div>
                  <p className="text-sm text-muted-foreground">错误信息</p>
                  <p className="mt-1 text-red-600">{selectedLog.errorMessage}</p>
                </div>
              )}
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 使用说明 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <h4 className="text-blue-900 mb-2">
          <Activity className="w-4 h-4 inline mr-2" />
          操作日志说明
        </h4>
        <ul className="space-y-1 text-sm text-blue-800">
          <li>• 记录用户在系统中的所有关键操作，包括数据修改、流程触发、配置变更等</li>
          <li>• 详细记录操作人、时间、模块、动作及请求详情</li>
          <li>• 支持按多个维度进行复杂条件搜索和过滤</li>
          <li>• 可查看原始请求信息，满足运维审计需求</li>
          <li>• 失败操作会记录错误信息，便于事故追溯</li>
        </ul>
      </Card>
    </div>
  );
}
