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 { Label } from '../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { LoginLog as LoginLogType } from '../../types/monitor';
import { Search, Download, Shield, MapPin, Monitor } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

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

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

  const loadLogs = () => {
    const data = localStorage.getItem('smart_agriculture_login_logs');
    if (data) {
      setLogs(JSON.parse(data));
    } else {
      const mockLogs: LoginLogType[] = [
        {
          id: 'log-1',
          userId: 'user-1',
          username: 'admin',
          loginTime: '2024-10-14T09: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-14T10: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-14T11: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-14T14: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-14T15: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-13T16:20:00',
          ipAddress: '192.168.1.104',
          device: 'Windows 10',
          browser: 'Edge 118',
          os: 'Windows',
          location: '杭州市西湖区',
          status: 'success',
          sessionId: 'sess-004',
        },
      ];
      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('导出成功');
  };

  const stats = [
    {
      label: '总登录次数',
      value: logs.length,
      color: 'text-blue-600',
      bg: 'bg-blue-100',
    },
    {
      label: '成功登录',
      value: logs.filter(l => l.status === 'success').length,
      color: 'text-green-600',
      bg: 'bg-green-100',
    },
    {
      label: '失败登录',
      value: logs.filter(l => l.status === 'failed').length,
      color: 'text-red-600',
      bg: 'bg-red-100',
    },
    {
      label: '今日登录',
      value: logs.filter(l => {
        const logDate = new Date(l.loginTime);
        const today = new Date();
        return logDate.toDateString() === today.toDateString();
      }).length,
      color: 'text-purple-600',
      bg: 'bg-purple-100',
    },
  ];

  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="搜索用户名、IP地址、位置..."
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              className="pl-10"
            />
          </div>
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger>
              <SelectValue placeholder="登录状态" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部状态</SelectItem>
              <SelectItem value="success">成功</SelectItem>
              <SelectItem value="failed">失败</SelectItem>
            </SelectContent>
          </Select>
          <Select value={dateRange} onValueChange={setDateRange}>
            <SelectTrigger>
              <SelectValue placeholder="时间范围" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部时间</SelectItem>
              <SelectItem value="today">今天</SelectItem>
              <SelectItem value="week">近7天</SelectItem>
              <SelectItem value="month">近30天</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 日志列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>用户名</TableHead>
              <TableHead>登录时间</TableHead>
              <TableHead>IP地址</TableHead>
              <TableHead>设备/浏览器</TableHead>
              <TableHead>位置</TableHead>
              <TableHead>状态</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredLogs.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                  暂无登录日志
                </TableCell>
              </TableRow>
            ) : (
              filteredLogs.map((log) => (
                <TableRow key={log.id}>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Shield className="w-4 h-4 text-gray-400" />
                      {log.username}
                    </div>
                  </TableCell>
                  <TableCell className="text-muted-foreground">
                    {new Date(log.loginTime).toLocaleString('zh-CN')}
                  </TableCell>
                  <TableCell>
                    <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                      {log.ipAddress}
                    </code>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Monitor className="w-4 h-4 text-gray-400" />
                      <div className="text-sm">
                        <div>{log.device}</div>
                        {log.browser && (
                          <div className="text-xs text-muted-foreground">{log.browser}</div>
                        )}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    {log.location && (
                      <div className="flex items-center gap-1 text-sm">
                        <MapPin className="w-3 h-3 text-gray-400" />
                        {log.location}
                      </div>
                    )}
                  </TableCell>
                  <TableCell>
                    {log.status === 'success' ? (
                      <Badge className="bg-green-100 text-green-700">成功</Badge>
                    ) : (
                      <div>
                        <Badge className="bg-red-100 text-red-700">失败</Badge>
                        {log.failReason && (
                          <p className="text-xs text-red-600 mt-1">{log.failReason}</p>
                        )}
                      </div>
                    )}
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 使用说明 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <h4 className="text-blue-900 mb-2">
          <Shield className="w-4 h-4 inline mr-2" />
          登录日志说明
        </h4>
        <ul className="space-y-1 text-sm text-blue-800">
          <li>• 记录所有用户的登录行为，包括成功和失败的登录尝试</li>
          <li>• 支持按用户名、IP地址、位置等多条件检索</li>
          <li>• 登录失败会记录失败原因，便于安全审计</li>
          <li>• 可用于识别异常登录行为和未授权访问尝试</li>
          <li>• 日志数据可导出用于长期归档和合规审计</li>
        </ul>
      </Card>
    </div>
  );
}
