import { useState } from 'react';
import { View, Text } from '@tarojs/components';
import Taro, { useDidShow } from '@tarojs/taro';
import { listConsultations, ConsultationSession } from '../../services/consultation';
import Loading from '../../components/Loading';
import './index.scss';

type MsgTab = 'consultation' | 'notification';

interface NotificationItem {
  id: string;
  title: string;
  desc: string;
  time: string;
  type: string;
}

export default function Messages() {
  const [activeTab, setActiveTab] = useState<MsgTab>('consultation');
  const [sessions, setSessions] = useState<ConsultationSession[]>([]);
  const [notifications, setNotifications] = useState<NotificationItem[]>([]);
  const [loading, setLoading] = useState(false);

  useDidShow(() => {
    loadData(activeTab);
  });

  const loadData = async (tab: MsgTab) => {
    setLoading(true);
    try {
      if (tab === 'consultation') {
        const res = await listConsultations({ page: 1, page_size: 20 });
        setSessions(res.data || []);
      } else {
        // 通知目前从咨询中提取状态变化作为示例
        // 后续可对接独立通知 API
        setNotifications([]);
      }
    } catch {
      if (tab === 'consultation') setSessions([]);
      else setNotifications([]);
    } finally {
      setLoading(false);
    }
  };

  const handleTabChange = (tab: MsgTab) => {
    setActiveTab(tab);
    loadData(tab);
  };

  const formatTime = (dateStr: string | null) => {
    if (!dateStr) return '';
    const d = new Date(dateStr);
    const now = new Date();
    const diffMs = now.getTime() - d.getTime();
    const diffMin = Math.floor(diffMs / 60000);
    if (diffMin < 60) return `${diffMin} 分钟前`;
    const diffHour = Math.floor(diffMin / 60);
    if (diffHour < 24) return `${diffHour} 小时前`;
    return dateStr.slice(0, 10);
  };

  return (
    <View className='messages-page'>
      {/* 页头 */}
      <View className='messages-header'>
        <Text className='messages-title'>消息</Text>
      </View>

      {/* Tab 切换 */}
      <View className='msg-tabs'>
        <View
          className={`msg-tab ${activeTab === 'consultation' ? 'msg-tab-active' : ''}`}
          onClick={() => handleTabChange('consultation')}
        >
          <Text className='msg-tab-text'>咨询</Text>
        </View>
        <View
          className={`msg-tab ${activeTab === 'notification' ? 'msg-tab-active' : ''}`}
          onClick={() => handleTabChange('notification')}
        >
          <Text className='msg-tab-text'>通知</Text>
        </View>
      </View>
      <View className='msg-tab-indicator'>
        <View className={`msg-tab-bar ${activeTab === 'notification' ? 'msg-tab-bar-right' : ''}`} />
      </View>

      {/* 咨询列表 */}
      {activeTab === 'consultation' && (
        <View className='msg-content'>
          {loading ? (
            <Loading />
          ) : sessions.length === 0 ? (
            <View className='msg-empty'>
              <Text className='msg-empty-text'>暂无咨询消息</Text>
            </View>
          ) : (
            sessions.map((session) => (
              <View
                key={session.id}
                className='consult-card'
                onClick={() => Taro.navigateTo({ url: `/pages/consultation/detail/index?id=${session.id}` })}
              >
                <View className='consult-info'>
                  <Text className='consult-doctor'>
                    {session.consultation_type === 'online' ? '在线咨询' : '门诊咨询'}
                  </Text>
                  <Text className='consult-preview'>
                    {session.last_message || session.subject || '暂无消息'}
                  </Text>
                </View>
                <View className='consult-meta'>
                  <Text className='consult-time'>{formatTime(session.last_message_at)}</Text>
                  {session.unread_count_patient > 0 && (
                    <View className='consult-badge'>
                      <Text className='consult-badge-text'>
                        {session.unread_count_patient > 99 ? '99+' : session.unread_count_patient}
                      </Text>
                    </View>
                  )}
                </View>
              </View>
            ))
          )}
        </View>
      )}

      {/* 通知列表 */}
      {activeTab === 'notification' && (
        <View className='msg-content'>
          {loading ? (
            <Loading />
          ) : notifications.length === 0 ? (
            <View className='msg-empty'>
              <Text className='msg-empty-text'>暂无新通知</Text>
            </View>
          ) : (
            notifications.map((n) => (
              <View key={n.id} className='notify-card'>
                <View className='notify-info'>
                  <Text className='notify-title'>{n.title}</Text>
                  <Text className='notify-desc'>{n.desc}</Text>
                </View>
                <Text className='notify-time'>{n.time}</Text>
              </View>
            ))
          )}
        </View>
      )}
    </View>
  );
}
