'use client';

import { useState, useCallback, useEffect } from 'react';
import { Modal, toast, Button } from '@/components/common';
import { cn } from '@/utils/helpers';
import {
  userTagService,
  TagCategory,
  UserTag,
  TagType,
  TagValueType,
  TagUserItem,
  TAG_TYPE_OPTIONS,
  TAG_VALUE_TYPE_OPTIONS,
  TAG_COLORS,
} from '@/services/userTagService';
import { formatDateTime } from '@/utils/formatters';
import styles from './UserTagsTab.module.scss';

/**
 * 用户标签管理 Tab
 */
export const UserTagsTab = () => {
  // 数据状态
  const [categories, setCategories] = useState<TagCategory[]>([]);
  const [tags, setTags] = useState<UserTag[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeCategory, setActiveCategory] = useState<string | null>(null);

  // 分类弹窗状态
  const [showCategoryModal, setShowCategoryModal] = useState(false);
  const [editingCategory, setEditingCategory] = useState<TagCategory | null>(null);
  const [categoryForm, setCategoryForm] = useState({
    code: '',
    name: '',
    description: '',
  });

  // 标签弹窗状态
  const [showTagModal, setShowTagModal] = useState(false);
  const [editingTag, setEditingTag] = useState<UserTag | null>(null);
  const [tagForm, setTagForm] = useState({
    code: '',
    name: '',
    description: '',
    color: TAG_COLORS[0],
    type: 'MANUAL' as TagType,
    valueType: 'BOOLEAN' as TagValueType,
    enumValues: '',
    isAdvertisable: true,
  });

  // 删除确认
  const [deleteConfirm, setDeleteConfirm] = useState<{ type: 'category' | 'tag'; id: string } | null>(null);

  // 分配用户弹窗状态
  const [showAssignModal, setShowAssignModal] = useState(false);
  const [assigningTag, setAssigningTag] = useState<UserTag | null>(null);
  const [assignForm, setAssignForm] = useState({
    userIds: '',
    value: '',
    reason: '',
  });
  const [assigning, setAssigning] = useState(false);

  // 查看用户弹窗状态
  const [showUsersModal, setShowUsersModal] = useState(false);
  const [viewingTag, setViewingTag] = useState<UserTag | null>(null);
  const [tagUsers, setTagUsers] = useState<TagUserItem[]>([]);
  const [loadingUsers, setLoadingUsers] = useState(false);

  // 加载数据
  const loadData = useCallback(async () => {
    try {
      setLoading(true);
      const [categoriesData, tagsResponse] = await Promise.all([
        userTagService.getCategories(),
        userTagService.getTags({ categoryId: activeCategory ?? undefined }),
      ]);
      setCategories(categoriesData);
      setTags(tagsResponse.items);
    } catch (err) {
      toast.error((err as Error).message || '加载失败');
    } finally {
      setLoading(false);
    }
  }, [activeCategory]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // =====================
  // 分类操作
  // =====================

  const handleCreateCategory = () => {
    setEditingCategory(null);
    setCategoryForm({ code: '', name: '', description: '' });
    setShowCategoryModal(true);
  };

  const handleEditCategory = (category: TagCategory) => {
    setEditingCategory(category);
    setCategoryForm({
      code: category.code,
      name: category.name,
      description: category.description || '',
    });
    setShowCategoryModal(true);
  };

  const handleSaveCategory = async () => {
    if (!categoryForm.name.trim()) {
      toast.error('请输入分类名称');
      return;
    }
    if (!editingCategory && !categoryForm.code.trim()) {
      toast.error('请输入分类代码');
      return;
    }

    try {
      if (editingCategory) {
        await userTagService.updateCategory(editingCategory.id, {
          name: categoryForm.name.trim(),
          description: categoryForm.description.trim() || undefined,
        });
        toast.success('分类已更新');
      } else {
        await userTagService.createCategory({
          code: categoryForm.code.trim(),
          name: categoryForm.name.trim(),
          description: categoryForm.description.trim() || undefined,
        });
        toast.success('分类已创建');
      }
      setShowCategoryModal(false);
      loadData();
    } catch (err) {
      toast.error((err as Error).message || '操作失败');
    }
  };

  const handleDeleteCategory = async () => {
    if (!deleteConfirm || deleteConfirm.type !== 'category') return;
    try {
      await userTagService.deleteCategory(deleteConfirm.id);
      toast.success('分类已删除');
      setDeleteConfirm(null);
      if (activeCategory === deleteConfirm.id) {
        setActiveCategory(null);
      }
      loadData();
    } catch (err) {
      toast.error((err as Error).message || '删除失败');
    }
  };

  // =====================
  // 标签操作
  // =====================

  const handleCreateTag = () => {
    setEditingTag(null);
    setTagForm({
      code: '',
      name: '',
      description: '',
      color: TAG_COLORS[0],
      type: 'MANUAL',
      valueType: 'BOOLEAN',
      enumValues: '',
      isAdvertisable: true,
    });
    setShowTagModal(true);
  };

  const handleEditTag = (tag: UserTag) => {
    setEditingTag(tag);
    setTagForm({
      code: tag.code,
      name: tag.name,
      description: tag.description || '',
      color: tag.color || TAG_COLORS[0],
      type: tag.type,
      valueType: tag.valueType,
      enumValues: tag.enumValues?.join(', ') || '',
      isAdvertisable: tag.isAdvertisable,
    });
    setShowTagModal(true);
  };

  const handleSaveTag = async () => {
    if (!tagForm.name.trim()) {
      toast.error('请输入标签名称');
      return;
    }
    if (!editingTag && !tagForm.code.trim()) {
      toast.error('请输入标签代码');
      return;
    }

    try {
      const enumValues = tagForm.valueType === 'ENUM' && tagForm.enumValues.trim()
        ? tagForm.enumValues.split(',').map(v => v.trim()).filter(Boolean)
        : undefined;

      if (editingTag) {
        await userTagService.updateTag(editingTag.id, {
          categoryId: activeCategory || undefined,
          name: tagForm.name.trim(),
          description: tagForm.description.trim() || undefined,
          color: tagForm.color,
          type: tagForm.type,
          valueType: tagForm.valueType,
          enumValues,
          isAdvertisable: tagForm.isAdvertisable,
        });
        toast.success('标签已更新');
      } else {
        await userTagService.createTag({
          categoryId: activeCategory || undefined,
          code: tagForm.code.trim(),
          name: tagForm.name.trim(),
          description: tagForm.description.trim() || undefined,
          color: tagForm.color,
          type: tagForm.type,
          valueType: tagForm.valueType,
          enumValues,
          isAdvertisable: tagForm.isAdvertisable,
        });
        toast.success('标签已创建');
      }
      setShowTagModal(false);
      loadData();
    } catch (err) {
      toast.error((err as Error).message || '操作失败');
    }
  };

  const handleDeleteTag = async () => {
    if (!deleteConfirm || deleteConfirm.type !== 'tag') return;
    try {
      await userTagService.deleteTag(deleteConfirm.id);
      toast.success('标签已删除');
      setDeleteConfirm(null);
      loadData();
    } catch (err) {
      toast.error((err as Error).message || '删除失败');
    }
  };

  // =====================
  // 分配用户操作
  // =====================

  const handleOpenAssignModal = (tag: UserTag) => {
    setAssigningTag(tag);
    setAssignForm({ userIds: '', value: '', reason: '' });
    setShowAssignModal(true);
  };

  const handleAssignUsers = async () => {
    if (!assigningTag) return;

    const userIds = assignForm.userIds
      .split(/[\n,]/)
      .map(id => id.trim())
      .filter(Boolean);

    if (userIds.length === 0) {
      toast.error('请输入用户ID');
      return;
    }

    try {
      setAssigning(true);
      const result = await userTagService.batchAssignTag({
        tagId: assigningTag.id,
        accountSequences: userIds,
        value: assignForm.value.trim() || undefined,
        reason: assignForm.reason.trim() || undefined,
      });

      if (result.failed > 0) {
        toast.warning(`成功: ${result.success}, 失败: ${result.failed}`);
      } else {
        toast.success(`成功分配给 ${result.success} 个用户`);
      }

      setShowAssignModal(false);
      loadData(); // 刷新以更新预估用户数
    } catch (err) {
      toast.error((err as Error).message || '分配失败');
    } finally {
      setAssigning(false);
    }
  };

  // =====================
  // 查看用户操作
  // =====================

  const handleViewUsers = async (tag: UserTag) => {
    setViewingTag(tag);
    setShowUsersModal(true);
    setLoadingUsers(true);

    try {
      const response = await userTagService.getTagUsers(tag.id, { limit: 100 });
      setTagUsers(response.items);
    } catch (err) {
      toast.error((err as Error).message || '加载用户失败');
    } finally {
      setLoadingUsers(false);
    }
  };

  const handleRemoveUserTag = async (accountSequence: string) => {
    if (!viewingTag) return;

    try {
      await userTagService.removeTag({
        accountSequence,
        tagId: viewingTag.id,
      });
      toast.success('已移除用户标签');
      // 刷新用户列表
      const response = await userTagService.getTagUsers(viewingTag.id, { limit: 100 });
      setTagUsers(response.items);
      loadData(); // 刷新以更新预估用户数
    } catch (err) {
      toast.error((err as Error).message || '移除失败');
    }
  };

  // 获取标签类型显示
  const getTagTypeLabel = (type: TagType) => {
    const opt = TAG_TYPE_OPTIONS.find(o => o.value === type);
    return opt?.label || type;
  };

  const getTagTypeColor = (type: TagType) => {
    const opt = TAG_TYPE_OPTIONS.find(o => o.value === type);
    return opt?.color || 'gray';
  };

  if (loading && categories.length === 0) {
    return <div className={styles.loading}>加载中...</div>;
  }

  return (
    <div className={styles.container}>
      {/* 左侧分类列表 */}
      <div className={styles.sidebar}>
        <div className={styles.sidebarHeader}>
          <h3>标签分类</h3>
          <button className={styles.addBtn} onClick={handleCreateCategory}>+</button>
        </div>
        <div className={styles.categoryList}>
          <div
            className={cn(styles.categoryItem, !activeCategory && styles.active)}
            onClick={() => setActiveCategory(null)}
          >
            <span>全部标签</span>
            <span className={styles.count}>{tags.length}</span>
          </div>
          {categories.map(cat => (
            <div
              key={cat.id}
              className={cn(styles.categoryItem, activeCategory === cat.id && styles.active)}
              onClick={() => setActiveCategory(cat.id)}
            >
              <span>{cat.name}</span>
              <div className={styles.categoryActions}>
                <button onClick={(e) => { e.stopPropagation(); handleEditCategory(cat); }}>编辑</button>
                <button onClick={(e) => { e.stopPropagation(); setDeleteConfirm({ type: 'category', id: cat.id }); }}>删除</button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 右侧标签列表 */}
      <div className={styles.main}>
        <div className={styles.mainHeader}>
          <h3>{activeCategory ? categories.find(c => c.id === activeCategory)?.name : '全部标签'}</h3>
          <Button variant="primary" size="sm" onClick={handleCreateTag}>+ 新建标签</Button>
        </div>

        {loading ? (
          <div className={styles.loading}>加载中...</div>
        ) : tags.length === 0 ? (
          <div className={styles.empty}>暂无标签，点击"新建标签"创建</div>
        ) : (
          <div className={styles.tagGrid}>
            {tags.map(tag => (
              <div key={tag.id} className={styles.tagCard}>
                <div className={styles.tagHeader}>
                  <span
                    className={styles.tagColor}
                    style={{ backgroundColor: tag.color || '#6B7280' }}
                  />
                  <span className={styles.tagName}>{tag.name}</span>
                  <span className={cn(styles.tagType, styles[`tagType--${getTagTypeColor(tag.type)}`])}>
                    {getTagTypeLabel(tag.type)}
                  </span>
                </div>
                <div className={styles.tagCode}>代码: {tag.code}</div>
                {tag.description && <div className={styles.tagDesc}>{tag.description}</div>}
                <div className={styles.tagMeta}>
                  {tag.estimatedUsers !== null && (
                    <span>预估用户: {tag.estimatedUsers.toLocaleString()}</span>
                  )}
                  {tag.isAdvertisable && <span className={styles.adBadge}>可投放</span>}
                </div>
                <div className={styles.tagActions}>
                  <button onClick={() => handleOpenAssignModal(tag)}>分配用户</button>
                  <button onClick={() => handleViewUsers(tag)}>查看用户</button>
                  <button onClick={() => handleEditTag(tag)}>编辑</button>
                  <button onClick={() => setDeleteConfirm({ type: 'tag', id: tag.id })}>删除</button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 分类弹窗 */}
      <Modal
        visible={showCategoryModal}
        title={editingCategory ? '编辑分类' : '新建分类'}
        onClose={() => setShowCategoryModal(false)}
        footer={
          <div className={styles.modalFooter}>
            <Button variant="outline" onClick={() => setShowCategoryModal(false)}>取消</Button>
            <Button variant="primary" onClick={handleSaveCategory}>保存</Button>
          </div>
        }
        width={480}
      >
        <div className={styles.form}>
          {!editingCategory && (
            <div className={styles.formGroup}>
              <label>分类代码 *</label>
              <input
                type="text"
                value={categoryForm.code}
                onChange={e => setCategoryForm({ ...categoryForm, code: e.target.value })}
                placeholder="如: lifecycle, behavior"
              />
            </div>
          )}
          <div className={styles.formGroup}>
            <label>分类名称 *</label>
            <input
              type="text"
              value={categoryForm.name}
              onChange={e => setCategoryForm({ ...categoryForm, name: e.target.value })}
              placeholder="如: 生命周期, 行为特征"
            />
          </div>
          <div className={styles.formGroup}>
            <label>描述</label>
            <textarea
              value={categoryForm.description}
              onChange={e => setCategoryForm({ ...categoryForm, description: e.target.value })}
              placeholder="分类说明"
              rows={3}
            />
          </div>
        </div>
      </Modal>

      {/* 标签弹窗 */}
      <Modal
        visible={showTagModal}
        title={editingTag ? '编辑标签' : '新建标签'}
        onClose={() => setShowTagModal(false)}
        footer={
          <div className={styles.modalFooter}>
            <Button variant="outline" onClick={() => setShowTagModal(false)}>取消</Button>
            <Button variant="primary" onClick={handleSaveTag}>保存</Button>
          </div>
        }
        width={560}
      >
        <div className={styles.form}>
          {!editingTag && (
            <div className={styles.formGroup}>
              <label>标签代码 *</label>
              <input
                type="text"
                value={tagForm.code}
                onChange={e => setTagForm({ ...tagForm, code: e.target.value })}
                placeholder="如: vip, new_user, whale"
              />
            </div>
          )}
          <div className={styles.formGroup}>
            <label>标签名称 *</label>
            <input
              type="text"
              value={tagForm.name}
              onChange={e => setTagForm({ ...tagForm, name: e.target.value })}
              placeholder="如: VIP用户, 新用户"
            />
          </div>
          <div className={styles.formGroup}>
            <label>描述</label>
            <textarea
              value={tagForm.description}
              onChange={e => setTagForm({ ...tagForm, description: e.target.value })}
              placeholder="标签说明"
              rows={2}
            />
          </div>
          <div className={styles.formRow}>
            <div className={styles.formGroup}>
              <label>标签类型</label>
              <select
                value={tagForm.type}
                onChange={e => setTagForm({ ...tagForm, type: e.target.value as TagType })}
              >
                {TAG_TYPE_OPTIONS.map(opt => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>
            </div>
            <div className={styles.formGroup}>
              <label>值类型</label>
              <select
                value={tagForm.valueType}
                onChange={e => setTagForm({ ...tagForm, valueType: e.target.value as TagValueType })}
              >
                {TAG_VALUE_TYPE_OPTIONS.map(opt => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>
            </div>
          </div>
          {tagForm.valueType === 'ENUM' && (
            <div className={styles.formGroup}>
              <label>枚举值 (逗号分隔)</label>
              <input
                type="text"
                value={tagForm.enumValues}
                onChange={e => setTagForm({ ...tagForm, enumValues: e.target.value })}
                placeholder="如: 高, 中, 低"
              />
            </div>
          )}
          <div className={styles.formGroup}>
            <label>标签颜色</label>
            <div className={styles.colorPicker}>
              {TAG_COLORS.map(color => (
                <button
                  key={color}
                  className={cn(styles.colorBtn, tagForm.color === color && styles.selected)}
                  style={{ backgroundColor: color }}
                  onClick={() => setTagForm({ ...tagForm, color })}
                />
              ))}
            </div>
          </div>
          <div className={styles.formGroup}>
            <label className={styles.checkbox}>
              <input
                type="checkbox"
                checked={tagForm.isAdvertisable}
                onChange={e => setTagForm({ ...tagForm, isAdvertisable: e.target.checked })}
              />
              <span>可用于广告定向</span>
            </label>
          </div>
        </div>
      </Modal>

      {/* 删除确认弹窗 */}
      <Modal
        visible={!!deleteConfirm}
        title="确认删除"
        onClose={() => setDeleteConfirm(null)}
        footer={
          <div className={styles.modalFooter}>
            <Button variant="outline" onClick={() => setDeleteConfirm(null)}>取消</Button>
            <Button
              variant="danger"
              onClick={deleteConfirm?.type === 'category' ? handleDeleteCategory : handleDeleteTag}
            >
              确认删除
            </Button>
          </div>
        }
        width={400}
      >
        <p>
          {deleteConfirm?.type === 'category'
            ? '确定要删除这个分类吗？分类下的标签将变为未分类。'
            : '确定要删除这个标签吗？相关的用户标签关联也会被删除。'}
        </p>
      </Modal>

      {/* 分配用户弹窗 */}
      <Modal
        visible={showAssignModal}
        title={`分配用户到标签: ${assigningTag?.name || ''}`}
        onClose={() => setShowAssignModal(false)}
        footer={
          <div className={styles.modalFooter}>
            <Button variant="outline" onClick={() => setShowAssignModal(false)}>取消</Button>
            <Button variant="primary" onClick={handleAssignUsers} disabled={assigning}>
              {assigning ? '分配中...' : '确认分配'}
            </Button>
          </div>
        }
        width={560}
      >
        <div className={styles.form}>
          <div className={styles.formGroup}>
            <label>用户ID列表 *</label>
            <textarea
              className={styles.userIdsInput}
              value={assignForm.userIds}
              onChange={e => setAssignForm({ ...assignForm, userIds: e.target.value })}
              placeholder="请输入用户ID（账户序列号），每行一个或用逗号分隔&#10;例如:&#10;000000000001&#10;000000000002"
              rows={6}
            />
            <span className={styles.formHint}>
              当前 {assignForm.userIds.split(/[\n,]/).filter(s => s.trim()).length} 个用户
            </span>
          </div>
          {assigningTag?.valueType !== 'BOOLEAN' && (
            <div className={styles.formGroup}>
              <label>标签值 {assigningTag?.valueType === 'ENUM' ? `(可选值: ${assigningTag.enumValues?.join(', ')})` : ''}</label>
              {assigningTag?.valueType === 'ENUM' && assigningTag.enumValues ? (
                <select
                  value={assignForm.value}
                  onChange={e => setAssignForm({ ...assignForm, value: e.target.value })}
                >
                  <option value="">请选择</option>
                  {assigningTag.enumValues.map(v => (
                    <option key={v} value={v}>{v}</option>
                  ))}
                </select>
              ) : (
                <input
                  type="text"
                  value={assignForm.value}
                  onChange={e => setAssignForm({ ...assignForm, value: e.target.value })}
                  placeholder={assigningTag?.valueType === 'NUMBER' ? '输入数字' : '输入值'}
                />
              )}
            </div>
          )}
          <div className={styles.formGroup}>
            <label>备注原因 (可选)</label>
            <input
              type="text"
              value={assignForm.reason}
              onChange={e => setAssignForm({ ...assignForm, reason: e.target.value })}
              placeholder="如: 批量导入, 运营活动等"
            />
          </div>
        </div>
      </Modal>

      {/* 查看用户弹窗 */}
      <Modal
        visible={showUsersModal}
        title={`标签用户: ${viewingTag?.name || ''}`}
        onClose={() => setShowUsersModal(false)}
        footer={
          <div className={styles.modalFooter}>
            <Button variant="outline" onClick={() => setShowUsersModal(false)}>关闭</Button>
            <Button variant="primary" onClick={() => viewingTag && handleOpenAssignModal(viewingTag)}>
              + 添加用户
            </Button>
          </div>
        }
        width={640}
      >
        <div className={styles.usersList}>
          {loadingUsers ? (
            <div className={styles.loading}>加载中...</div>
          ) : tagUsers.length === 0 ? (
            <div className={styles.empty}>暂无用户拥有此标签</div>
          ) : (
            <>
              <div className={styles.usersHeader}>
                <span>共 {tagUsers.length} 个用户</span>
              </div>
              <table className={styles.usersTable}>
                <thead>
                  <tr>
                    <th>用户ID</th>
                    <th>标签值</th>
                    <th>分配时间</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {tagUsers.map(user => (
                    <tr key={user.accountSequence}>
                      <td>{user.accountSequence}</td>
                      <td>{user.value || '-'}</td>
                      <td>{formatDateTime(user.assignedAt)}</td>
                      <td>
                        <button
                          className={styles.removeBtn}
                          onClick={() => handleRemoveUserTag(user.accountSequence)}
                        >
                          移除
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </>
          )}
        </div>
      </Modal>
    </div>
  );
};

export default UserTagsTab;
