import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Search, RotateCcw, BookOpen, ChevronLeft, ChevronRight } from 'lucide-react';
import { Checkbox } from './ui/checkbox';
import { Button as AntButton, Modal, Form, Input, Select, DatePicker, Tooltip, Descriptions, Table as AntdTable, Space } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { Button } from './ui/button';
import { toast } from 'sonner';
import dayjs, { Dayjs } from 'dayjs';
import { app_message, type NotifyMessageVO } from '../api/notification/app_message';
import { dateFormatter } from '../utils/formatTime';
import { DICT_TYPE, getDictLabel, getDictObj } from '../utils/dict';

interface MessageItem {
  id: number;
  title: string;
  type: string;
  sender: string;
  sendTime: string;
  createTime?: string | number;
  content: string;
  status: 'read' | 'unread';
  readTime?: string | number;
  userId?: number;
  userType?: number;
  templateId?: number;
  templateCode?: string;
  templateParams?: any;
  templateType?: number;
}

export default function AppMessage() {
  const { t } = useTranslation();
  const [messageTitle, setMessageTitle] = useState<string>('');
  const [messageStatus, setMessageStatus] = useState<string | undefined>(undefined);
  const [startDate, setStartDate] = useState<Dayjs | null>(null);
  const [endDate, setEndDate] = useState<Dayjs | null>(null);
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const [messages, setMessages] = useState<MessageItem[]>([]);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const [detailModalVisible, setDetailModalVisible] = useState<boolean>(false);
  const [detailMessage, setDetailMessage] = useState<MessageItem | null>(null);
  const [detailLoading, setDetailLoading] = useState<boolean>(false);
  const pageSize = 10;
  const totalPages = Math.ceil(total / pageSize);
  const isSearchingRef = React.useRef(false);

  // 将API数据转换为组件使用的格式
  const convertMessageData = (data: NotifyMessageVO): MessageItem => {
    // 根据 templateType 获取字典标签
    const typeLabel = data.templateType 
      ? getDictLabel(DICT_TYPE.SYSTEM_NOTIFY_TEMPLATE_TYPE, data.templateType) 
      : t('notificationManagement.appNotify');
    
    return {
      id: data.id,
      title: data.title || '',
      type: typeLabel,
      sender: data.templateNickname || t('notificationManagement.system'),
      sendTime: data.createTime || '',
      createTime: data.createTime,
      content: data.templateContent || '',
      status: data.readStatus === true ? 'read' : 'unread',
      readTime: data.readTime,
      userId: data.userId,
      userType: data.userType,
      templateId: data.templateId,
      templateCode: data.templateCode,
      templateParams: data.templateParams,
      templateType: data.templateType
    };
  };

  // 获取消息列表
  const fetchMessages = async (searchParams?: {
    title?: string;
    status?: string;
    startDate?: Dayjs | null;
    endDate?: Dayjs | null;
    page?: number;
  }) => {
    setLoading(true);
    try {
      // 使用传入的参数或当前状态
      // 如果 searchParams 存在，优先使用 searchParams 的值（即使值是 undefined，也表示要清空）
      const title = searchParams !== undefined && 'title' in searchParams ? searchParams.title : messageTitle;
      const status = searchParams !== undefined && 'status' in searchParams ? searchParams.status : messageStatus;
      const start = searchParams !== undefined && 'startDate' in searchParams ? searchParams.startDate : startDate;
      const end = searchParams !== undefined && 'endDate' in searchParams ? searchParams.endDate : endDate;
      const page = searchParams !== undefined && 'page' in searchParams ? searchParams.page : currentPage;

      const params: any = {
        pageNo: page,
        pageSize: pageSize,
        type: 1 // App消息类型为1
      };

      // 添加筛选条件（只有当值存在时才添加）
      if (title && title.trim()) {
        params.title = title.trim();
      }
      // 只有当 status 有明确值（不是 undefined）时才添加 readStatus 参数
      if (status !== undefined && status !== null && status !== '') {
        // 将字符串转换为 boolean：'true' 表示已读(true)，'false' 表示未读(false)
        params.readStatus = status === 'true' ? true : status === 'false' ? false : undefined;
      }
      if (start) {
        // createTime[0] 格式：YYYY-MM-DD 00:00:00
        params['createTime[0]'] = start.format('YYYY-MM-DD 00:00:00');
      }
      if (end) {
        // createTime[1] 格式：YYYY-MM-DD 23:59:59
        params['createTime[1]'] = end.format('YYYY-MM-DD 23:59:59');
      }

      const response = await app_message.getMyPage(params);
      const messageList = (response.list || []).map(convertMessageData);
      setMessages(messageList);
      setTotal(response.total || 0);
    } catch (error: any) {
      console.error('获取App通知列表失败:', error);
      toast.error(error?.response?.data?.message || t('notificationManagement.getAppListFailed'));
      setMessages([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  // 初始加载和分页变化时重新获取数据
  useEffect(() => {
    // 如果是搜索触发的，不在这里处理
    if (isSearchingRef.current) {
      isSearchingRef.current = false;
      return;
    }
    fetchMessages();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage]);

  // 全选/取消全选
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedIds(messages.map(msg => msg.id));
    } else {
      setSelectedIds([]);
    }
  };

  // 单个选择
  const handleSelectItem = (id: number, checked: boolean) => {
    if (checked) {
      setSelectedIds([...selectedIds, id]);
    } else {
      setSelectedIds(selectedIds.filter(selectedId => selectedId !== id));
    }
  };

  // 搜索
  const handleSearch = () => {
    // 标记为搜索触发，避免 useEffect 重复调用
    isSearchingRef.current = true;
    const targetPage = 1;
    // 先更新页码
    setCurrentPage(targetPage);
    // 直接使用当前搜索条件进行搜索
    fetchMessages({
      title: messageTitle,
      status: messageStatus,
      startDate: startDate,
      endDate: endDate,
      page: targetPage
    });
  };

  // 重置
  const handleReset = () => {
    // 标记为搜索触发，避免 useEffect 重复调用
    isSearchingRef.current = true;
    
    // 先立即清空表格数据，确保界面立即更新
    setMessages([]);
    setTotal(0);
    
    // 同步清空所有搜索条件和状态
    setMessageTitle('');
    setMessageStatus(undefined);
    setStartDate(null);
    setEndDate(null);
    setSelectedIds([]);
    setCurrentPage(1);
    
    // 重置后重新获取数据（使用空条件，确保传入所有参数）
    // 直接调用 fetchMessages，传入重置后的参数，不依赖状态
    fetchMessages({
      title: '',
      status: undefined,
      startDate: null,
      endDate: null,
      page: 1
    });
  };

  // 查看详情（点击阅读时若未读先调用 update-read 再展示详情）
  const handleViewDetail = async (id: number) => {
    const currentMessage = messages.find(msg => msg.id === id);
    const isUnread = currentMessage?.status === 'unread';

    if (isUnread) {
      try {
        await app_message.updateRead([id]);
        await fetchMessages();
        window.dispatchEvent(new CustomEvent('messageRead'));
      } catch (error: any) {
        console.error('标记已读失败:', error);
        toast.error(error?.response?.data?.message || t('notificationManagement.markReadFailed'));
        return;
      }
    }

    setDetailLoading(true);
    try {
      if (currentMessage) {
        setDetailMessage(isUnread ? { ...currentMessage, status: 'read' as const } : currentMessage);
        setDetailModalVisible(true);
      } else {
        toast.error(t('notificationManagement.messageDetailNotFound'));
      }
    } catch (error: any) {
      console.error('获取消息详情失败:', error);
      toast.error(error?.response?.data?.message || t('notificationManagement.getMessageDetailFailed'));
    } finally {
      setDetailLoading(false);
    }
  };

  // 全部已读
  const handleMarkAllAsRead = async () => {
    setLoading(true);
    try {
      await app_message.updateAllRead();
      setSelectedIds([]);
      await fetchMessages();
      toast.success(t('notificationManagement.markAllReadSuccess'));
      window.dispatchEvent(new CustomEvent('messageRead'));
    } catch (error: any) {
      console.error('全部标记已读失败:', error);
      toast.error(error?.response?.data?.message || t('notificationManagement.markAllReadFailed'));
    } finally {
      setLoading(false);
    }
  };

  // 使用从API获取的消息列表（已根据筛选条件过滤）
  const filteredMessages = messages;

  const isAllSelected = filteredMessages.length > 0 && selectedIds.length === filteredMessages.length;

  // 定义表格列
  const columns: ColumnsType<MessageItem> = [
    {
      title: t('notificationManagement.messageTitle'),
      dataIndex: 'title',
      key: 'title',
      width: '15%',
      render: (text: string) => <span className="text-sm text-gray-900">{text}</span>,
    },
    {
      title: t('notificationManagement.messageType'),
      dataIndex: 'type',
      key: 'type',
      width: '10%',
      render: (type: string, record: MessageItem) => {
        const dictObj = record.templateType 
          ? getDictObj(DICT_TYPE.SYSTEM_NOTIFY_TEMPLATE_TYPE, record.templateType)
          : null;
        
        let bgColor = 'bg-gray-100';
        let textColor = 'text-gray-700';
        
        if (dictObj) {
          switch (dictObj.colorType) {
            case 'blue':
              bgColor = 'bg-blue-100';
              textColor = 'text-blue-700';
              break;
            case 'green':
              bgColor = 'bg-green-100';
              textColor = 'text-green-700';
              break;
            case 'orange':
              bgColor = 'bg-orange-100';
              textColor = 'text-orange-700';
              break;
            default:
              bgColor = 'bg-gray-100';
              textColor = 'text-gray-700';
          }
        }
        
        return (
          <span className={`inline-flex px-3 py-1 rounded-lg text-xs ${bgColor} ${textColor}`}>
            {type}
          </span>
        );
      },
    },
    {
      title: t('notificationManagement.sender'),
      dataIndex: 'sender',
      key: 'sender',
      width: '10%',
      render: (text: string) => <span className="text-sm text-gray-900">{text}</span>,
    },
    {
      title: t('table.createTime'),
      dataIndex: 'createTime',
      key: 'createTime',
      width: '12%',
      render: (createTime: string | number | undefined, record: MessageItem) => {
        const time = createTime || record.sendTime;
        return <span className="text-sm text-gray-900">{time ? dateFormatter(time) : '-'}</span>;
      },
    },
    {
      title: t('notificationManagement.messageContent'),
      dataIndex: 'content',
      key: 'content',
      width: '20%',
      render: (content: string) => {
        const contentText = content || '-';
        const maxLength = 20;
        const shouldTruncate = contentText.length > maxLength;
        const displayText = shouldTruncate ? contentText.slice(0, maxLength) + '...' : contentText;
        
        return (
          <Tooltip placement="topLeft" title={contentText}>
            <span className="text-sm text-gray-900">{displayText}</span>
          </Tooltip>
        );
      },
    },
    {
      title: t('notificationManagement.messageStatus'),
      dataIndex: 'status',
      key: 'status',
      width: '8%',
      render: (status: 'read' | 'unread') => {
        return status === 'read' ? (
          <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-gray-100 text-gray-700">
            {t('notificationManagement.read')}
          </span>
        ) : (
          <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-red-100 text-red-700">
            {t('notificationManagement.unread')}
          </span>
        );
      },
    },
    {
      title: t('notificationManagement.readTime'),
      dataIndex: 'readTime',
      key: 'readTime',
      width: '12%',
      render: (readTime: string | number | undefined) => {
        return <span className="text-sm text-gray-900">{readTime ? dateFormatter(readTime) : '-'}</span>;
      },
    },
    {
      title: t('common.operation'),
      key: 'action',
      width: '8%',
      align: 'center',
      render: (_: any, record: MessageItem) => {
        return (
          <Button 
            variant="ghost"
            size="sm"
            onClick={() => handleViewDetail(record.id)}
            className="h-8 px-2 transition-colors"
            style={{ color: record.status === 'unread' ? '#f56565' : '#1677ff' }}
            onMouseEnter={(e) => {
              if (record.status === 'unread') {
                e.currentTarget.style.color = '#f56565';
                e.currentTarget.style.textDecoration = 'underline';
                e.currentTarget.style.textDecorationColor = '#f56565';
              } else {
                e.currentTarget.style.color = '#1677ff';
                e.currentTarget.style.textDecoration = 'underline';
              }
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.color = record.status === 'unread' ? '#f56565' : '#1677ff';
              e.currentTarget.style.textDecoration = 'none';
            }}
          >
            <span>{record.status === 'unread' ? t('notificationManagement.readLabel') : t('notificationManagement.detailLabel')}</span>
          </Button>
        );
      },
    },
  ];

  return (
    <div className="space-y-6">
      {/* 操作栏和表格容器 */}
      <div className="bg-white rounded-2xl border border-gray-200/50 shadow-sm overflow-hidden">
        {/* 查询与操作栏 */}
        <div className="p-4 lg:p-5 border-b border-gray-200/50">
          <div className="flex flex-wrap items-center gap-3">
            {/* 搜索条件 + 搜索、重置紧跟其后 */}
            <div className="flex flex-wrap items-center gap-3">
              {/* 消息标题 */}
              <div className="flex items-center gap-2">
                <label className="text-sm text-gray-700 whitespace-nowrap">{t('notificationManagement.messageTitle')}：</label>
                <Input
                  placeholder={t('notificationManagement.placeholderMessageTitle')}
                  value={messageTitle}
                  onChange={(e) => setMessageTitle(e.target.value)}
                  onPressEnter={handleSearch}
                  allowClear
                  style={{ width: 200 }}
                />
              </div>

              {/* 消息状态 */}
              <div className="flex items-center gap-2">
                <label className="text-sm text-gray-700 whitespace-nowrap">{t('notificationManagement.messageStatus')}：</label>
                <Select
                  value={messageStatus}
                  onChange={setMessageStatus}
                  placeholder={t('common.pleaseSelect')}
                  style={{ width: 120 }}
                  allowClear
                >
                  <Select.Option value="true">{t('notificationManagement.read')}</Select.Option>
                  <Select.Option value="false">{t('notificationManagement.unread')}</Select.Option>
                </Select>
              </div>

              {/* 发送日期 + 搜索/重置（放在同一组，按钮紧跟最后一个条件后面） */}
              <div className="flex items-center gap-2">
                <label className="text-sm text-gray-700 whitespace-nowrap">{t('notificationManagement.time')}：</label>
                <DatePicker
                  placeholder={t('common.startDate')}
                  value={startDate}
                  onChange={setStartDate}
                  format="YYYY-MM-DD"
                  style={{ width: 140 }}
                />
                <span className="text-gray-400">-</span>
                <DatePicker
                  placeholder={t('common.endDate')}
                  value={endDate}
                  onChange={setEndDate}
                  format="YYYY-MM-DD"
                  style={{ width: 140 }}
                />
                <Space size="small">
                  <AntButton
                    type="primary"
                    icon={<Search className="w-4 h-4" />}
                    onClick={handleSearch}
                    disabled={loading}
                  >
                    {t('common.search')}
                  </AntButton>
                  <AntButton
                    icon={<RotateCcw className="w-4 h-4" />}
                    onClick={handleReset}
                  >
                    {t('common.reset')}
                  </AntButton>
                </Space>
              </div>
            </div>

            {/* 其他操作按钮保持在最右侧（全部已读） */}
            <Space size="small" className="ml-auto">
              <AntButton
                icon={<BookOpen className="w-4 h-4" />}
                onClick={handleMarkAllAsRead}
                disabled={loading}
              >
                {t('notificationManagement.markAllRead')}
              </AntButton>
            </Space>
          </div>
        </div>

        {/* 表格容器 */}
        <div className="overflow-hidden min-w-0">
          <AntdTable
            loading={loading}
            columns={columns}
            dataSource={filteredMessages}
            rowKey={(record) => record.id}
            pagination={false}
            scroll={{ x: 'max-content' }}
            locale={{
              emptyText: t('common.noData'),
            }}
          />
        </div>
      </div>

      {/* 分页 */}
      {total > 0 && (
        <div className="bg-white rounded-lg border border-gray-200 px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="text-sm text-gray-600">
              {t('common.total')} <span className="text-blue-600 font-medium">{total}</span> {t('common.records')}
            </div>
            <div className="flex gap-2">
              <AntButton
                onClick={() => {
                  const newPage = Math.max(1, currentPage - 1);
                  setCurrentPage(newPage);
                }}
                disabled={currentPage === 1 || loading}
              >
                {t('common.prevPage')}
              </AntButton>
              <span className="px-4 py-2 text-sm text-gray-600 flex items-center">
                {currentPage} / {totalPages || 1}
              </span>
              <AntButton
                onClick={() => {
                  const newPage = Math.min(totalPages, currentPage + 1);
                  setCurrentPage(newPage);
                }}
                disabled={currentPage >= totalPages || loading || totalPages === 0}
              >
                {t('common.nextPage')}
              </AntButton>
            </div>
          </div>
        </div>
      )}

      {/* 消息详情弹窗 */}
      <Modal
        title={t('notificationManagement.inboxDetail')}
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setDetailMessage(null);
        }}
        footer={null}
        width={800}
        confirmLoading={detailLoading}
      >
        {detailLoading ? (
          <div className="py-8 text-center text-gray-500">{t('common.loading')}</div>
        ) : detailMessage ? (
          <Descriptions 
            column={1} 
            bordered
            labelStyle={{ whiteSpace: 'nowrap', width: '120px' }}
          >
            <Descriptions.Item label={t('notificationManagement.sender')}>
              {detailMessage.sender || t('notificationManagement.system')}
            </Descriptions.Item>
            <Descriptions.Item label={t('table.createTime')}>
              {detailMessage.createTime ? dateFormatter(detailMessage.createTime) : (detailMessage.sendTime ? dateFormatter(detailMessage.sendTime) : '-')}
            </Descriptions.Item>
            <Descriptions.Item label={t('notificationManagement.messageType')}>
              {(() => {
                // 根据 templateType 获取字典对象，包含颜色信息
                const dictObj = detailMessage.templateType 
                  ? getDictObj(DICT_TYPE.SYSTEM_NOTIFY_TEMPLATE_TYPE, detailMessage.templateType)
                  : null;
                
                // 根据字典的 colorType 设置不同的颜色
                let bgColor = 'bg-gray-100';
                let textColor = 'text-gray-700';
                let borderColor = 'border-gray-200';
                
                if (dictObj) {
                  switch (dictObj.colorType) {
                    case 'blue':
                      bgColor = 'bg-blue-100';
                      textColor = 'text-blue-700';
                      borderColor = 'border-blue-200';
                      break;
                    case 'green':
                      bgColor = 'bg-green-100';
                      textColor = 'text-green-700';
                      borderColor = 'border-green-200';
                      break;
                    case 'orange':
                      bgColor = 'bg-orange-100';
                      textColor = 'text-orange-700';
                      borderColor = 'border-orange-200';
                      break;
                    default:
                      bgColor = 'bg-gray-100';
                      textColor = 'text-gray-700';
                      borderColor = 'border-gray-200';
                  }
                }
                
                return (
                  <span className={`inline-flex px-3 py-1 rounded-lg text-xs ${bgColor} ${textColor} border ${borderColor}`}>
                    {detailMessage.type || t('notificationManagement.appNotify')}
                  </span>
                );
              })()}
            </Descriptions.Item>
            <Descriptions.Item label={t('notificationManagement.isRead')}>
              {detailMessage.status === 'read' ? (
                <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-gray-100 text-gray-700 border border-gray-200">
                  {t('notificationManagement.read')}
                </span>
              ) : (
                <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-red-100 text-red-700 border border-red-200">
                  {t('notificationManagement.unread')}
                </span>
              )}
            </Descriptions.Item>
            {detailMessage.readTime && (
              <Descriptions.Item label={t('notificationManagement.readTime')}>
                {dateFormatter(detailMessage.readTime)}
              </Descriptions.Item>
            )}
            <Descriptions.Item label={t('notificationManagement.content')}>
              <div className="text-sm text-gray-900 bg-gray-50 p-3 rounded-lg border border-gray-200 min-h-[80px] whitespace-pre-wrap">
                {detailMessage.content || '-'}
              </div>
            </Descriptions.Item>
          </Descriptions>
        ) : null}
      </Modal>
    </div>
  );
}

