import React, { useState, useEffect } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { Button, Table, Modal, message, Input, Form, Tooltip, Tag, Space, TablePaginationConfig } from 'antd';
import {
  DeleteOutlined,
  ExclamationCircleOutlined,
  SearchOutlined
} from '@ant-design/icons';
import styles from './userQuestionManage.less';
// 引入封装的组件
import QuestionModal from './QuestionModal';
// 引入API
import {
  getQuestionPage,
  getQuestionDetail,
  markQuestionSeen,
  markQuestionSeeEdit,
  deleteQuestion,
  batchDeleteQuestion
} from '@/servers/api/userQuestion';
// 引入字典
import { QuestionCategoryOptions } from '@/dicts/userQuestionDict';

const { confirm } = Modal;

// 用户提问类型定义，扩展API.QuestionRecord类型，添加key属性
type QuestionItemType = API.QuestionRecord & {
  key: string;
};

// 搜索参数类型
interface SearchParams {
  title?: string;
  type?: string;
  isAnswer?: number;
}

const UnreadQuestionManage: React.FC = () => {
  const intl = useIntl();
  const [loading, setLoading] = useState<boolean>(false);
  const [questionData, setQuestionData] = useState<QuestionItemType[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [form] = Form.useForm();
  const [answerModalVisible, setAnswerModalVisible] = useState<boolean>(false);
  const [currentQuestion, setCurrentQuestion] = useState<QuestionItemType | null>(null);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条记录`,
  });
  const [searchParams, setSearchParams] = useState<SearchParams>({
    isAnswer: 0 // 默认未回答
  });

  // 获取未回答的用户提问列表数据
  const fetchQuestionList = async (
    current: number = 1,
    pageSize: number = 10,
    params: SearchParams = searchParams,
  ) => {
    // 更新搜索参数状态
    if (params !== searchParams) {
      setSearchParams(params);
    }

    setLoading(true);
    try {
      // 构造请求参数
      const requestParams: API.PageRequest = {
        basePageRequest: {
          pageNo: current,
          pageSize: pageSize,
        },
        ...params,
        isAnswer: 0, // 确保始终查询未回答的问题
      };

      const response = await getQuestionPage(requestParams);
      if (response && response.success) {
        const { records, total, current: currentPage, size } = response.data;

        // 添加key属性用于表格
        const formattedData = records.map((item: API.QuestionRecord) => ({
          ...item,
          key: item.id,
        }));

        setQuestionData(formattedData);
          setPagination({
            ...pagination,
          current: currentPage,
          pageSize: size,
          total,
        });
      } else {
        message.error(response.message || intl.formatMessage({ id: 'unreadQuestion.fetchFailed' }));
      }
    } catch (error) {
      console.error('获取问题列表失败:', error);
      message.error(intl.formatMessage({ id: 'unreadQuestion.fetchFailed' }));
    } finally {
        setLoading(false);
    }
  };

  // 首次加载时获取数据
  useEffect(() => {
    fetchQuestionList(pagination.current, pagination.pageSize);
  }, []);

  // 处理搜索
  const handleSearch = (values: SearchParams) => {
    const params = { ...values, isAnswer: 0 };
    fetchQuestionList(1, pagination.pageSize, params);
  };

  // 处理回答问题
  const handleAnswer = async (record: QuestionItemType) => {
    try {
      // 先标记为已阅
      const response = await markQuestionSeeEdit(record.id);
      if (!response || !response.success) {
        message.error(response?.message || intl.formatMessage({ id: 'userQuestion.replyFailed' }));
      return;
    }

      // 获取问题详情
      const detailResponse = await getQuestionDetail(record.id);
      if (detailResponse && detailResponse.success) {
        const detailData = detailResponse.data;
        const formattedDetail = {
          ...detailData,
          key: detailData.id
        };

        setCurrentQuestion(formattedDetail);
        setAnswerModalVisible(true);
      } else {
        message.error(detailResponse.message || intl.formatMessage({ id: 'userQuestion.replyFailed' }));
      }
    } catch (error) {
      console.error('处理问题失败:', error);
      message.error(intl.formatMessage({ id: 'userQuestion.replyFailed' }));
    }
  };

  // 处理删除
  const showDeleteConfirm = (record: QuestionItemType) => {
    confirm({
      title: intl.formatMessage({ id: 'unreadQuestion.confirmDelete' }),
      icon: <ExclamationCircleOutlined />,
      content: `${intl.formatMessage({ id: 'unreadQuestion.confirmDelete' })} "${record.title}"?`,
      okText: intl.formatMessage({ id: 'readQuestion.delete' }),
      okType: 'danger',
      cancelText: intl.formatMessage({ id: 'readQuestion.cancel' }),
      maskClosable: false,
      onOk: async () => {
        try {
          const response = await deleteQuestion(record.id);
          if (response && response.success) {
            message.success(intl.formatMessage({ id: 'userQuestion.deleteSuccess' }));
            fetchQuestionList(pagination.current, pagination.pageSize, searchParams); // 重新加载数据
          } else {
            message.error(response.message || intl.formatMessage({ id: 'userQuestion.deleteFailed' }));
          }
        } catch (error) {
          console.error('删除问题失败:', error);
          message.error(intl.formatMessage({ id: 'userQuestion.deleteFailed' }));
        }
      },
    });
  };

  // 处理表格分页变化
  const handleTableChange = (newPagination: TablePaginationConfig) => {
    fetchQuestionList(newPagination.current, newPagination.pageSize, searchParams);
  };

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning(intl.formatMessage({ id: 'userQuestion.selectRequired' }));
      return;
    }

    confirm({
      title: intl.formatMessage({ id: 'unreadQuestion.batchDelete' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'userQuestion.batchDeleteConfirm' }),
      okText: intl.formatMessage({ id: 'readQuestion.delete' }),
      okType: 'danger',
      cancelText: intl.formatMessage({ id: 'readQuestion.cancel' }),
      maskClosable: false,
      onOk: async () => {
        try {
          const response = await batchDeleteQuestion(selectedRowKeys as string[]);
          if (response && response.success) {
            setSelectedRowKeys([]);
            message.success(intl.formatMessage({ id: 'unreadQuestion.batchDeleteSuccess' }));
            fetchQuestionList(pagination.current, pagination.pageSize, searchParams);
          } else {
            message.error(response.message || intl.formatMessage({ id: 'unreadQuestion.batchDeleteFailed' }));
          }
        } catch (error) {
          console.error('批量删除失败:', error);
          message.error(intl.formatMessage({ id: 'unreadQuestion.batchDeleteFailed' }));
        }
      },
    });
  };

  // 行选择限制
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const hasSelected = selectedRowKeys.length > 0;

  // 获取分类选项，处理为下拉框选项
  const getCategoryOptions = () => {
    return QuestionCategoryOptions.map(option => (
      <option key={option.value} value={option.value}>
        {typeof option.label === 'function' ? option.label() : option.label}
      </option>
    ));
  };

  // 表格列定义
  const columns = [
    {
      title: intl.formatMessage({ id: 'unreadQuestion.serialNumber' }),
      render: (_: any, __: any, index: number) => index + 1,
      width: 80,
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'unreadQuestion.questionTitle' }),
      dataIndex: 'title',
      key: 'title',
      ellipsis: {
        showTitle: false,
      },
      render: (title: string) => (
        <Tooltip placement="topLeft" title={title}>
          {title}
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'unreadQuestion.category' }),
      dataIndex: 'type',
      key: 'type',
      width: 120,
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'unreadQuestion.asker' }),
      dataIndex: 'userName',
      key: 'userName',
      width: 100,
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'unreadQuestion.company' }),
      dataIndex: 'companyName',
      key: 'companyName',
      width: 150,
      ellipsis: {
        showTitle: false,
      },
      render: (companyName: string) => (
        <Tooltip placement="topLeft" title={companyName}>
          {companyName}
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'unreadQuestion.account' }),
      dataIndex: 'fullName',
      key: 'fullName',
      width: 120,
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'unreadQuestion.contact' }),
      dataIndex: 'contactDetails',
      key: 'contactDetails',
      width: 120,
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'unreadQuestion.email' }),
      dataIndex: 'email',
      key: 'email',
      width: 150,
      ellipsis: {
        showTitle: false,
      },
      render: (email: string) => (
        <Tooltip placement="topLeft" title={email}>
          {email}
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'unreadQuestion.askTime' }),
      dataIndex: 'askTime',
      key: 'askTime',
      width: 150,
      align: 'center' as const,
    },

    {
      title: intl.formatMessage({ id: 'unreadQuestion.operation' }),
      key: 'action',
      width: 150,
      align: 'center' as const,
      render: (_: unknown, record: QuestionItemType) => (
        <Space>
          <Button type="link" onClick={() => handleAnswer(record)}>
            {intl.formatMessage({ id: 'unreadQuestion.reply' })}
            </Button>
          <Button type="link" onClick={() => showDeleteConfirm(record)}>
            {intl.formatMessage({ id: 'unreadQuestion.delete' })}
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="common-container">
      <div className="filter-action-row">
        <Form
          form={form}
          name="search"
          onFinish={handleSearch}
          layout="inline"
          className="filter-form"
        >
          <Form.Item name="title" label={intl.formatMessage({ id: 'unreadQuestion.questionTitle' })}>
            <Input placeholder={intl.formatMessage({ id: 'unreadQuestion.questionPlaceholder' })} allowClear />
          </Form.Item>
          <Form.Item name="type" label={intl.formatMessage({ id: 'unreadQuestion.category' })}>
            <select className="ant-select" style={{ width: 150, height: 32, borderRadius: 2 }}>
              <option value="">{intl.formatMessage({ id: 'unreadQuestion.selectCategory' })}</option>
              {getCategoryOptions()}
            </select>
          </Form.Item>
          <Form.Item className="filter-btns">
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              {intl.formatMessage({ id: 'unreadQuestion.search' })}
            </Button>
            <Button
              type="primary"
              danger
              onClick={() => {
                form.resetFields();
                setSearchParams({ isAnswer: 0 });
                fetchQuestionList(1, pagination.pageSize, { isAnswer: 0 });
              }}
            >
              {intl.formatMessage({ id: 'unreadQuestion.reset' })}
            </Button>
          </Form.Item>
        </Form>

        <div className="right-buttons">
          <Button
            danger
            onClick={handleBatchDelete}
            disabled={!hasSelected}
            loading={loading}
          >
            {intl.formatMessage({ id: 'unreadQuestion.batchDelete' })}
          </Button>
          {hasSelected && (
            <span className="selected-count">
              {intl.formatMessage({ id: 'unreadQuestion.selectedCount' }, { count: selectedRowKeys.length })}
            </span>
          )}
        </div>
      </div>

      <div className="content-area">
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={questionData}
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          rowKey="id"
          scroll={{ x: 1500 }}
        />
      </div>

      {/* 使用封装的问题模态框组件 */}
      <QuestionModal
        visible={answerModalVisible}
        onCancel={() => setAnswerModalVisible(false)}
        question={currentQuestion}
        mode="answer"
        onSuccess={() => fetchQuestionList(pagination.current, pagination.pageSize, searchParams)}
      />
    </div>
  );
};

export default UnreadQuestionManage;
