<template>
  <a-dropdown :trigger="['click']" v-model:open="dropdownVisible">
    <a-badge :count="unreadCount" :overflow-count="99">
      <BellOutlined
        :style="{ fontSize: '18px', cursor: 'pointer', color: iconColor }"
        @click="handleBellClick"
      />
    </a-badge>
    <template #overlay>
      <div class="notification-dropdown">
        <div class="dropdown-header">
          <span>通知消息</span>
          <a-button
            v-if="unreadCount > 0"
            type="link"
            size="small"
            @click="markAllRead"
          >
            全部已读
          </a-button>
        </div>
        <a-spin :spinning="loading">
          <div class="notification-list" v-if="notifications.length > 0">
            <div
              v-for="notification in notifications"
              :key="notification.id"
              class="notification-item"
              :class="{ unread: !notification.isRead }"
              @click="handleNotificationClick(notification)"
            >
              <div class="notification-icon">
                <component :is="getNotificationIcon(notification.notificationType)" />
              </div>
              <div class="notification-content">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-text">{{ notification.content }}</div>
                <div class="notification-time">{{ formatTime(notification.createdAt) }}</div>
              </div>
            </div>
          </div>
          <div class="empty-state" v-else>
            <InboxOutlined />
            <p>暂无通知</p>
          </div>
        </a-spin>
        <div class="dropdown-footer" v-if="total > notifications.length">
          <a-button type="link" block @click="viewAll">
            查看全部
          </a-button>
        </div>
      </div>
    </template>
  </a-dropdown>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import {
  BellOutlined,
  InboxOutlined,
  BookOutlined,
  CheckSquareOutlined,
  FileImageOutlined,
  SoundOutlined,
} from '@ant-design/icons-vue';
import { useUserStore } from '@/stores/user';
import { getNotifications, markNotificationAsRead, markAllNotificationsAsRead } from '@/api/parent';
import type { Component } from 'vue';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn';

dayjs.extend(relativeTime);
dayjs.locale('zh-cn');

interface Props {
  iconColor?: string;
}

withDefaults(defineProps<Props>(), {
  iconColor: '#666',
});

const userStore = useUserStore();
const dropdownVisible = ref(false);
const loading = ref(false);
const notifications = ref<any[]>([]);
const total = ref(0);
const unreadCount = ref(0);

const getNotificationIcon = (type: string): Component => {
  const icons: Record<string, Component> = {
    SYSTEM: SoundOutlined,
    TASK: CheckSquareOutlined,
    LESSON: BookOutlined,
    GROWTH: FileImageOutlined,
  };
  return icons[type] || BellOutlined;
};

const formatTime = (time: string) => {
  return dayjs(time).fromNow();
};

const handleBellClick = () => {
  loadNotifications();
};

const loadNotifications = async () => {
  loading.value = true;
  try {
    const role = userStore.user?.role;
    // 根据角色调用不同的API
    if (role === 'parent') {
      const data = await getNotifications({ pageSize: 5 });
      notifications.value = data.items;
      total.value = data.total;
      unreadCount.value = data.unreadCount;
    }
    // 其他角色的通知可以在这里扩展
  } catch (error: any) {
    console.error('Failed to load notifications:', error);
  } finally {
    loading.value = false;
  }
};

const handleNotificationClick = async (notification: any) => {
  if (!notification.isRead) {
    try {
      const role = userStore.user?.role;
      if (role === 'parent') {
        await markNotificationAsRead(notification.id);
      }
      notification.isRead = true;
      unreadCount.value = Math.max(0, unreadCount.value - 1);
    } catch (error) {
      console.error('Failed to mark notification as read:', error);
    }
  }
  dropdownVisible.value = false;
};

const markAllRead = async () => {
  try {
    const role = userStore.user?.role;
    if (role === 'parent') {
      await markAllNotificationsAsRead();
    }
    notifications.value.forEach((n) => (n.isRead = true));
    unreadCount.value = 0;
    message.success('已全部标记为已读');
  } catch (error) {
    message.error('操作失败');
  }
};

const viewAll = () => {
  dropdownVisible.value = false;
  // 可以跳转到通知列表页面
};

onMounted(() => {
  // 可以定期检查未读数量
});
</script>

<style scoped>
.notification-dropdown {
  width: 360px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.dropdown-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  font-weight: 500;
}

.notification-list {
  max-height: 400px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  padding: 12px 16px;
  cursor: pointer;
  transition: background 0.2s;
}

.notification-item:hover {
  background: #fafafa;
}

.notification-item.unread {
  background: #f6ffed;
}

.notification-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: #52c41a;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-title {
  font-weight: 500;
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.notification-text {
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.notification-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.empty-state {
  padding: 40px;
  text-align: center;
  color: #999;
}

.empty-state .anticon {
  font-size: 32px;
  margin-bottom: 8px;
}

.dropdown-footer {
  border-top: 1px solid #f0f0f0;
}
</style>
