import React, { useState } from 'react';
import { Table, Button, Space, Input, Form, DatePicker, Select, Collapse, Row, Col } from 'antd';
import { SearchOutlined, FilterOutlined, DownOutlined, RightOutlined } from '@ant-design/icons';
import { useQuery } from '@tanstack/react-query';
import { operationLogsClient } from '@/client/api';
import UserSelect from '@/client/admin/components/UserSelect';
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.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,
          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="mb-6 flex justify-between items-center">
        <h2 className="text-2xl font-bold">系统日志管理</h2>
      </div>
      
      <div className="bg-white p-3 mb-4 rounded-lg shadow-sm transition-all duration-300 hover:shadow-md">
        <Form
          form={form}
          onValuesChange={handleFilterChange}
          initialValues={{
            pagination: {
              current: 1,
              pageSize: 10
            }
          }}
          layout="inline"
        >
          {/* 紧凑搜索区域 */}
          <div className="w-full">
            <Row gutter={12} align="middle" wrap={false}>
              <Col flex="auto">
                <Row gutter={12} wrap>
                  <Col>
                    <Form.Item name="resourceType" label="资源类型" style={{ marginBottom: 0 }}>
                      <Select
                        placeholder="全部类型"
                        allowClear
                        className="w-28"
                        size="small"
                        popupMatchSelectWidth={false}
                      >
                        <Select.Option value="user">用户</Select.Option>
                        <Select.Option value="client">客户</Select.Option>
                        <Select.Option value="contract">合同</Select.Option>
                        <Select.Option value="permission">权限</Select.Option>
                        <Select.Option value="role">角色</Select.Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col>
                    <Form.Item name="action" label="操作" style={{ marginBottom: 0 }}>
                      <Select
                        placeholder="全部操作"
                        allowClear
                        className="w-28"
                        size="small"
                        popupMatchSelectWidth={false}
                      >
                        <Select.Option value="create">创建</Select.Option>
                        <Select.Option value="update">更新</Select.Option>
                        <Select.Option value="delete">删除</Select.Option>
                        <Select.Option value="view">查看</Select.Option>
                        <Select.Option value="login">登录</Select.Option>
                        <Select.Option value="logout">登出</Select.Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col>
                    <Form.Item name="status" label="状态" style={{ marginBottom: 0 }}>
                      <Select placeholder="全部状态" allowClear className="w-24" size="small">
                        <Select.Option value="success">成功</Select.Option>
                        <Select.Option value="failed">失败</Select.Option>
                        <Select.Option value="permission_denied">拒绝</Select.Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col>
                    <Form.Item name="method" label="方法" style={{ marginBottom: 0 }}>
                      <Select placeholder="全部" allowClear className="w-20" size="small">
                        <Select.Option value="GET">GET</Select.Option>
                        <Select.Option value="POST">POST</Select.Option>
                        <Select.Option value="PUT">PUT</Select.Option>
                        <Select.Option value="DELETE">DELETE</Select.Option>
                        <Select.Option value="PATCH">PATCH</Select.Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col>
                    <Form.Item name="searchText" style={{ marginBottom: 0 }}>
                      <Input
                        placeholder="关键词：日志内容、ID等"
                        prefix={<SearchOutlined />}
                        onPressEnter={handleSearch}
                        allowClear
                        className="w-48"
                        size="small"
                      />
                    </Form.Item>
                  </Col>
                </Row>
              </Col>
              <Col>
                <Space size={8}>
                  <Button
                    type="primary"
                    icon={<FilterOutlined />}
                    onClick={handleFilterChange}
                    size="small"
                  >
                    查询
                  </Button>
                  <Button
                    onClick={handleResetFilters}
                    size="small"
                  >
                    重置
                  </Button>
                  <Button
                    type="link"
                    size="small"
                    icon={advancedSearchExpanded ? <DownOutlined /> : <RightOutlined />}
                    onClick={() => setAdvancedSearchExpanded(!advancedSearchExpanded)}
                  >
                    {advancedSearchExpanded ? '收起' : '高级'}
                  </Button>
                </Space>
              </Col>
            </Row>

            {/* 高级搜索条件 - 直接展开显示 */}
            {advancedSearchExpanded && (
              <div className="mt-2 pt-2 border-t border-gray-100">
                <Row gutter={12} wrap>
                  <Col>
                    <Form.Item name="dateRange" label="操作时间" style={{ marginBottom: 0 }}>
                      <RangePicker
                        format="YYYY-MM-DD"
                        className="w-56"
                        allowClear
                        size="small"
                        placeholder={['开始日期', '结束日期']}
                      />
                    </Form.Item>
                  </Col>
                  <Col>
                    <Form.Item name="userId" label="操作用户" style={{ marginBottom: 0 }}>
                      <UserSelect
                        placeholder="选择用户"
                        className="w-36"
                        style={{ fontSize: 12 }}
                      />
                    </Form.Item>
                  </Col>
                  <Col>
                    <Form.Item name="ipAddress" label="IP地址" style={{ marginBottom: 0 }}>
                      <Input
                        placeholder="IP地址"
                        allowClear
                        className="w-28"
                        size="small"
                      />
                    </Form.Item>
                  </Col>
                  <Col>
                    <Form.Item name="endpoint" label="API端点" style={{ marginBottom: 0 }}>
                      <Input
                        placeholder="API端点"
                        allowClear
                        className="w-36"
                        size="small"
                      />
                    </Form.Item>
                  </Col>
                </Row>
              </div>
            )}
          </div>
        </Form>
      </div>
      
      <div className="bg-white p-6 mb-6 rounded-lg shadow-sm transition-all duration-300 hover:shadow-md">
        <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"
          scroll={{ x: 'max-content' }}
          rowClassName={(record, index) => index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}
        />
      </div>
    </div>
  );
};

export default Logs;