import React, { useState, useEffect, useCallback } from 'react';
import { t } from '@/i18n';
import { getMessages, markAllRead, markAsRead } from '../../services/notification';
import type { MessageItem } from '../../services/notification';
// Taro mini-program component

/**
 * P2. 消息中心
 *
 * 交易通知、到期提醒、价格提醒、公告
 */

const typeIconMap: Record<string, string> = {
  transaction: '\uD83D\uDD04',
  expiry: '\u23F0',
  price: '\uD83D\uDCC8',
  announcement: '\uD83D\uDCE2',
};

const typeColorMap: Record<string, string> = {
  transaction: '#6C5CE7',
  expiry: '#FF9500',
  price: '#00C48C',
  announcement: '#3498DB',
};

const TAB_TYPE_MAP: (string | null)[] = [null, 'transaction', 'expiry', 'announcement'];

const MessagesPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState(0);
  const [messages, setMessages] = useState<MessageItem[]>([]);
  const [loading, setLoading] = useState(true);

  const tabs = [
    { label: t('all'), filter: null },
    { label: t('messages_tab_trade'), filter: 'transaction' },
    { label: t('messages_tab_expiry'), filter: 'expiry' },
    { label: t('messages_tab_announcement'), filter: 'announcement' },
  ];

  const loadMessages = useCallback((tabIndex: number) => {
    setLoading(true);
    const typeFilter = TAB_TYPE_MAP[tabIndex];
    getMessages({ type: typeFilter || undefined })
      .then((data) => setMessages(data.items))
      .catch(() => setMessages([]))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    loadMessages(activeTab);
  }, [activeTab, loadMessages]);

  const handleMarkAllRead = () => {
    markAllRead()
      .then(() => {
        setMessages((prev) => prev.map((m) => ({ ...m, isRead: true })));
      })
      .catch(() => {});
  };

  const handleMessageTap = (msg: MessageItem) => {
    if (!msg.isRead) {
      markAsRead(msg.id)
        .then(() => {
          setMessages((prev) => prev.map((m) => m.id === msg.id ? { ...m, isRead: true } : m));
        })
        .catch(() => {});
    }
  };

  const formatTime = (dateStr: string) => {
    if (!dateStr) return '';
    try {
      const date = new Date(dateStr);
      const now = new Date();
      if (date.toDateString() === now.toDateString()) {
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
      }
      return `${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}`;
    } catch {
      return dateStr;
    }
  };

  return (
    <view className="messages-page">
      {/* Header */}
      <view className="msg-header">
        <text className="msg-header-title">{t('messages_title')}</text>
        <text className="msg-mark-read" onClick={handleMarkAllRead}>{t('messages_mark_all_read')}</text>
      </view>

      {/* Tab Row */}
      <view className="msg-tabs">
        {tabs.map((tab, i) => (
          <view
            key={i}
            className={`msg-tab ${activeTab === i ? 'msg-tab-active' : ''}`}
            onClick={() => setActiveTab(i)}
          >
            <text className={`msg-tab-text ${activeTab === i ? 'msg-tab-text-active' : ''}`}>
              {tab.label}
            </text>
          </view>
        ))}
      </view>

      {/* Message List */}
      <scroll-view scrollY className="msg-list">
        {loading ? (
          <view style={{ textAlign: 'center', padding: '80rpx 0' }}>
            <text style={{ color: '#A0A8BE', fontSize: '26rpx' }}>{t('loading') || '加载中...'}</text>
          </view>
        ) : messages.length === 0 ? (
          <view className="msg-empty">
            <text className="msg-empty-icon">{typeIconMap.announcement}</text>
            <text className="msg-empty-text">{t('messages_empty')}</text>
          </view>
        ) : (
          messages.map((msg) => (
            <view key={msg.id} className="msg-item" onClick={() => handleMessageTap(msg)}>
              <view className="msg-icon-circle" style={{ background: typeColorMap[msg.type] || '#6C5CE7' }}>
                <text className="msg-icon-emoji">{typeIconMap[msg.type] || typeIconMap.announcement}</text>
              </view>
              <view className="msg-content">
                <view className="msg-title-row">
                  <text className={`msg-title ${!msg.isRead ? 'msg-title-unread' : ''}`}>
                    {msg.title}
                  </text>
                  <text className="msg-time">{formatTime(msg.createdAt)}</text>
                </view>
                <text className="msg-body">{msg.content}</text>
              </view>
              {!msg.isRead && <view className="msg-unread-dot" />}
            </view>
          ))
        )}
      </scroll-view>
    </view>
  );
};

export default MessagesPage;

/*
CSS:

.messages-page { background: #F8F9FC; min-height: 100vh; }

.msg-header {
  display: flex; align-items: center; justify-content: space-between;
  padding: 48rpx 32rpx 24rpx; background: white;
}
.msg-header-title { font-size: 36rpx; font-weight: 700; color: #141723; }
.msg-mark-read { font-size: 24rpx; color: #6C5CE7; }

.msg-tabs {
  display: flex; padding: 0 32rpx 20rpx; background: white;
  border-bottom: 1rpx solid #F1F3F8; gap: 12rpx;
}
.msg-tab {
  padding: 10rpx 24rpx; border-radius: 999rpx;
  background: #F1F3F8;
}
.msg-tab-active { background: #6C5CE7; }
.msg-tab-text { font-size: 24rpx; color: #5C6478; }
.msg-tab-text-active { color: white; font-weight: 500; }

.msg-list { padding: 16rpx 0; }

.msg-item {
  display: flex; align-items: flex-start;
  padding: 24rpx 32rpx; background: white;
  margin-bottom: 2rpx; position: relative;
}
.msg-icon-circle {
  width: 72rpx; height: 72rpx; border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  flex-shrink: 0;
}
.msg-icon-emoji { font-size: 32rpx; }
.msg-content { flex: 1; margin-left: 20rpx; margin-right: 16rpx; }
.msg-title-row {
  display: flex; align-items: center; justify-content: space-between;
}
.msg-title { font-size: 28rpx; color: #141723; }
.msg-title-unread { font-weight: 600; }
.msg-time { font-size: 22rpx; color: #A0A8BE; flex-shrink: 0; }
.msg-body {
  font-size: 24rpx; color: #5C6478; margin-top: 8rpx;
  display: -webkit-box; -webkit-line-clamp: 2;
  -webkit-box-orient: vertical; overflow: hidden;
}
.msg-unread-dot {
  width: 16rpx; height: 16rpx; border-radius: 50%;
  background: #6C5CE7; flex-shrink: 0; margin-top: 6rpx;
}

.msg-empty {
  display: flex; flex-direction: column; align-items: center;
  padding: 120rpx 0;
}
.msg-empty-icon { font-size: 80rpx; margin-bottom: 20rpx; }
.msg-empty-text { font-size: 28rpx; color: #A0A8BE; }
*/
