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 { NetworkLog as NetworkLogType } from '../../types/monitor';
import { Search, Download, Eye, Globe, Clock } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function NetworkLog() {
  const [logs, setLogs] = useState<NetworkLogType[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [methodFilter, setMethodFilter] = useState<string>('all');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedLog, setSelectedLog] = useState<NetworkLogType | null>(null);

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

  const loadLogs = () => {
    const data = localStorage.getItem('smart_agriculture_network_logs');
    if (data) {
      setLogs(JSON.parse(data));
    } else {
      const mockLogs: NetworkLogType[] = [
        {
          id: 'net-1',
          timestamp: '2024-10-14T09:35:00',
          method: 'POST',
          url: '/api/users',
          requestParams: 'username=zhangsan&name=张三',
          responseStatus: 200,
          responseTime: 150,
          responseSize: 256,
          clientIp: '192.168.1.100',
          userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/118.0.0.0',
          userId: 'user-1',
          username: 'admin',
        },
        {
          id: 'net-2',
          timestamp: '2024-10-14T10:20:00',
          method: 'GET',
          url: '/api/machinery/list',
          requestParams: 'page=1&size=10',
          responseStatus: 200,
          responseTime: 89,
          responseSize: 4096,
          clientIp: '192.168.1.101',
          userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Safari/17.0',
          userId: 'user-2',
          username: 'zhangsan',
        },
        {
          id: 'net-3',
          timestamp: '2024-10-14T11:25:00',
          method: 'DELETE',
          url: '/api/roles/456',
          responseStatus: 400,
          responseTime: 120,
          responseSize: 128,
          clientIp: '192.168.1.102',
          userAgent: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/118.0.0.0',
          userId: 'user-3',
          username: 'lisi',
        },
        {
          id: 'net-4',
          timestamp: '2024-10-14T14:50:00',
          method: 'PUT',
          url: '/api/system/settings',
          requestParams: 'sessionTimeout=30',
          responseStatus: 200,
          responseTime: 95,
          responseSize: 512,
          clientIp: '192.168.1.100',
          userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/118.0.0.0',
          userId: 'user-1',
          username: 'admin',
        },
        {
          id: 'net-5',
          timestamp: '2024-10-14T15:35:00',
          method: 'POST',
          url: '/api/tasks',
          responseStatus: 201,
          responseTime: 180,
          responseSize: 1024,
          clientIp: '192.168.1.101',
          userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Safari/17.0',
          userId: 'user-2',
          username: 'zhangsan',
        },
        {
          id: 'net-6',
          timestamp: '2024-10-14T16:15:00',
          method: 'GET',
          url: '/api/users/export',
          requestParams: 'format=excel',
          responseStatus: 200,
          responseTime: 1250,
          responseSize: 102400,
          clientIp: '192.168.1.100',
          userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/118.0.0.0',
          userId: 'user-1',
          username: 'admin',
        },
      ];
      localStorage.setItem('smart_agriculture_network_logs', JSON.stringify(mockLogs));
      setLogs(mockLogs);
    }
  };

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

    const matchMethod = methodFilter === 'all' || log.method === methodFilter;

    let matchStatus = true;
    if (statusFilter !== 'all') {
      const status = log.responseStatus;
      switch (statusFilter) {
        case '2xx':
          matchStatus = status >= 200 && status < 300;
          break;
        case '4xx':
          matchStatus = status >= 400 && status < 500;
          break;
        case '5xx':
          matchStatus = status >= 500;
          break;
      }
    }

    return matchKeyword && matchMethod && matchStatus;
  });

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

  const getMethodBadge = (method: string) => {
    const colors: Record<string, string> = {
      GET: 'bg-blue-100 text-blue-700',
      POST: 'bg-green-100 text-green-700',
      PUT: 'bg-yellow-100 text-yellow-700',
      DELETE: 'bg-red-100 text-red-700',
      PATCH: 'bg-purple-100 text-purple-700',
    };
    return colors[method] || 'bg-gray-100 text-gray-700';
  };

  const getStatusBadge = (status: number) => {
    if (status >= 200 && status < 300) {
      return 'bg-green-100 text-green-700';
    } else if (status >= 400 && status < 500) {
      return 'bg-yellow-100 text-yellow-700';
    } else if (status >= 500) {
      return 'bg-red-100 text-red-700';
    }
    return 'bg-gray-100 text-gray-700';
  };

  const formatBytes = (bytes: number) => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
  };

  const stats = [
    {
      label: '总请求数',
      value: logs.length,
      color: 'text-blue-600',
    },
    {
      label: '成功请求',
      value: logs.filter(l => l.responseStatus >= 200 && l.responseStatus < 300).length,
      color: 'text-green-600',
    },
    {
      label: '失败请求',
      value: logs.filter(l => l.responseStatus >= 400).length,
      color: 'text-red-600',
    },
    {
      label: '平均响应时间',
      value: logs.length > 0
        ? Math.round(logs.reduce((sum, l) => sum + l.responseTime, 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-3 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="搜索URL、用户名..."
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              className="pl-10"
            />
          </div>
          <Select value={methodFilter} onValueChange={setMethodFilter}>
            <SelectTrigger>
              <SelectValue placeholder="请求方法" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部方法</SelectItem>
              <SelectItem value="GET">GET</SelectItem>
              <SelectItem value="POST">POST</SelectItem>
              <SelectItem value="PUT">PUT</SelectItem>
              <SelectItem value="DELETE">DELETE</SelectItem>
              <SelectItem value="PATCH">PATCH</SelectItem>
            </SelectContent>
          </Select>
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger>
              <SelectValue placeholder="响应状态" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部状态</SelectItem>
              <SelectItem value="2xx">2xx 成功</SelectItem>
              <SelectItem value="4xx">4xx 客户端错误</SelectItem>
              <SelectItem value="5xx">5xx 服务器错误</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 日志列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>时间</TableHead>
              <TableHead>方法</TableHead>
              <TableHead>URL</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 className="text-sm text-muted-foreground">
                    {new Date(log.timestamp).toLocaleTimeString('zh-CN')}
                  </TableCell>
                  <TableCell>
                    <Badge className={getMethodBadge(log.method)}>
                      {log.method}
                    </Badge>
                  </TableCell>
                  <TableCell className="max-w-xs truncate text-sm">
                    {log.url}
                  </TableCell>
                  <TableCell className="text-sm">{log.username || '-'}</TableCell>
                  <TableCell>
                    <Badge className={getStatusBadge(log.responseStatus)}>
                      {log.responseStatus}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-sm">
                    <div className="flex items-center gap-1">
                      <Clock className="w-3 h-3 text-gray-400" />
                      {log.responseTime}ms
                    </div>
                  </TableCell>
                  <TableCell className="text-sm">
                    {log.responseSize ? formatBytes(log.responseSize) : '-'}
                  </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">
                <Globe 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">{new Date(selectedLog.timestamp).toLocaleString('zh-CN')}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">请求方法</p>
                  <p className="mt-1">
                    <Badge className={getMethodBadge(selectedLog.method)}>
                      {selectedLog.method}
                    </Badge>
                  </p>
                </div>
                <div className="col-span-2">
                  <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 block">
                      {selectedLog.url}
                    </code>
                  </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.clientIp}
                    </code>
                  </p>
                </div>
                <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">
                    <Badge className={getStatusBadge(selectedLog.responseStatus)}>
                      {selectedLog.responseStatus}
                    </Badge>
                  </p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">响应时间</p>
                  <p className="mt-1">{selectedLog.responseTime}ms</p>
                </div>
                {selectedLog.responseSize && (
                  <div>
                    <p className="text-sm text-muted-foreground">响应大小</p>
                    <p className="mt-1">{formatBytes(selectedLog.responseSize)}</p>
                  </div>
                )}
              </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">
                    {selectedLog.requestParams}
                  </pre>
                </div>
              )}
              {selectedLog.userAgent && (
                <div>
                  <p className="text-sm text-muted-foreground">User Agent</p>
                  <p className="mt-1 text-xs text-muted-foreground">
                    {selectedLog.userAgent}
                  </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">
          <Globe className="w-4 h-4 inline mr-2" />
          网络日志说明
        </h4>
        <ul className="space-y-1 text-sm text-blue-800">
          <li>• 记录所有HTTP请求的详细信息，包括请求地址、参数、响应状态等</li>
          <li>• 响应时间超过1秒的请求需要关注，可能存在性能问题</li>
          <li>• 4xx状态码通常表示客户端错误，5xx表示服务器错误</li>
          <li>• 可用于接口调试、性能分析和异常排查</li>
          <li>• 建议定期清理历史日志，避免占用过多存储空间</li>
        </ul>
      </Card>
    </div>
  );
}
