import React, { useState } from 'react';
import { Table, Button, Space, Input, Form, DatePicker, Select, Collapse } from 'antd';
import { SearchOutlined, FilterOutlined, DownOutlined, RightOutlined } from '@ant-design/icons';
import { useQuery } from '@tanstack/react-query';
import { operationLogsClient } from '@/client/api';
import type { InferResponseType } from 'hono/client';
import dayjs from 'dayjs';

// 定义类型
type LogfileItem = InferResponseType<typeof operationLogsClient.$get, 200>['data'][0];
type LogfileListResponse = InferResponseType<typeof operationLogsClient.$get, 200>;

const { RangePicker } = DatePicker;
const { Panel } = Collapse;

const Logs: React.FC = () => {
  const [form] = Form.useForm();
  const [advancedSearchExpanded, setAdvancedSearchExpanded] = useState(false);
  
  // 获取日志列表数据
  const fetchLogs = async ({
    page = 1,
    pageSize = 10,
    searchText = '',
    filters = {}
  }: {
    page?: number;
    pageSize?: number;
    searchText?: string;
    filters?: Record<string, any>;
  }): Promise<LogfileListResponse> => {
    const queryParams: Record<string, any> = { page, pageSize };
    
    if (searchText) queryParams.keyword = searchText;
    if (filters.resourceType) queryParams.resourceType = filters.resourceType;
    if (filters.action) queryParams.action = filters.action;
    if (filters.method) queryParams.method = filters.method;
    if (filters.endpoint) queryParams.endpoint = filters.endpoint;
    if (filters.userId) queryParams.userId = filters.userId;
    if (filters.username) queryParams.username = filters.username;
    if (filters.ipAddress) queryParams.ipAddress = filters.ipAddress;
    if (filters.status) queryParams.status = filters.status;
    if (filters.dateRange?.[0]) queryParams.startDate = filters.dateRange[0].format('YYYY-MM-DD');
    if (filters.dateRange?.[1]) queryParams.endDate = filters.dateRange[1].format('YYYY-MM-DD');
    
    const response = await operationLogsClient.$get({ query: queryParams });
    if (!response.ok) throw new Error('Failed to fetch logs');
    return response.json() as Promise<LogfileListResponse>;
  };
  
  // 表格列定义
  const columns = [
    {
      title: '日志ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '资源类型',
      dataIndex: 'resourceType',
      key: 'resourceType',
      width: 120,
    },
    {
      title: '资源ID',
      dataIndex: 'resourceId',
      key: 'resourceId',
      width: 120,
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 100,
    },
    {
      title: 'HTTP方法',
      dataIndex: 'method',
      key: 'method',
      width: 100,
    },
    {
      title: 'API端点',
      dataIndex: 'endpoint',
      key: 'endpoint',
      width: 200,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        switch (status) {
          case 'success':
            return <span style={{ color: '#52c41a' }}>成功</span>;
          case 'failed':
            return <span style={{ color: '#ff4d4f' }}>失败</span>;
          case 'permission_denied':
            return <span style={{ color: '#faad14' }}>权限拒绝</span>;
          default:
            return status;
        }
      },
    },
    {
      title: '耗时(ms)',
      dataIndex: 'duration',
      key: 'duration',
      width: 100,
    },
    {
      title: '操作用户ID',
      dataIndex: 'userId',
      key: 'userId',
      width: 100,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 120,
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      key: 'ipAddress',
      width: 150,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (time: string) => time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-',
    },
  ];
  
  // 使用React Query v5实现数据获取
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['logs', form.getFieldsValue(), form.getFieldValue('searchText')],
    queryFn: ({ signal }) => {
      const values = form.getFieldsValue();
      const searchText = form.getFieldValue('searchText') || '';
      
      return fetchLogs({
        page: values.pagination?.current || 1,
        pageSize: values.pagination?.pageSize || 10,
        searchText,
        filters: {
          resourceType: values.resourceType,
          action: values.action,
          method: values.method,
          endpoint: values.endpoint,
          userId: values.userId,
          username: values.username,
          ipAddress: values.ipAddress,
          status: values.status,
          dateRange: values.dateRange
        }
      });
    },
    staleTime: 1000 * 60 * 5, // 5分钟缓存
    gcTime: 1000 * 60 * 30, // 30分钟垃圾回收
  });
  
  // 处理搜索
  const handleSearch = () => {
    refetch();
  };
  
  // 处理过滤
  const handleFilterChange = () => {
    refetch();
  };
  
  // 处理分页变化
  const handleTableChange = (pagination: any) => {
    form.setFieldsValue({ pagination });
    refetch();
  };
  
  // 重置过滤条件
  const handleResetFilters = () => {
    form.resetFields();
    refetch();
  };
  
  return (
    <div className="p-4">
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-xl font-bold">系统日志管理</h2>
      </div>
      
      <div className="bg-white p-4 mb-4 rounded-lg shadow-sm">
        <Form
          form={form}
          onValuesChange={handleFilterChange}
          initialValues={{
            pagination: {
            current: 1,
            pageSize: 10
            }
          }}
        >
          {/* 常用搜索项 */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2 mb-2">
            <Form.Item name="resourceType" label="资源类型" className="mb-1">
              <Input placeholder="请输入资源类型" size="small" />
            </Form.Item>
            <Form.Item name="action" label="操作动作" className="mb-1">
              <Input placeholder="请输入操作动作" size="small" />
            </Form.Item>
            <Form.Item name="status" label="状态" className="mb-1">
              <Select placeholder="请选择状态" size="small">
                <Select.Option value="">全部</Select.Option>
                <Select.Option value="success">成功</Select.Option>
                <Select.Option value="failed">失败</Select.Option>
                <Select.Option value="permission_denied">权限拒绝</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item name="dateRange" label="操作时间" className="mb-1">
              <RangePicker format="YYYY-MM-DD" className="w-full" size="small" />
            </Form.Item>
          </div>
          
          {/* 高级搜索项折叠面板 */}
          <Collapse
            ghost
            expandIcon={({ isActive }) => isActive ? <DownOutlined /> : <RightOutlined />}
            className="mb-3"
          >
            <Panel header="高级搜索" key="1">
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2">
                <Form.Item name="method" label="HTTP方法" className="mb-1">
                  <Input placeholder="请输入HTTP方法" size="small" />
                </Form.Item>
                <Form.Item name="endpoint" label="API端点" className="mb-1">
                  <Input placeholder="请输入API端点" size="small" />
                </Form.Item>
                <Form.Item name="userId" label="操作用户ID" className="mb-1">
                  <Input placeholder="请输入用户ID" size="small" />
                </Form.Item>
                <Form.Item name="username" label="用户名" className="mb-1">
                  <Input placeholder="请输入用户名" size="small" />
                </Form.Item>
                <Form.Item name="ipAddress" label="IP地址" className="mb-1">
                  <Input placeholder="请输入IP地址" size="small" />
                </Form.Item>
              </div>
            </Panel>
          </Collapse>
          
          {/* 操作按钮和搜索框 */}
          <div className="flex flex-col sm:flex-row gap-2">
            <div className="flex gap-2">
              <Button type="primary" icon={<FilterOutlined />} onClick={handleFilterChange} size="small">
                筛选
              </Button>
              <Button onClick={handleResetFilters} size="small">
                重置
              </Button>
            </div>
            <div className="flex-grow flex gap-2">
              <Form.Item name="searchText" className="flex-grow mb-0">
                <Input
                  placeholder="搜索日志内容"
                  prefix={<SearchOutlined />}
                  onPressEnter={handleSearch}
                  size="small"
                />
              </Form.Item>
              <Button type="default" onClick={handleSearch} size="small">
                搜索
              </Button>
            </div>
          </div>
        </Form>
      </div>
      
      <Table
        columns={columns}
        dataSource={data?.data || []}
        rowKey="id"
        loading={isLoading}
        pagination={{
          current: data?.pagination.current || 1,
          pageSize: data?.pagination.pageSize || 10,
          total: data?.pagination.total || 0,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`
        }}
        onChange={handleTableChange}
        bordered
        size="middle"
      />
    </div>
  );
};

export default Logs;