import React, { useEffect, useState, useMemo, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { Button } from '@/components/ui/button';
import { PaginatedTable, type ColumnDef, type SearchFieldDef, type PaginatedTableRef } from '@/components/ui/paginated-table';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { useToast } from '@/components/ui/use-toast';
import { RefreshCw, Users, TrendingUp, Clock, LogOut } from 'lucide-react';
import { getOnlineUsers, getOnlineStatistics, kickUser } from './service';
import type { OnlineUserResponse, OnlineStatistics, OnlineUserQuery } from './types';
import dayjs from 'dayjs';

const OnlineUserList: React.FC = () => {
  const { toast } = useToast();
  const tableRef = useRef<PaginatedTableRef<OnlineUserResponse>>(null);
  const [statistics, setStatistics] = useState<OnlineStatistics | null>(null);
  const [kickDialogOpen, setKickDialogOpen] = useState(false);
  const [selectedUser, setSelectedUser] = useState<OnlineUserResponse | null>(null);

  // 加载统计数据
  const loadStatistics = async () => {
    try {
      const stats = await getOnlineStatistics();
      setStatistics(stats);
    } catch (error) {
      console.error('加载统计失败:', error);
    }
  };

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

  // 包装 fetchFn，转换页码（后端从1开始）
  const fetchData = async (query: OnlineUserQuery) => {
    return await getOnlineUsers({
      ...query,
      pageNum: (query.pageNum || 0) + 1, // 转换为从1开始
      sortField: 'loginTime',
      sortOrder: 'desc',
    });
  };

  // 刷新
  const handleRefresh = () => {
    tableRef.current?.refresh();
    loadStatistics();
  };

  // 打开强制下线确认对话框
  const handleKickClick = (user: OnlineUserResponse) => {
    setSelectedUser(user);
    setKickDialogOpen(true);
  };

  // 确认强制下线
  const handleKickConfirm = async () => {
    if (!selectedUser) return;

    try {
      await kickUser(selectedUser.userId);
      toast({
        title: '操作成功',
        description: `用户 "${selectedUser.username}" 已被强制下线`,
      });
      setKickDialogOpen(false);
      setSelectedUser(null);
      tableRef.current?.refresh();
      loadStatistics();
    } catch (error) {
      console.error('强制下线失败:', error);
      toast({
        title: '操作失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive',
      });
    }
  };

  // 格式化在线时长
  const formatDuration = (seconds: number): string => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    
    if (hours > 0) {
      return `${hours}小时${minutes}分钟`;
    } else if (minutes > 0) {
      return `${minutes}分钟`;
    } else {
      return `${seconds}秒`;
    }
  };

  // 搜索字段定义
  const searchFields: SearchFieldDef[] = useMemo(() => [
    { key: 'keyword', type: 'input', placeholder: '搜索用户名/昵称', width: 'w-[220px]' },
  ], []);

  // 列定义
  const columns: ColumnDef<OnlineUserResponse>[] = useMemo(() => [
    { key: 'username', title: '用户名', dataIndex: 'username', width: '120px' },
    { key: 'nickname', title: '昵称', dataIndex: 'nickname', width: '120px' },
    { key: 'departmentName', title: '部门', dataIndex: 'departmentName', width: '120px' },
    {
      key: 'loginTime',
      title: '登录时间',
      width: '180px',
      render: (_, record) => dayjs(record.loginTime).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      key: 'onlineDuration',
      title: '在线时长',
      width: '120px',
      render: (_, record) => formatDuration(record.onlineDuration),
    },
    {
      key: 'lastActiveTime',
      title: '最后活跃',
      width: '180px',
      render: (_, record) => dayjs(record.lastActiveTime).format('YYYY-MM-DD HH:mm:ss'),
    },
    { key: 'ipAddress', title: 'IP地址', dataIndex: 'ipAddress', width: '140px' },
    { key: 'browser', title: '浏览器', dataIndex: 'browser', width: '120px' },
    { key: 'os', title: '操作系统', dataIndex: 'os', width: '120px' },
    {
      key: 'actions',
      title: '操作',
      width: '120px',
      sticky: true,
      render: (_, record) => (
        <Button
          type="button"
          variant="ghost"
          size="sm"
          onClick={() => handleKickClick(record)}
          className="text-red-600 hover:text-red-700 hover:bg-red-50"
        >
          <LogOut className="h-4 w-4 mr-1" />
          强制下线
        </Button>
      ),
    },
  ], []);

  // 工具栏
  const toolbar = (
    <Button onClick={handleRefresh} variant="outline" size="sm">
      <RefreshCw className="h-4 w-4 mr-1" />
      刷新
    </Button>
  );

  return (
    <div className="p-6 space-y-6">
      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">当前在线</CardTitle>
            <Users className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">
              {statistics?.totalOnline || 0}
            </div>
            <p className="text-xs text-muted-foreground">实时在线用户数</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">今日峰值</CardTitle>
            <TrendingUp className="h-4 w-4 text-orange-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-600">
              {statistics?.todayPeak || 0}
            </div>
            <p className="text-xs text-muted-foreground">今日最高在线人数</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">平均时长</CardTitle>
            <Clock className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {statistics?.averageOnlineTime || '-'}
            </div>
            <p className="text-xs text-muted-foreground">平均在线时长</p>
          </CardContent>
        </Card>
      </div>

      {/* 主内容卡片 */}
      <Card>
        <CardHeader>
          <CardTitle>在线用户列表</CardTitle>
        </CardHeader>
        <Separator />
        <CardContent className="pt-6">
          <PaginatedTable<OnlineUserResponse, OnlineUserQuery>
            ref={tableRef}
            fetchFn={fetchData}
            columns={columns}
            searchFields={searchFields}
            toolbar={toolbar}
            rowKey="userId"
            minWidth="1400px"
          />
        </CardContent>
      </Card>

      {/* 强制下线确认对话框 */}
      <AlertDialog open={kickDialogOpen} onOpenChange={setKickDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认强制下线</AlertDialogTitle>
            <AlertDialogDescription>
              确定要强制用户 <span className="font-semibold text-foreground">"{selectedUser?.username}"</span> 下线吗？
              <br />
              该操作将立即终止用户的会话。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={handleKickConfirm} className="bg-red-600 hover:bg-red-700">
              确认下线
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};

export default OnlineUserList;
