'use client';

import { useState, useCallback, useEffect } from 'react';
import { Modal, toast, Button } from '@/components/common';
import { PageContainer } from '@/components/layout';
import { UserTagsTab, AudienceSegmentsTab } from '@/components/features/notifications';
import { cn } from '@/utils/helpers';
import { formatDateTime } from '@/utils/formatters';
import {
  notificationService,
  NotificationItem,
  NotificationType,
  NotificationPriority,
  TargetType,
  NOTIFICATION_TYPE_OPTIONS,
  NOTIFICATION_PRIORITY_OPTIONS,
  TARGET_TYPE_OPTIONS,
} from '@/services/notificationService';
import { userTagService, UserTag } from '@/services/userTagService';
import styles from './notifications.module.scss';

// Tab 类型
type TabType = 'notifications' | 'tags' | 'segments';

const TABS = [
  { key: 'notifications' as TabType, label: '通知列表' },
  { key: 'tags' as TabType, label: '用户标签' },
  { key: 'segments' as TabType, label: '人群包' },
];

// 获取类型标签样式
const getTypeStyle = (type: NotificationType) => {
  const option = NOTIFICATION_TYPE_OPTIONS.find((o) => o.value === type);
  return option?.color || 'gray';
};

// 获取类型标签文本
const getTypeLabel = (type: NotificationType) => {
  const option = NOTIFICATION_TYPE_OPTIONS.find((o) => o.value === type);
  return option?.label || type;
};

// 获取优先级标签
const getPriorityLabel = (priority: string) => {
  const option = NOTIFICATION_PRIORITY_OPTIONS.find((o) => o.value === priority);
  return option?.label || priority;
};

// 获取目标用户标签
const getTargetLabel = (target: string) => {
  const option = TARGET_TYPE_OPTIONS.find((o) => o.value === target);
  return option?.label || target;
};

/**
 * 通知管理页面
 */
