import React, { useEffect, useState, useRef } from "react";
import { useParams } from "react-router-dom";
import Layout from "@/components/Layout/Layout";
import { Avatar, Popup, CheckList, Button as MobileButton, SearchBar, Tag, Empty } from "antd-mobile";
import { Spin, message } from "antd";
import {
  UserOutlined,
  PhoneOutlined,
  EnvironmentOutlined,
  TagOutlined,
  HistoryOutlined,
  ShareAltOutlined,
  TrophyOutlined,
  EditOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  CommentOutlined,
  NodeIndexOutlined,
  ClockCircleOutlined,
} from "@ant-design/icons";
import NavCommon from "@/components/NavCommon";
import { fetchUserDetail, addTag, removeTag, updateRfm } from "./api";
import {
  SOURCE_TYPE_TEXT,
  LEVEL_TEXT,
  LIFECYCLE_TEXT,
  INTENTION_LEVEL_TEXT,
  FRIEND_STATUS_TEXT,
  getTagDefines,
  syncTagsFromEngine,
  getPoolSources,
  getPoolBehaviors,
  type TagDefine,
} from "../api";
import styles from "./index.module.scss";

const defaultAvatar = "https://cdn.jsdelivr.net/gh/maokaka/static/avatar-default.png";

const TrafficPoolDetail: React.FC = () => {
  const { id } = useParams<{ wechatId: string; id: string }>();
  const [loading, setLoading] = useState(false);
  const [detail, setDetail] = useState<any>(null);

  // 状态管理保持原有逻辑
  const [tagModalVisible, setTagModalVisible] = useState(false);
  const [tagDefines, setTagDefines] = useState<TagDefine[]>([]);
  const [selectedTagIds, setSelectedTagIds] = useState<number[]>([]);
  const [tagLoading, setTagLoading] = useState(false);
  const [syncLoading, setSyncLoading] = useState(false);
  const [rfmLoading, setRfmLoading] = useState(false);

  const [sourcesPage, setSourcesPage] = useState(1);
  const [sourcesLoading, setSourcesLoading] = useState(false);
  const [sourcesTotal, setSourcesTotal] = useState(0);
  const [allSources, setAllSources] = useState<any[]>([]);
  const [sourcesKeyword, setSourcesKeyword] = useState("");
  const [sourcesSearchInput, setSourcesSearchInput] = useState("");
  const sourcesSearchTimer = useRef<NodeJS.Timeout | null>(null);
  const sourcesKeywordInitialized = useRef(false);

  const [behaviorsPage, setBehaviorsPage] = useState(1);
  const [behaviorsLoading, setBehaviorsLoading] = useState(false);
  const [behaviorsTotal, setBehaviorsTotal] = useState(0);
  const [allBehaviors, setAllBehaviors] = useState<any[]>([]);
  const [behaviorsKeyword, setBehaviorsKeyword] = useState("");
  const [behaviorsSearchInput, setBehaviorsSearchInput] = useState("");
  const behaviorsSearchTimer = useRef<NodeJS.Timeout | null>(null);
  const behaviorsKeywordInitialized = useRef(false);

  useEffect(() => {
    if (id) loadDetail();
  }, [id]);

  const loadDetail = async () => {
    if (!id) return;
    // 如果有搜索关键词，不重置搜索状态
    if (sourcesKeyword || behaviorsKeyword) {
      return;
    }

    setLoading(true);
    try {
      const res = await fetchUserDetail(parseInt(id));
      setDetail(res);
      // 初始化来源和行为数据（详情接口返回的前50条）
      const initialSources = res.sources || [];
      const initialBehaviors = res.behaviors || [];
      setAllSources(initialSources);
      setAllBehaviors(initialBehaviors);

      // 如果返回了50条，说明可能还有更多，需要获取总数
      if (initialSources.length >= 50) {
        try {
          const sourcesResult = await getPoolSources({
            poolCompanyId: parseInt(id),
            page: 1,
            pageSize: 1,
          });
          setSourcesTotal(sourcesResult.total);
          setSourcesPage(3);
        } catch (e) {
          setSourcesTotal(initialSources.length);
          setSourcesPage(1);
        }
      } else {
        setSourcesTotal(initialSources.length);
        setSourcesPage(1);
      }

      if (initialBehaviors.length >= 50) {
        try {
          const behaviorsResult = await getPoolBehaviors({
            poolCompanyId: parseInt(id),
            page: 1,
            pageSize: 1,
          });
          setBehaviorsTotal(behaviorsResult.total);
          setBehaviorsPage(3);
        } catch (e) {
          setBehaviorsTotal(initialBehaviors.length);
          setBehaviorsPage(1);
        }
      } else {
        setBehaviorsTotal(initialBehaviors.length);
        setBehaviorsPage(1);
      }
    } catch (error: any) {
      message.error(error?.message || "获取详情失败");
    } finally {
      setLoading(false);
    }
  };

  // 搜索来源（带防抖）
  const handleSourcesSearchChange = (value: string) => {
    setSourcesSearchInput(value);
    if (sourcesSearchTimer.current) {
      clearTimeout(sourcesSearchTimer.current);
    }
    sourcesSearchTimer.current = setTimeout(() => {
      setSourcesKeyword(value);
      setSourcesPage(1);
    }, 500);
  };

  // 搜索来源数据
  const searchSources = async (keyword: string, page: number = 1) => {
    if (!id) return;
    setSourcesLoading(true);
    try {
      const result = await getPoolSources({
        poolCompanyId: parseInt(id),
        page,
        pageSize: keyword ? 100 : 50,
        keyword,
      });
      if (page === 1) {
        setAllSources(result.list);
      } else {
        // 去重合并
        const existingIds = new Set(allSources.map(s => s.id));
        const newList = result.list.filter(s => !existingIds.has(s.id));
        setAllSources([...allSources, ...newList]);
      }
      setSourcesTotal(result.total);
      setSourcesPage(page);
    } catch (error: any) {
      message.error(error?.message || "搜索失败");
    } finally {
      setSourcesLoading(false);
    }
  };

  // 加载更多来源
  const loadMoreSources = async () => {
    if (!id || sourcesLoading) return;
    const nextPage = sourcesPage + 1;
    await searchSources(sourcesKeyword, nextPage);
  };

  // 监听搜索关键词变化
  useEffect(() => {
    if (!sourcesKeywordInitialized.current) {
      sourcesKeywordInitialized.current = true;
      return;
    }
    if (id && sourcesKeyword !== "") {
      searchSources(sourcesKeyword, 1);
    } else if (id && sourcesKeyword === "") {
      loadDetail();
    }
  }, [sourcesKeyword]);

  // 搜索行为（带防抖）
  const handleBehaviorsSearchChange = (value: string) => {
    setBehaviorsSearchInput(value);
    if (behaviorsSearchTimer.current) {
      clearTimeout(behaviorsSearchTimer.current);
    }
    behaviorsSearchTimer.current = setTimeout(() => {
      setBehaviorsKeyword(value);
      setBehaviorsPage(1);
    }, 500);
  };

  // 搜索行为数据
  const searchBehaviors = async (keyword: string, page: number = 1) => {
    if (!id) return;
    setBehaviorsLoading(true);
    try {
      const result = await getPoolBehaviors({
        poolCompanyId: parseInt(id),
        page,
        pageSize: 100,
        keyword,
      });
      if (page === 1) {
        setAllBehaviors(result.list);
      } else {
        const existingIds = new Set(allBehaviors.map(b => b.id));
        const newList = result.list.filter(b => !existingIds.has(b.id));
        setAllBehaviors([...allBehaviors, ...newList]);
      }
      setBehaviorsTotal(result.total);
      setBehaviorsPage(page);
    } catch (error: any) {
      message.error(error?.message || "搜索失败");
    } finally {
      setBehaviorsLoading(false);
    }
  };

  // 加载更多行为
  const loadMoreBehaviors = async () => {
    if (!id || behaviorsLoading) return;
    const nextPage = behaviorsPage + 1;
    await searchBehaviors(behaviorsKeyword, nextPage);
  };

  // 监听搜索关键词变化
  useEffect(() => {
    if (!behaviorsKeywordInitialized.current) {
      behaviorsKeywordInitialized.current = true;
      return;
    }
    if (id && behaviorsKeyword !== "") {
      searchBehaviors(behaviorsKeyword, 1);
    } else if (id && behaviorsKeyword === "") {
      loadDetail();
    }
  }, [behaviorsKeyword]);

  // 标签处理逻辑
  const openTagModal = async () => {
    setTagModalVisible(true);
    setTagLoading(true);
    try {
      const defines = await getTagDefines({ tagType: 2 });
      setTagDefines(defines);
      const existingTagIds = detail?.tags?.filter((t: any) => t.tagType === 2).map((t: any) => t.tagDefineId) || [];
      setSelectedTagIds(existingTagIds);
    } catch (error) {
      message.error("获取标签列表失败");
    } finally {
      setTagLoading(false);
    }
  };

  const handleSyncTags = async () => {
    if (!id || syncLoading) return;
    setSyncLoading(true);
    try {
      const result = await syncTagsFromEngine(parseInt(id));
      message.success(`同步成功：已同步 ${result.syncedCount} 个标签`);
      loadDetail();
    } catch (error: any) {
      message.error(error?.message || "同步失败");
    } finally {
      setSyncLoading(false);
    }
  };

  const handleUpdateRfm = async () => {
    if (!detail?.identifier || rfmLoading) return;
    setRfmLoading(true);
    try {
      const result = await updateRfm(detail.identifier);
      message.success("RFM评分更新成功");
      // 重新加载详情以获取最新的RFM数据
      loadDetail();
    } catch (error: any) {
      message.error(error?.message || "RFM更新失败");
    } finally {
      setRfmLoading(false);
    }
  };

  const saveTagChanges = async () => {
    if (!id || !detail) return;
    const poolCompanyId = parseInt(id);
    const existingTagIds = detail.tags
      ?.filter((t: any) => t.tagType === 2)
      ?.map((t: any) => t.tagDefineId) || [];

    const toAdd = selectedTagIds.filter(tagId => !existingTagIds.includes(tagId));
    const toRemove = existingTagIds.filter((tagId: number) => !selectedTagIds.includes(tagId));

    setTagLoading(true);
    try {
      for (const tagDefineId of toAdd) {
        await addTag(poolCompanyId, tagDefineId);
      }
      for (const tagDefineId of toRemove) {
        await removeTag(poolCompanyId, tagDefineId);
      }
      message.success("标签更新成功");
      setTagModalVisible(false);
      loadDetail();
    } catch (error) {
      message.error("标签更新失败");
    } finally {
      setTagLoading(false);
    }
  };

  if (loading && !detail) {
    return <Layout><div className={styles.loadingContainer}><Spin tip="加载中..." /></div></Layout>;
  }

  return (
    <Layout>
      <div className={styles.container}>
        <NavCommon title="用户详情" />

        {/* 顶部核心卡片 */}
        <div className={styles.headerCard}>
          <Avatar src={detail?.avatar || defaultAvatar} className={styles.avatar} style={{ '--size': '64px' }} />
          <div className={styles.userInfo}>
            <div className={styles.nickname}>
              {detail?.nickname || '未知用户'}
              <Tag color='warning' fill='outline' style={{ fontSize: '10px' }}>
                {LEVEL_TEXT[detail?.level] || '普通'}
              </Tag>
            </div>
            <div className={styles.tags}>
              <span className={styles.levelBadge}>{detail?.wechatAlias || detail?.wechatId || '无微信号'}</span>
              <span className={styles.levelBadge}>{detail?.region || '未知地区'}</span>
            </div>
          </div>
        </div>

        {/* 统计面板卡片 */}
        <div className={styles.card}>
          <div className={styles.sectionTitle}>
            <span><TrophyOutlined style={{ color: '#faad14', marginRight: 8 }} />互动统计</span>
            <div className={styles.titleActions}>
              <span className={styles.actionBtn} onClick={handleUpdateRfm}>
                <SyncOutlined spin={rfmLoading} /> 更新RFM
              </span>
            </div>
          </div>
          <div className={styles.statsGrid}>
            <div className={styles.statBox}>
              <span className={styles.statVal}>{detail?.totalMsgCount || 0}</span>
              <span className={styles.statLabel}>消息数</span>
            </div>
            <div className={styles.statBox}>
              <span className={styles.statVal}>{detail?.totalOrderCount || 0}</span>
              <span className={styles.statLabel}>订单数</span>
            </div>
            <div className={styles.statBox}>
              <span className={styles.statVal}>{detail?.rfmScore?.total || 0}</span>
              <span className={styles.statLabel}>RFM得分</span>
            </div>
          </div>

          {/* RFM详细得分 */}
          <div className={styles.infoGrid} style={{ marginTop: '12px', paddingTop: '12px', borderTop: '1px solid #f0f0f0' }}>
            <div className={styles.infoItem}>
              <div className={styles.label}>R-最近购买</div>
              <div className={styles.value}>{detail?.rfmScore?.R || 0}分</div>
            </div>
            <div className={styles.infoItem}>
              <div className={styles.label}>F-购买频次</div>
              <div className={styles.value}>{detail?.rfmScore?.F || 0}分</div>
            </div>
            <div className={styles.infoItem}>
              <div className={styles.label}>M-购买金额</div>
              <div className={styles.value}>{detail?.rfmScore?.M || 0}分</div>
            </div>
          </div>
        </div>

        {/* 基础信息卡片 */}
        <div className={`${styles.card} ${styles.noOverlap}`}>
          <div className={styles.sectionTitle}>
            <span><UserOutlined style={{ color: '#1677ff', marginRight: 8 }} />基础资料</span>
          </div>
          <div className={styles.infoGrid}>
            <div className={styles.infoItem}>
              <div className={styles.label}>加粉状态</div>
              <div className={styles.value}>{FRIEND_STATUS_TEXT[detail?.friendStatus] || '未知'}</div>
            </div>
            <div className={styles.infoItem}>
              <div className={styles.label}>客户周期</div>
              <div className={styles.value}>{LIFECYCLE_TEXT[detail?.lifecycle] || '新流量'}</div>
            </div>
            <div className={styles.infoItem}>
              <div className={styles.label}>意向等级</div>
              <div className={styles.value}>{INTENTION_LEVEL_TEXT[detail?.intentionLevel] || '未知'}</div>
            </div>
            <div className={styles.infoItem}>
              <div className={styles.label}>最后互动</div>
              <div className={styles.value}>{detail?.lastInteractTime ? new Date(detail.lastInteractTime * 1000).toLocaleDateString() : '从未'}</div>
            </div>
          </div>
        </div>

        {/* 标签管理卡片 */}
        <div className={styles.card}>
          <div className={styles.sectionTitle}>
            <span><TagOutlined style={{ color: '#722ed1', marginRight: 8 }} />标签画像</span>
            <div className={styles.titleActions}>
              <span className={styles.actionBtn} onClick={handleSyncTags}><SyncOutlined spin={syncLoading} /> 同步</span>
              <span className={styles.actionBtn} onClick={openTagModal}><EditOutlined /> 编辑</span>
            </div>
          </div>

          <div className={styles.tagGroups}>
            {/* 微信标签 */}
            {detail?.tags?.some((t: any) => t.tagType === 1) && (
              <div className={styles.tagGroup}>
                <div className={styles.tagGroupTitle}><CommentOutlined /> 微信标签</div>
                <div className={styles.tagsList}>
                  {detail?.tags?.filter((t: any) => t.tagType === 1).map((tag: any) => (
                    <span key={tag.id} className={styles.tagWechat}>{tag.tagName}</span>
                  ))}
                </div>
              </div>
            )}
            {/* 站内标签 */}
            <div className={styles.tagGroup}>
              <div className={styles.tagGroupTitle}><EditOutlined /> 站内标签</div>
              <div className={styles.tagsList}>
                {detail?.tags?.filter((t: any) => t.tagType === 2).length > 0 ? (
                  detail?.tags?.filter((t: any) => t.tagType === 2).map((tag: any) => (
                    <span key={tag.id} className={styles.tagSite}>{tag.tagName}</span>
                  ))
                ) : <span style={{ color: '#bfbfbf', fontSize: '12px' }}>暂无标签</span>}
              </div>
            </div>
            {/* AI标签 */}
            {detail?.tags?.some((t: any) => t.tagType === 3) && (
              <div className={styles.tagGroup}>
                <div className={styles.tagGroupTitle}><NodeIndexOutlined /> AI标签</div>
                <div className={styles.tagsList}>
                  {detail?.tags?.filter((t: any) => t.tagType === 3).map((tag: any) => (
                    <span key={tag.id} className={styles.tagAi}>{tag.tagName}</span>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* 行为轨迹卡片 */}
        <div className={styles.card}>
          <div className={styles.sectionTitle}>
            <span><HistoryOutlined style={{ color: '#eb2f96', marginRight: 8 }} />行为轨迹</span>
          </div>
          <div className={styles.searchWrapper}>
            <SearchBar
              placeholder="搜索行为..."
              value={behaviorsSearchInput}
              onChange={handleBehaviorsSearchChange}
              onClear={() => {
                setBehaviorsSearchInput("");
                setBehaviorsKeyword("");
                setBehaviorsPage(1);
              }}
            />
          </div>
          <div className={styles.journeyList}>
            {allBehaviors.length > 0 ? (
              allBehaviors.map((b, index) => (
                <div key={index} className={styles.journeyItem}>
                  <div className={styles.journeyHeader}>
                    <span className={styles.jTitle}>{b.behaviorName}</span>
                    <span className={styles.jTime}><ClockCircleOutlined /> {b.behaviorTimeFormatted || '刚刚'}</span>
                  </div>
                  <div className={styles.jContent}>{b.targetName || '执行了相关操作'}</div>
                </div>
              ))
            ) : <Empty description="暂无轨迹" />}
          </div>
          {behaviorsTotal > allBehaviors.length && (
            <MobileButton
              block
              className={styles.loadMore}
              fill='none'
              color='primary'
              loading={behaviorsLoading}
              onClick={loadMoreBehaviors}
            >
              加载更多
            </MobileButton>
          )}
        </div>

        {/* 来源追溯卡片 */}
        <div className={styles.card}>
          <div className={styles.sectionTitle}>
            <span><ShareAltOutlined style={{ color: '#2f54eb', marginRight: 8 }} />来源追溯</span>
          </div>
          <div className={styles.searchWrapper}>
            <SearchBar
              placeholder="搜索来源..."
              value={sourcesSearchInput}
              onChange={handleSourcesSearchChange}
              onClear={() => {
                setSourcesSearchInput("");
                setSourcesKeyword("");
                setSourcesPage(1);
              }}
            />
          </div>
          <div className={styles.journeyList}>
            {allSources.length > 0 ? (
              allSources.map((s, index) => (
                <div key={index} className={styles.journeyItem}>
                  <div className={styles.journeyHeader}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      {s.sourceType === 2 && s.chatroomInfo?.chatroomAvatar ? (
                        <Avatar src={s.chatroomInfo.chatroomAvatar} style={{ '--size': '24px', borderRadius: '4px' }} />
                      ) : (s.sourceType === 1 && s.sourceAvatar ? (
                        <Avatar src={s.sourceAvatar} style={{ '--size': '24px', borderRadius: '50%' }} />
                      ) : (
                        <div className={styles.sourceIconText}>{SOURCE_TYPE_TEXT[s.sourceType]?.charAt(0)}</div>
                      ))}
                      <span className={styles.jTitle}>{SOURCE_TYPE_TEXT[s.sourceType]}</span>
                    </div>
                    <span className={styles.jTime}>{s.createTimeFormatted}</span>
                  </div>
                  <div className={styles.jContent}>
                    {s.sourceType === 2 ? (
                      <div>
                        <div>群聊：{s.chatroomInfo?.chatroomName}</div>
                        {s.chatroomOwners && s.chatroomOwners.length > 0 && (
                          <div className={styles.ownerList}>
                            <span className={styles.ownerLabel}>归属：</span>
                            {s.chatroomOwners.map((owner: any, idx: number) => (
                              <div key={idx} className={styles.ownerItem}>
                                <Avatar src={owner.ownerAvatar || defaultAvatar} style={{ '--size': '16px', borderRadius: '50%' }} />
                                <span>{owner.ownerNickname}</span>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    ) : (
                      s.sourceName
                    )}
                    {s.displayId && <div style={{ fontSize: '11px', color: '#bfbfbf', marginTop: '4px' }}>ID: {s.displayId}</div>}
                  </div>
                </div>
              ))
            ) : <Empty description="暂无来源" />}
          </div>
          {sourcesTotal > allSources.length && (
            <MobileButton
              block
              className={styles.loadMore}
              fill='none'
              color='primary'
              loading={sourcesLoading}
              onClick={loadMoreSources}
            >
              加载更多
            </MobileButton>
          )}
        </div>

        {/* 标签编辑弹窗 */}
        <Popup
          visible={tagModalVisible}
          onMaskClick={() => setTagModalVisible(false)}
          bodyStyle={{ borderTopLeftRadius: '16px', borderTopRightRadius: '16px', minHeight: '40vh' }}
        >
          <div style={{ padding: '20px' }}>
            <div className={styles.sectionTitle}>编辑站内标签</div>
            {tagLoading ? <Spin /> : (
              <CheckList
                multiple
                value={selectedTagIds}
                onChange={(val) => setSelectedTagIds(val as number[])}
              >
                {tagDefines.map(item => (
                  <CheckList.Item key={item.id} value={item.id}>{item.tagName}</CheckList.Item>
                ))}
              </CheckList>
            )}
            <MobileButton
              block
              color='primary'
              style={{ marginTop: '20px' }}
              loading={tagLoading}
              onClick={saveTagChanges}
            >
              完成
            </MobileButton>
          </div>
        </Popup>
      </div>
    </Layout>
  );
};

export default TrafficPoolDetail;
