'use client';

import React, { useState, useEffect, useCallback } from 'react';
import {
  Table, Form, Input, Select, Button, DatePicker, message, Tag, Tooltip, Card, Row, Col, Space
} from 'antd';
import type { TableProps, TablePaginationConfig } from 'antd';
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
import { SearchOutlined, RedoOutlined } from '@ant-design/icons';
import { useAuth } from '@/contexts/AuthContext';
import { fetchMqttLogs, BaseResponse } from '@/services/logService';
import {
  MqttCommunicationLog, MqttLogQueryRequest, PageResponse
} from '@/types/log.types';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;

const MqttCommunicationLogPage: React.FC = () => {
  const { user } = useAuth();
  const [form] = Form.useForm<MqttLogQueryRequest>();
  const [logs, setLogs] = useState<MqttCommunicationLog[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 20,
    total: 0,
    showSizeChanger: true,
    pageSizeOptions: ['10', '20', '50', '100'],
    showTotal: (total) => `共 ${total} 条记录`,
  });

  const fetchData = useCallback(async (params: Partial<MqttLogQueryRequest & { dateRange?: [dayjs.Dayjs, dayjs.Dayjs] | null, antdOrder?: 'ascend' | 'descend' | null }> = {}) => {
    setLoading(true);
    
    const formValues = form.getFieldsValue();

    const currentPage = params.current !== undefined ? params.current : pagination.current;
    const currentPageSize = params.pageSize !== undefined ? params.pageSize : pagination.pageSize;

    const queryParamsBuild: Partial<MqttLogQueryRequest> = {
      ...formValues,
      ...params,
      current: currentPage,
      pageSize: currentPageSize,
    };

    if (params.antdOrder) {
      queryParamsBuild.sortOrder = params.antdOrder;
    } else if (params.hasOwnProperty('antdOrder') && params.antdOrder === null) {
      queryParamsBuild.sortOrder = undefined;
      queryParamsBuild.sortField = undefined;
    } else if (!params.sortField) {
      queryParamsBuild.sortOrder = undefined;
    }
    delete (queryParamsBuild as any).antdOrder;

    const effectiveDateRange = params.dateRange !== undefined ? params.dateRange : formValues.dateRange;
    if (effectiveDateRange && effectiveDateRange[0] && effectiveDateRange[1]) {
      queryParamsBuild.startTime = effectiveDateRange[0].toISOString();
      queryParamsBuild.endTime = effectiveDateRange[1].toISOString();
    } else {
      queryParamsBuild.startTime = undefined;
      queryParamsBuild.endTime = undefined;
    }
    delete (queryParamsBuild as any).dateRange;

    const finalQueryParams = queryParamsBuild as MqttLogQueryRequest;

    try {
      const response: BaseResponse<PageResponse<MqttCommunicationLog>> = await fetchMqttLogs(finalQueryParams);
      if (response.code === 0 && response.data) {
        setLogs(response.data.records || []);
        setPagination(prev => ({
          ...prev,
          current: response.data.current,
          pageSize: response.data.size,
          total: response.data.total,
        }));
      } else {
        message.error(response.message || '获取MQTT日志失败');
        setLogs([]);
        setPagination(prev => ({ ...prev, total: 0, current: 1 }));
      }
    } catch (error) {
      console.error('获取MQTT日志错误:', error);
      message.error('无法连接到服务器或请求失败');
      setLogs([]);
      setPagination(prev => ({ ...prev, total: 0, current: 1 }));
    } finally {
      setLoading(false);
    }
  }, [form, pagination.current, pagination.pageSize]);

  useEffect(() => {
    if (user?.role === 'admin') {
      fetchData();
    }
  }, [fetchData, user?.role]);

  const handleTableChange: TableProps<MqttCommunicationLog>['onChange'] = (
    newPagination: TablePaginationConfig,
    filters: Record<string, FilterValue | null>,
    sorter: SorterResult<MqttCommunicationLog> | SorterResult<MqttCommunicationLog>[],
  ) => {
    const currentSorter = Array.isArray(sorter) ? sorter[0] : sorter;
    const paramsToFetch: Partial<MqttLogQueryRequest & { antdOrder?: 'ascend' | 'descend' | null }> = {
      current: newPagination.current,
      pageSize: newPagination.pageSize,
    };

    if (currentSorter && currentSorter.field) {
      paramsToFetch.sortField = String(currentSorter.field);
      paramsToFetch.antdOrder = currentSorter.order;
    } else {
      paramsToFetch.sortField = undefined;
      paramsToFetch.antdOrder = null;
    }

    setPagination(prev => ({
        ...prev,
        current: newPagination.current,
        pageSize: newPagination.pageSize,
    }));
    
    fetchData(paramsToFetch); 
  };

  const onFinish = (values: MqttLogQueryRequest & { dateRange?: [dayjs.Dayjs, dayjs.Dayjs] | null }) => {
    setPagination(prev => ({ ...prev, current: 1 })); 
    fetchData({
        ...values,
        current: 1,
        sortField: undefined,
        antdOrder: null,
    });
  };

  const handleReset = () => {
    form.resetFields();
    setPagination(prev => ({ ...prev, current: 1, pageSize: 20 }));
    fetchData({
        current: 1, 
        pageSize: 20, 
        sortField: undefined, 
        antdOrder: null,
        clientId: undefined,
        topic: undefined,
        direction: undefined,
        payloadContains: undefined,
        dateRange: undefined,
    });
  };

  if (!user && !loading) {
    return <Card style={{ margin: 20 }}><p className="text-center text-red-500 mt-8">请先登录。</p></Card>;
  }

  if (user?.role !== 'admin' && !loading) {
    return (
      <Card style={{ margin: 20 }} title="MQTT 通信日志">
        <p className="text-center text-red-600 text-lg bg-red-100 border border-red-400 rounded-md p-6 shadow-md">
          抱歉，您没有权限访问此页面。此功能仅对管理员开放。
        </p>
      </Card>
    );
  }

  const columns: TableProps<MqttCommunicationLog>['columns'] = [
    { title: 'ID', dataIndex: 'id', key: 'id', width: 80, sorter: true },
    {
      title: '时间戳',
      dataIndex: 'logTimestamp',
      key: 'logTimestamp',
      sorter: true,
      width: 180,
      render: (text: string) => dayjs(text).format('YYYY-MM-DD HH:mm:ss.SSS'),
    },
    {
      title: '方向',
      dataIndex: 'direction',
      key: 'direction',
      width: 100,
      render: (direction: 'UPSTREAM' | 'DOWNSTREAM') => (
        <Tag color={direction === 'UPSTREAM' ? 'blue' : 'green'}>
          {direction === 'UPSTREAM' ? '上行' : '下行'}
        </Tag>
      ),
    },
    { title: '客户端ID', dataIndex: 'clientId', key: 'clientId', width: 150, sorter: true, ellipsis: true },
    { title: '主题', dataIndex: 'topic', key: 'topic', width: 250, sorter: true, ellipsis: true },    
    {
      title: 'Payload',
      dataIndex: 'payload',
      key: 'payload',
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={text} placement="topLeft">
          <pre style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-all', maxHeight: '60px', overflowY: 'auto', margin: 0, fontSize: '12px' }}>
            {text}
          </pre>
        </Tooltip>
      ),
    },
    {
      title: '格式',
      dataIndex: 'payloadFormat',
      key: 'payloadFormat',
      width: 80,
      render: (format?: 'TEXT' | 'JSON' | 'BINARY') => format || 'N/A',
    },
    { title: 'QoS', dataIndex: 'qos', key: 'qos', width: 60, sorter: true },
    {
      title: 'Retained',
      dataIndex: 'isRetained',
      key: 'isRetained',
      width: 90,
      render: (isRetained?: boolean) => (isRetained ? <Tag color="gold">是</Tag> : '否'),
    },
    { title: '关联会话ID', dataIndex: 'relatedSessionId', key: 'relatedSessionId', width: 120, sorter: true },
    { title: '关联任务ID', dataIndex: 'relatedTaskId', key: 'relatedTaskId', width: 120, sorter: true },
  ];

  return (
    <div style={{ margin: '20px' }}>
      <Card title="MQTT 通信日志查询" style={{ marginBottom: '20px' }}>
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
        >
          <Row gutter={16}>
            <Col xs={24} sm={12} md={8} lg={6}>
              <Form.Item name="clientId" label="客户端ID">
                <Input placeholder="请输入客户端ID" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={8} lg={6}>
              <Form.Item name="topic" label="主题">
                <Input placeholder="请输入主题" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={8} lg={6}>
              <Form.Item name="direction" label="方向">
                <Select placeholder="请选择消息方向" allowClear>
                  <Option value="UPSTREAM">上行</Option>
                  <Option value="DOWNSTREAM">下行</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={8} lg={6}>
               <Form.Item name="payloadContains" label="Payload包含">
                <Input placeholder="请输入Payload包含的内容" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={8} lg={6}>
              <Form.Item name="dateRange" label="时间范围">
                <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: '100%' }} />
              </Form.Item>
            </Col>
             <Col xs={24} sm={12} md={8} lg={6}>
              <Form.Item name="relatedSessionId" label="关联会话ID">
                <Input type="number" placeholder="请输入会话ID" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={8} lg={6}>
              <Form.Item name="relatedTaskId" label="关联任务ID">
                <Input type="number" placeholder="请输入任务ID" />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24} style={{ textAlign: 'right' }}>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                  查询
                </Button>
                <Button onClick={handleReset} icon={<RedoOutlined />}>
                  重置
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card title="日志列表">
        <Table
          columns={columns}
          rowKey="id"
          dataSource={logs}
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: 1500 }}
          bordered
        />
      </Card>
    </div>
  );
};

export default MqttCommunicationLogPage; 