export default function NotificationsPage() {
  // Tab 状态
  const [activeTab, setActiveTab] = useState<TabType>('notifications');

  // 通知数据状态
  const [notifications, setNotifications] = useState<NotificationItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [typeFilter, setTypeFilter] = useState<NotificationType | ''>('');

  // 可用标签列表（用于定向选择）
  const [availableTags, setAvailableTags] = useState<UserTag[]>([]);

  // 弹窗状态
  const [showModal, setShowModal] = useState(false);
  const [editingNotification, setEditingNotification] = useState<NotificationItem | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);

  // 表单状态
  const [formData, setFormData] = useState({
    title: '',
    content: '',
    type: 'SYSTEM' as NotificationType,
    priority: 'NORMAL' as NotificationPriority,
    targetType: 'ALL' as TargetType,
    selectedTagIds: [] as string[],
    userIds: '',
    imageUrl: '',
    linkUrl: '',
    requiresForceRead: false,
    publishedAt: '',
    expiresAt: '',
  });

  // 加载通知列表
  const loadNotifications = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await notificationService.getNotifications({
        type: typeFilter || undefined,
        limit: 100,
      });
      setNotifications(data);
    } catch (err) {
      setError((err as Error).message || '加载失败');
    } finally {
      setLoading(false);
    }
  }, [typeFilter]);

  // 加载可用标签
  const loadTags = useCallback(async () => {
    try {
      const response = await userTagService.getTags({ isAdvertisable: true, isEnabled: true });
      setAvailableTags(response.items);
    } catch (err) {
      console.error('Failed to load tags:', err);
    }
  }, []);

  useEffect(() => {
    if (activeTab === 'notifications') {
      loadNotifications();
      loadTags();
    }
  }, [activeTab, loadNotifications, loadTags]);

  // 打开创建弹窗
  const handleCreate = () => {
    setEditingNotification(null);
    setFormData({
      title: '',
      content: '',
      type: 'SYSTEM',
      priority: 'NORMAL',
      targetType: 'ALL',
      selectedTagIds: [],
      userIds: '',
      imageUrl: '',
      linkUrl: '',
      requiresForceRead: false,
      publishedAt: '',
      expiresAt: '',
    });
    // 刷新可用标签列表，确保显示最新创建的标签
    loadTags();
    setShowModal(true);
  };

  // 打开编辑弹窗
  const handleEdit = (notification: NotificationItem) => {
    setEditingNotification(notification);
    setFormData({
      title: notification.title,
      content: notification.content,
      type: notification.type,
      priority: notification.priority,
      targetType: notification.targetType,
      selectedTagIds: notification.targetConfig?.tagIds || [],
      userIds: notification.targetConfig?.accountSequences?.join('\n') || '',
      imageUrl: notification.imageUrl || '',
      linkUrl: notification.linkUrl || '',
      requiresForceRead: notification.requiresForceRead ?? false,
      publishedAt: notification.publishedAt ? notification.publishedAt.slice(0, 16) : '',
      expiresAt: notification.expiresAt ? notification.expiresAt.slice(0, 16) : '',
    });
    setShowModal(true);
  };

  // 关闭弹窗
  const handleCloseModal = () => {
    setShowModal(false);
    setEditingNotification(null);
  };

  // 提交表单
  const handleSubmit = async () => {
    if (!formData.title.trim()) {
      toast.error('请输入通知标题');
      return;
    }
    if (!formData.content.trim()) {
      toast.error('请输入通知内容');
      return;
    }

    // 构建目标配置
    let targetConfig: { tagIds?: string[]; accountSequences?: string[] } | undefined;

    if (formData.targetType === 'BY_TAG') {
      if (formData.selectedTagIds.length === 0) {
        toast.error('请至少选择一个标签');
        return;
      }
      targetConfig = { tagIds: formData.selectedTagIds };
    } else if (formData.targetType === 'SPECIFIC') {
      const userIds = formData.userIds
        .split(/[\n,]/)
        .map(id => id.trim())
        .filter(Boolean);
      if (userIds.length === 0) {
        toast.error('请输入用户ID');
        return;
      }
      targetConfig = { accountSequences: userIds };
    }

    try {
      const payload = {
        title: formData.title.trim(),
        content: formData.content.trim(),
        type: formData.type,
        priority: formData.priority,
        targetType: formData.targetType,
        targetConfig,
        imageUrl: formData.imageUrl.trim() || undefined,
        linkUrl: formData.linkUrl.trim() || undefined,
        requiresForceRead: formData.requiresForceRead,
        publishedAt: formData.publishedAt ? new Date(formData.publishedAt).toISOString() : undefined,
        expiresAt: formData.expiresAt ? new Date(formData.expiresAt).toISOString() : undefined,
      };

      if (editingNotification) {
        await notificationService.updateNotification(editingNotification.id, payload);
        toast.success('通知已更新');
      } else {
        await notificationService.createNotification(payload);
        toast.success('通知已创建');
      }

      handleCloseModal();
      loadNotifications();
    } catch (err) {
      toast.error((err as Error).message || '操作失败');
    }
  };

  // 切换标签选择
  const toggleTagSelection = (tagId: string) => {
    setFormData(prev => ({
      ...prev,
      selectedTagIds: prev.selectedTagIds.includes(tagId)
        ? prev.selectedTagIds.filter(id => id !== tagId)
        : [...prev.selectedTagIds, tagId],
    }));
  };

  // 切换启用状态
  const handleToggle = async (notification: NotificationItem) => {
    try {
      await notificationService.toggleNotification(notification.id, !notification.isEnabled);
      toast.success(notification.isEnabled ? '已禁用' : '已启用');
      loadNotifications();
    } catch (err) {
      toast.error((err as Error).message || '操作失败');
    }
  };

  // 删除通知
  const handleDelete = async (id: string) => {
    try {
      await notificationService.deleteNotification(id);
      toast.success('通知已删除');
      setDeleteConfirm(null);
      loadNotifications();
    } catch (err) {
      toast.error((err as Error).message || '删除失败');
    }
  };

  return (
    <PageContainer title="通知管理">
      <div className={styles.notifications}>
        {/* 页面标题 */}
        <div className={styles.notifications__header}>
          <h1 className={styles.notifications__title}>通知与用户画像</h1>
        </div>

        {/* Tab 导航 */}
        <div className={styles.notifications__tabs}>
          {TABS.map(tab => (
            <button
              key={tab.key}
              className={cn(
                styles.notifications__tab,
                activeTab === tab.key && styles['notifications__tab--active']
              )}
              onClick={() => setActiveTab(tab.key)}
            >
              {tab.label}
            </button>
          ))}
        </div>

        {/* Tab 内容 */}
        {activeTab === 'notifications' && (
          <>
            {/* 主内容卡片 */}
            <div className={styles.notifications__card}>
              {/* 筛选区域 */}
              <div className={styles.notifications__filters}>
                <select
                  className={styles.notifications__select}
                  value={typeFilter}
                  onChange={(e) => setTypeFilter(e.target.value as NotificationType | '')}
                >
                  <option value="">全部类型</option>
                  {NOTIFICATION_TYPE_OPTIONS.map((opt) => (
                    <option key={opt.value} value={opt.value}>
                      {opt.label}
                    </option>
                  ))}
                </select>
                <Button variant="outline" size="sm" onClick={loadNotifications}>
                  刷新
                </Button>
                <div style={{ flex: 1 }} />
                <Button variant="primary" onClick={handleCreate}>
                  + 新建通知
                </Button>
              </div>

              {/* 通知列表 */}
              <div className={styles.notifications__list}>
                {loading ? (
                  <div className={styles.notifications__loading}>加载中...</div>
                ) : error ? (
                  <div className={styles.notifications__error}>
                    <span>{error}</span>
                    <Button variant="outline" size="sm" onClick={loadNotifications}>
                      重试
                    </Button>
                  </div>
                ) : notifications.length === 0 ? (
                  <div className={styles.notifications__empty}>
                    暂无通知，点击"新建通知"创建第一条通知
                  </div>
                ) : (
                  notifications.map((notification) => (
                    <div
                      key={notification.id}
                      className={cn(
                        styles.notifications__item,
                        !notification.isEnabled && styles['notifications__item--disabled']
                      )}
                    >
                      <div className={styles.notifications__itemHeader}>
                        <div className={styles.notifications__itemMeta}>
                          <span
                            className={cn(
                              styles.notifications__tag,
                              styles[`notifications__tag--${getTypeStyle(notification.type)}`]
                            )}
                          >
                            {getTypeLabel(notification.type)}
                          </span>
                          <span className={styles.notifications__priority}>
                            {getPriorityLabel(notification.priority)}
                          </span>
                          <span className={styles.notifications__target}>
                            {getTargetLabel(notification.targetType)}
                            {notification.targetConfig?.tagIds && notification.targetConfig.tagIds.length > 0 && (
                              <> ({notification.targetConfig.tagIds.length}个标签)</>
                            )}
                            {notification.targetConfig?.accountSequences && notification.targetConfig.accountSequences.length > 0 && (
                              <> ({notification.targetConfig.accountSequences.length}个用户)</>
                            )}
                          </span>
                          {notification.requiresForceRead && (
                            <span
                              className={styles.notifications__tag}
                              style={{ backgroundColor: '#fee2e2', color: '#b91c1c', borderColor: '#fca5a5' }}
                            >
                              强制阅读
                            </span>
                          )}
                          {!notification.isEnabled && (
                            <span className={styles.notifications__disabled}>已禁用</span>
                          )}
                        </div>
                        <div className={styles.notifications__itemActions}>
                          <button
                            className={styles.notifications__actionBtn}
                            onClick={() => handleToggle(notification)}
                          >
                            {notification.isEnabled ? '禁用' : '启用'}
                          </button>
                          <button
                            className={styles.notifications__actionBtn}
                            onClick={() => handleEdit(notification)}
                          >
                            编辑
                          </button>
                          <button
                            className={cn(styles.notifications__actionBtn, styles['notifications__actionBtn--danger'])}
                            onClick={() => setDeleteConfirm(notification.id)}
                          >
                            删除
                          </button>
                        </div>
                      </div>
                      <h3 className={styles.notifications__itemTitle}>{notification.title}</h3>
                      <p className={styles.notifications__itemContent}>{notification.content}</p>
                      <div className={styles.notifications__itemFooter}>
                        <span>创建时间: {formatDateTime(notification.createdAt)}</span>
                        {notification.publishedAt && (
                          <span>发布时间: {formatDateTime(notification.publishedAt)}</span>
                        )}
                        {notification.expiresAt && (
                          <span>过期时间: {formatDateTime(notification.expiresAt)}</span>
                        )}
                      </div>
                    </div>
                  ))
                )}
              </div>
            </div>
          </>
        )}

        {activeTab === 'tags' && (
          <div className={styles.notifications__card}>
            <UserTagsTab />
          </div>
        )}

        {activeTab === 'segments' && (
          <div className={styles.notifications__card}>
            <AudienceSegmentsTab />
          </div>
        )}

        {/* 创建/编辑弹窗 */}
        <Modal
          visible={showModal}
          title={editingNotification ? '编辑通知' : '新建通知'}
          onClose={handleCloseModal}
          footer={
            <div className={styles.notifications__modalFooter}>
              <Button variant="outline" onClick={handleCloseModal}>
                取消
              </Button>
              <Button variant="primary" onClick={handleSubmit}>
                {editingNotification ? '保存' : '创建'}
              </Button>
            </div>
          }
          width={720}
        >
          <div className={styles.notifications__form}>
            <div className={styles.notifications__formGroup}>
              <label>通知标题 *</label>
              <input
                type="text"
                value={formData.title}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                placeholder="请输入通知标题"
                maxLength={100}
              />
            </div>

            <div className={styles.notifications__formGroup}>
              <label>通知内容 *</label>
              <textarea
                value={formData.content}
                onChange={(e) => setFormData({ ...formData, content: e.target.value })}
                placeholder="请输入通知内容"
                rows={4}
              />
            </div>

            <div className={styles.notifications__formRow}>
              <div className={styles.notifications__formGroup}>
                <label>通知类型</label>
                <select
                  value={formData.type}
                  onChange={(e) => setFormData({ ...formData, type: e.target.value as NotificationType })}
                >
                  {NOTIFICATION_TYPE_OPTIONS.map((opt) => (
                    <option key={opt.value} value={opt.value}>
                      {opt.label}
                    </option>
                  ))}
                </select>
              </div>

              <div className={styles.notifications__formGroup}>
                <label>优先级</label>
                <select
                  value={formData.priority}
                  onChange={(e) => setFormData({ ...formData, priority: e.target.value as NotificationPriority })}
                >
                  {NOTIFICATION_PRIORITY_OPTIONS.map((opt) => (
                    <option key={opt.value} value={opt.value}>
                      {opt.label}
                    </option>
                  ))}
                </select>
              </div>

              <div className={styles.notifications__formGroup}>
                <label>目标用户</label>
                <select
                  value={formData.targetType}
                  onChange={(e) => setFormData({ ...formData, targetType: e.target.value as TargetType })}
                >
                  {TARGET_TYPE_OPTIONS.map((opt) => (
                    <option key={opt.value} value={opt.value}>
                      {opt.label}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {/* 按标签筛选 */}
            {formData.targetType === 'BY_TAG' && (
              <div className={styles.notifications__formGroup}>
                <label style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <span>选择标签 (满足任一标签的用户)</span>
                  <button
                    type="button"
                    onClick={loadTags}
                    style={{
                      padding: '2px 8px',
                      fontSize: '12px',
                      color: '#3b82f6',
                      background: 'transparent',
                      border: '1px solid #3b82f6',
                      borderRadius: '4px',
                      cursor: 'pointer',
                    }}
                  >
                    刷新标签
                  </button>
                </label>
                <div className={styles.notifications__tagSelector}>
                  {availableTags.length === 0 ? (
                    <div className={styles.notifications__empty} style={{ padding: '20px' }}>
                      暂无可用标签，请先在"用户标签"中创建（需勾选"可用于广告定向"）
                    </div>
                  ) : (
                    <div className={styles.notifications__tagList}>
                      {availableTags.map(tag => (
                        <label
                          key={tag.id}
                          className={cn(
                            styles.notifications__tagOption,
                            formData.selectedTagIds.includes(tag.id) && styles['notifications__tagOption--selected']
                          )}
                        >
                          <input
                            type="checkbox"
                            checked={formData.selectedTagIds.includes(tag.id)}
                            onChange={() => toggleTagSelection(tag.id)}
                          />
                          <span
                            className={styles.notifications__tagColor}
                            style={{ backgroundColor: tag.color || '#6B7280' }}
                          />
                          {tag.name}
                        </label>
                      ))}
                    </div>
                  )}
                </div>
                <span className={styles.notifications__targetHint}>
                  已选择 {formData.selectedTagIds.length} 个标签
                </span>
              </div>
            )}

            {/* 指定用户 */}
            {formData.targetType === 'SPECIFIC' && (
              <div className={styles.notifications__formGroup}>
                <label>用户ID列表（账户序列号）</label>
                <textarea
                  className={styles.notifications__userIdsInput}
                  value={formData.userIds}
                  onChange={(e) => setFormData({ ...formData, userIds: e.target.value })}
                  placeholder="请输入用户账户序列号（如 000000000001），每行一个或用逗号分隔&#10;例如:&#10;000000000001&#10;000000000002,000000000003"
                  rows={6}
                />
                <span className={styles.notifications__targetHint}>
                  支持换行或逗号分隔，当前 {formData.userIds.split(/[\n,]/).filter(s => s.trim()).length} 个用户
                </span>
              </div>
            )}

            <div className={styles.notifications__formRow}>
              <div className={styles.notifications__formGroup}>
                <label>发布时间</label>
                <input
                  type="datetime-local"
                  value={formData.publishedAt}
                  onChange={(e) => setFormData({ ...formData, publishedAt: e.target.value })}
                />
                <span className={styles.notifications__formHint}>留空表示立即发布</span>
              </div>

              <div className={styles.notifications__formGroup}>
                <label>过期时间</label>
                <input
                  type="datetime-local"
                  value={formData.expiresAt}
                  onChange={(e) => setFormData({ ...formData, expiresAt: e.target.value })}
                />
                <span className={styles.notifications__formHint}>留空表示永不过期</span>
              </div>
            </div>

            <div className={styles.notifications__formGroup}>
              <label>图片链接 (可选)</label>
              <input
                type="text"
                value={formData.imageUrl}
                onChange={(e) => setFormData({ ...formData, imageUrl: e.target.value })}
                placeholder="https://..."
              />
            </div>

            <div className={styles.notifications__formGroup}>
              <label>跳转链接 (可选)</label>
              <input
                type="text"
                value={formData.linkUrl}
                onChange={(e) => setFormData({ ...formData, linkUrl: e.target.value })}
                placeholder="https://..."
              />
            </div>

            <div className={styles.notifications__formGroup}>
              <label
                style={{ display: 'flex', alignItems: 'center', gap: '10px', cursor: 'pointer' }}
                onClick={() => setFormData({ ...formData, requiresForceRead: !formData.requiresForceRead })}
              >
                <input
                  type="checkbox"
                  checked={formData.requiresForceRead}
                  onChange={(e) => setFormData({ ...formData, requiresForceRead: e.target.checked })}
                  style={{ width: '16px', height: '16px', cursor: 'pointer' }}
                />
                <span>需要强制弹窗阅读</span>
              </label>
              <span className={styles.notifications__formHint}>
                勾选后，用户打开 App 时会强制弹窗展示此消息，用户必须勾选"我已经阅读并知晓"后才能关闭
              </span>
            </div>
          </div>
        </Modal>

        {/* 删除确认弹窗 */}
        <Modal
          visible={!!deleteConfirm}
          title="确认删除"
          onClose={() => setDeleteConfirm(null)}
          footer={
            <div className={styles.notifications__modalFooter}>
              <Button variant="outline" onClick={() => setDeleteConfirm(null)}>
                取消
              </Button>
              <Button variant="danger" onClick={() => deleteConfirm && handleDelete(deleteConfirm)}>
                确认删除
              </Button>
            </div>
          }
          width={400}
        >
          <p>确定要删除这条通知吗？此操作无法撤销。</p>
        </Modal>
      </div>
    </PageContainer>
  );
}
