/**
 * filekorolheader: 登录日志页面 - 用户登录行为监控页面
 * 功能：登录日志查询、统计、导出、筛选
 * 路径：/central-config/monitor/login-log
 * 规范：遵循crop-x/docs/开发项目规范.md，使用SearchFormPagination重构，事件驱动模式
 */
'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Download, Eye, AlertTriangle, CheckCircle, XCircle } from 'lucide-react';

import { SearchFormPagination, type SearchFieldConfig, type TableColumnConfig } from '@/components/common/searchFormPagination';
import {
  fetchLoginLogs,
  transformLoginLogsList,
  LoginLog,
  PaginationState,
  LoginLogsQueryParams,
  fetchLoginStatistics,
  exportLoginLogs
} from './components/loginLogApi';

export default function LoginLogPage() {
  const [logs, setLogs] = useState<LoginLog[]>([]);
  const [loading, setLoading] = useState(false);
  const [statistics, setStatistics] = useState<any>(null);
  const [pagination, setPagination] = useState<PaginationState>({
    page: 1,
    size: 10,
    total: 0,
    totalPages: 0,
    hasNext: false,
    hasPrev: false,
  });
  const [searchFilters, setSearchFilters] = useState<Record<string, string>>({
    search: '',
    status: 'all'
  });
  const isFirstLoad = useRef(true);

  // 搜索字段配置
  const searchFields: SearchFieldConfig[] = [
    {
      key: 'search',
      label: '搜索',
      type: 'text',
      placeholder: '搜索用户名、IP地址...',
    },
    {
      key: 'status',
      label: '登录状态',
      type: 'select',
      defaultValue: 'all',
      options: [
        { value: 'all', label: '全部状态' },
        { value: 'success', label: '成功' },
        { value: 'failed', label: '失败' },
      ],
    },
    {
      key: 'dateRange',
      label: '时间范围',
      type: 'select',
      defaultValue: 'all',
      options: [
        { value: 'all', label: '全部时间' },
        { value: 'today', label: '今天' },
        { value: 'week', label: '最近7天' },
        { value: 'month', label: '最近30天' },
      ],
    },
  ];

  // 表格列配置
  const columns: TableColumnConfig[] = [
    {
      key: 'created_at',
      label: '登录时间',
      render: (value: string) => (
        <div className="text-sm text-muted-foreground">
          {value ? new Date(value).toLocaleString('zh-CN') : '-'}
        </div>
      ),
    },
    {
      key: 'username',
      label: '用户名',
      render: (value: string) => (
        <div className="font-medium text-foreground">{value || '-'}</div>
      ),
    },
    {
      key: 'ip_address',
      label: 'IP地址',
      render: (value: string) => (
        <div className="font-mono text-sm">{value || '-'}</div>
      ),
    },
    {
      key: 'user_agent',
      label: '设备信息',
      render: (value: string) => (
        <div className="text-sm text-muted-foreground max-w-[200px] truncate" title={value}>
          {value || '-'}
        </div>
      ),
    },
    {
      key: 'location',
      label: '登录地点',
      render: (value: string) => (
        <div className="text-sm text-muted-foreground">{value || '-'}</div>
      ),
    },
    {
      key: 'status',
      label: '状态',
      render: (value: string) => {
        if (value === 'success') {
          return (
            <Badge className="bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">
              <CheckCircle className="w-3 h-3 mr-1" />
              成功
            </Badge>
          );
        } else {
          return (
            <Badge className="bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200">
              <XCircle className="w-3 h-3 mr-1" />
              失败
            </Badge>
          );
        }
      },
    },
    {
      key: 'is_suspicious',
      label: '安全状态',
      render: (value: boolean) => {
        if (value) {
          return (
            <Badge className="bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200">
              <AlertTriangle className="w-3 h-3 mr-1" />
              可疑
            </Badge>
          );
        } else {
          return (
            <Badge className="bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
              <CheckCircle className="w-3 h-3 mr-1" />
              正常
            </Badge>
          );
        }
      },
    },
    {
      key: 'failure_reason',
      label: '失败原因',
      render: (value: string) => (
        <div className="text-sm text-muted-foreground max-w-[150px] truncate" title={value}>
          {value || '-'}
        </div>
      ),
    },
    {
      key: 'actions',
      label: '操作',
      render: (_: any, row: LoginLog) => (
        <div className="flex gap-2">
          <Button
            size="sm"
            variant="outline"
            onClick={() => handleViewDetail(row)}
            className="h-8 px-2"
            title="查看详情"
          >
            <Eye className="w-3 h-3 mr-1" />
            查看
          </Button>
        </div>
      ),
    },
  ];

  // 加载登录日志数据 - 事件驱动模式
  const loadLoginLogs = useCallback(async (params?: {
    filters?: Record<string, string>;
    pagination?: { page: number; size: number };
    resetPage?: boolean;
  }) => {
    try {
      setLoading(true);

      const queryParams: LoginLogsQueryParams = {
        page: params?.resetPage ? 1 : (params?.pagination?.page || pagination.page),
        size: params?.pagination?.size || pagination.size,
        sort_order: 'desc',
        order_by: 'created_at',
      };

      // 处理搜索条件
      const searchKeyword = params?.filters?.search ?? searchFilters.search;
      if (searchKeyword) {
        queryParams.username = searchKeyword;
        queryParams.ip_address = searchKeyword;
      }

      // 处理状态筛选
      const status = params?.filters?.status ?? searchFilters.status;
      if (status !== 'all') {
        queryParams.status = status;
      }

      // 处理时间范围
      const dateRange = params?.filters?.dateRange ?? searchFilters.dateRange;
      if (dateRange !== 'all') {
        const now = new Date();
        let startTime: string;

        switch (dateRange) {
          case 'today':
            startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0).toISOString();
            break;
          case 'week':
            startTime = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString();
            break;
          case 'month':
            startTime = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000).toISOString();
            break;
        }

        if (startTime) {
          queryParams.start_time = startTime;
          queryParams.end_time = now.toISOString();
        }
      }

      const response = await fetchLoginLogs(queryParams);
      const transformedLogs = transformLoginLogsList(response.data);

      setLogs(transformedLogs);
      setPagination({
        page: response.page,
        size: response.size,
        total: response.total,
        totalPages: response.total === 0 
        ? 0 
        : Math.floor(response.total / response.size) + 1,
        hasNext: response.hasNext,
        hasPrev: response.hasPrev,
      });
    } catch (error) {
      console.error('Failed to load login logs:', error);
      const errorMessage = error instanceof Error ? error.message : '加载登录日志失败';
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, [pagination.page, pagination.size, searchFilters]);

  // 事件处理器 - 事件驱动模式
  const handleSearch = useCallback((filters: Record<string, string>) => {
    setSearchFilters(filters);
    loadLoginLogs({
      filters,
      pagination: { page: 1, size: pagination.size }
    });
  }, [loadLoginLogs, pagination.size]);

  const handlePageChange = useCallback((page: number) => {
    setPagination(prev => ({ ...prev, page }));
    loadLoginLogs({
      filters: searchFilters,
      pagination: { page, size: pagination.size }
    });
  }, [loadLoginLogs, searchFilters, pagination.size]);

  const handleSizeChange = useCallback((size: number) => {
    setPagination(prev => ({ ...prev, size, page: 1 }));
    loadLoginLogs({
      filters: searchFilters,
      pagination: { page: 1, size }
    });
  }, [loadLoginLogs, searchFilters]);

  // 查看详情
  const handleViewDetail = (log: LoginLog) => {
    toast.info(`查看登录日志详情: ${log.username} - ${log.ip_address}`);
  };

  // 导出日志
  const handleExport = async () => {
    try {
      setLoading(true);
      const exportData = await exportLoginLogs({
        username: searchFilters.search,
        status: searchFilters.status === 'all' ? undefined : searchFilters.status,
        start_time: searchFilters.dateRange === 'all' ? undefined :
          searchFilters.dateRange === 'today' ? new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), 0, 0, 0).toISOString() :
          searchFilters.dateRange === 'week' ? new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString() :
          searchFilters.dateRange === 'month' ? new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString() : undefined,
        end_time: new Date().toISOString(),
      });

      // 创建下载链接
      const dataStr = JSON.stringify(exportData, 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();
      URL.revokeObjectURL(url);

      toast.success('导出成功');
    } catch (error) {
      console.error('Failed to export login logs:', error);
      const errorMessage = error instanceof Error ? error.message : '导出失败';
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  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} disabled={loading}>
          <Download className="w-4 h-4 mr-2" />
          导出日志
        </Button>
      </div>

      {/* 统计卡片 */}
      {statistics && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="p-6 bg-card hover:bg-muted transition-colors border rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <div className="text-sm text-muted-foreground">总登录次数</div>
              <div className="text-2xl font-bold text-blue-600">{statistics.total_logins}</div>
            </div>
            <div className="text-xs text-muted-foreground">
              系统总登录次数
            </div>
          </div>
          <div className="p-6 bg-card hover:bg-muted transition-colors border rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <div className="text-sm text-muted-foreground">成功登录</div>
              <div className="text-2xl font-bold text-green-600">{statistics.successful_logins}</div>
            </div>
            <div className="text-xs text-green-600">
              登录成功次数
            </div>
          </div>
          <div className="p-6 bg-card hover:bg-muted transition-colors border rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <div className="text-sm text-muted-foreground">失败登录</div>
              <div className="text-2xl font-bold text-red-600">{statistics.failed_logins}</div>
            </div>
            <div className="text-xs text-red-600">
              登录失败次数
            </div>
          </div>
          <div className="p-6 bg-card hover:bg-muted transition-colors border rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <div className="text-sm text-muted-foreground">成功率</div>
              <div className="text-2xl font-bold text-purple-600">{Math.round(statistics.success_rate * 100)}%</div>
            </div>
            <div className="text-xs text-purple-600">
              登录成功率
            </div>
          </div>
        </div>
      )}

      {/* 搜索、表格和分页 */}
      <SearchFormPagination
        formTitle="登录日志列表"
        searchFields={searchFields}
        columns={columns}
        data={logs}
        loading={loading}
        error={null}
        pagination={pagination}
        onPageChange={handlePageChange}
        onSizeChange={handleSizeChange}
        onSearch={handleSearch}
        emptyText="暂无登录日志数据"
        showSizeSelector={true}
        showPageInfo={true}
        sizeOptions={[10, 20, 50, 100]}
      />
    </div>
  );
}