import { useCallback, useState } from 'react';
import NavBar from '../components/NavBar';
import Tabs from '../components/Tabs';
import ChatInput from '../components/ChatInput';
import Card from '../components/Card';
import Input from '../components/Input';
import Icon from '../components/Icon';
import ChatConversationPattern from './ChatConversationPattern';
import { buildChatHomeConversationHandoff } from '../page-flows/chat-home-conversation-flow';
import {
  CHAT_DEMO_FEATURED_TEMPLATE_TITLE,
  CHAT_DEMO_PLATFORM_NAME,
} from '../page-flows/chat-conversation-demo';

/**
 * ChatHomePagePattern — Chat 类产品首页模板
 *
 * 右侧内容区从上到下：
 *   1. Hero 区：大标题 + 副标题 + 居中 ChatInput
 *   2. 筛选行（左胶囊 Tab + 右固定宽 Search），左右 40px 边距
 *   3. 自适应卡片网格（auto-fill minmax(260px,1fr)），左右 40px 边距
 */

/* ── 筛选 Tab ── */
const FILTER_TABS = [
  { label: '全部', id: 'all' },
  { label: '基础分析', id: '基础分析' },
  { label: '链路分析', id: '链路分析' },
  { label: '数据完善', id: '数据完善' },
];

const FILTER_SEARCH_WRAP_STYLE = {
  flex: '0 0 240px',
  width: '240px',
  minWidth: '240px',
  maxWidth: '240px',
};

/* ── 示例卡片数据（20 张，category 对应 Tab id）── */
const MOCK_CARDS = [
  {
    category: '基础分析',
    title: CHAT_DEMO_FEATURED_TEMPLATE_TITLE,
    description: '针对指定业务场景下智能服务核心指标、运行路径、渠道等进行趋势分析，并输出总结报告',
    tags: ['基础分析', '官方'],
    stats: [{ iconName: 'users-01-stroked', value: '1,289' }, { iconName: 'message-chat-square-stroked', value: '1,289' }, { iconName: 'hearts-stroked', value: '276' }],
  },
  {
    category: '基础分析',
    title: '渠道来源分布报告',
    description: '统计各渠道用户来源占比与活跃度，输出结构化渠道分布分析报告',
    tags: ['基础分析'],
    stats: [{ iconName: 'users-01-stroked', value: '987' }, { iconName: 'message-chat-square-stroked', value: '3,410' }, { iconName: 'hearts-stroked', value: '198' }],
  },
  {
    category: '基础分析',
    title: '用户满意度周报',
    description: '汇聚 NPS 评分与用户反馈关键词，自动生成满意度周报并标注波动原因',
    tags: ['基础分析', '官方'],
    stats: [{ iconName: 'users-01-stroked', value: '2,341' }, { iconName: 'message-chat-square-stroked', value: '7,890' }, { iconName: 'hearts-stroked', value: '512' }],
  },
  {
    category: '基础分析',
    title: '高频问题分类汇总',
    description: '对用户提问进行语义聚类，输出 Top 问题类别及占比，辅助运营决策',
    tags: ['基础分析'],
    stats: [{ iconName: 'users-01-stroked', value: '1,654' }, { iconName: 'message-chat-square-stroked', value: '5,230' }, { iconName: 'hearts-stroked', value: '341' }],
  },
  {
    category: '基础分析',
    title: '会话量环比分析',
    description: '对比本周期与上周期会话量变化，自动识别波峰波谷并给出可能归因',
    tags: ['基础分析'],
    stats: [{ iconName: 'users-01-stroked', value: '876' }, { iconName: 'message-chat-square-stroked', value: '2,100' }, { iconName: 'hearts-stroked', value: '143' }],
  },
  {
    category: '基础分析',
    title: '机器人接待率分析',
    description: '统计机器人独立解决率与转人工率，分析接待效率并提出优化建议',
    tags: ['基础分析', '官方'],
    stats: [{ iconName: 'users-01-stroked', value: '3,102' }, { iconName: 'message-chat-square-stroked', value: '9,870' }, { iconName: 'hearts-stroked', value: '678' }],
  },
  {
    category: '链路分析',
    title: '服务全链路复盘',
    description: '复盘指定会话的封闭答案错误链路，着重分析价值量服务结果，并输出复盘报告',
    tags: ['链路分析', '官方'],
    stats: [{ iconName: 'users-01-stroked', value: '1,289' }, { iconName: 'message-chat-square-stroked', value: '1,289' }, { iconName: 'hearts-stroked', value: '276' }],
  },
  {
    category: '链路分析',
    title: '产品深度对比分析报告',
    description: '针对指定产品进行全面的理解和战略策略，产生一份深入的对比分析报告',
    tags: ['链路分析'],
    stats: [{ iconName: 'users-01-stroked', value: '1,289' }, { iconName: 'message-chat-square-stroked', value: '1,289' }, { iconName: 'hearts-stroked', value: '275' }],
  },
  {
    category: '链路分析',
    title: '转人工节点溯源',
    description: '识别用户从机器人流转至人工的触发节点，分析转接原因分布并给出优化路径',
    tags: ['链路分析'],
    stats: [{ iconName: 'users-01-stroked', value: '743' }, { iconName: 'message-chat-square-stroked', value: '2,567' }, { iconName: 'hearts-stroked', value: '189' }],
  },
  {
    category: '链路分析',
    title: '对话意图识别偏差分析',
    description: '检测意图识别命中率偏低的节点，输出误判 TopN 并关联用户原话样本',
    tags: ['链路分析', '官方'],
    stats: [{ iconName: 'users-01-stroked', value: '1,102' }, { iconName: 'message-chat-square-stroked', value: '4,320' }, { iconName: 'hearts-stroked', value: '267' }],
  },
  {
    category: '链路分析',
    title: '流失节点热力图',
    description: '可视化用户在对话链路中的退出热点，标记高流失步骤并输出改进建议',
    tags: ['链路分析'],
    stats: [{ iconName: 'users-01-stroked', value: '892' }, { iconName: 'message-chat-square-stroked', value: '3,140' }, { iconName: 'hearts-stroked', value: '221' }],
  },
  {
    category: '链路分析',
    title: '多轮对话路径聚合',
    description: '聚合相似多轮对话路径，识别主干流程与长尾异常路径，辅助流程优化',
    tags: ['链路分析'],
    stats: [{ iconName: 'users-01-stroked', value: '654' }, { iconName: 'message-chat-square-stroked', value: '1,980' }, { iconName: 'hearts-stroked', value: '134' }],
  },
  {
    category: '链路分析',
    title: '跨渠道链路对比',
    description: '横向对比 Web、App、小程序等渠道的用户对话路径差异，输出渠道策略建议',
    tags: ['链路分析'],
    stats: [{ iconName: 'users-01-stroked', value: '1,432' }, { iconName: 'message-chat-square-stroked', value: '5,670' }, { iconName: 'hearts-stroked', value: '389' }],
  },
  {
    category: '数据完善',
    title: '未命中问题标注助手',
    description: '对未命中知识库的用户提问进行批量标注与分类，输出待补充知识点清单',
    tags: ['数据完善', '官方'],
    stats: [{ iconName: 'users-01-stroked', value: '2,150' }, { iconName: 'message-chat-square-stroked', value: '8,760' }, { iconName: 'hearts-stroked', value: '567' }],
  },
  {
    category: '数据完善',
    title: '知识库覆盖率评估',
    description: '统计业务问题被知识库覆盖的比例，识别空白领域并生成补全优先级建议',
    tags: ['数据完善'],
    stats: [{ iconName: 'users-01-stroked', value: '1,876' }, { iconName: 'message-chat-square-stroked', value: '6,340' }, { iconName: 'hearts-stroked', value: '432' }],
  },
  {
    category: '数据完善',
    title: '相似问法聚合归并',
    description: '识别表达不同但语义相近的用户问法，推荐合并为标准问并扩展同义词库',
    tags: ['数据完善', '官方'],
    stats: [{ iconName: 'users-01-stroked', value: '1,234' }, { iconName: 'message-chat-square-stroked', value: '4,890' }, { iconName: 'hearts-stroked', value: '312' }],
  },
  {
    category: '数据完善',
    title: '答案质量评分报告',
    description: '对知识库现有答案进行可读性、准确性和完整性评分，输出低分条目改写建议',
    tags: ['数据完善'],
    stats: [{ iconName: 'users-01-stroked', value: '987' }, { iconName: 'message-chat-square-stroked', value: '3,210' }, { iconName: 'hearts-stroked', value: '198' }],
  },
  {
    category: '数据完善',
    title: '过期内容检测清理',
    description: '扫描知识库中含有过期日期、已下线产品的条目，生成待更新清单并辅助批量修订',
    tags: ['数据完善'],
    stats: [{ iconName: 'users-01-stroked', value: '654' }, { iconName: 'message-chat-square-stroked', value: '2,340' }, { iconName: 'hearts-stroked', value: '145' }],
  },
  {
    category: '数据完善',
    title: '多语言内容对齐检查',
    description: '对比中英文知识库条目的语义一致性，标记翻译偏差并输出修订优先级',
    tags: ['数据完善'],
    stats: [{ iconName: 'users-01-stroked', value: '432' }, { iconName: 'message-chat-square-stroked', value: '1,560' }, { iconName: 'hearts-stroked', value: '98' }],
  },
  {
    category: '数据完善',
    title: '冷热知识分布分析',
    description: '按调用频次区分高频热点知识与长尾冷门知识，辅助知识库瘦身与重点维护',
    tags: ['数据完善', '官方'],
    stats: [{ iconName: 'users-01-stroked', value: '1,109' }, { iconName: 'message-chat-square-stroked', value: '4,120' }, { iconName: 'hearts-stroked', value: '278' }],
  },
];

export default function ChatHomePagePattern({
  /** 预览 / 演示：Hero 发送或点模板卡后，内部切换到 ChatConversationPattern */
  enableConversationHandoff = true,
  /** 业务路由：接收 handoff payload 后自行 navigate；与 enableConversationHandoff 可并存 */
  onEnterConversation,
  platformName = CHAT_DEMO_PLATFORM_NAME,
}) {
  const [selectedItemId, setSelectedItemId] = useState('ai');
  const [searchValue, setSearchValue] = useState('');
  const [activeTabIndex, setActiveTabIndex] = useState(0);
  const [conversationHandoff, setConversationHandoff] = useState(null);

  const startConversationFromHome = useCallback((text, ctx = {}) => {
    const trimmed = String(text || '').trim();
    if (!trimmed) return;

    const handoff = buildChatHomeConversationHandoff({
      text: trimmed,
      ctx: {
        ...ctx,
        source: ctx.source || 'chat-home-hero-send',
      },
      platformName,
    });

    onEnterConversation?.(handoff);
    if (enableConversationHandoff) {
      setConversationHandoff(handoff);
    }
  }, [enableConversationHandoff, onEnterConversation, platformName]);

  if (conversationHandoff) {
    return (
      <ChatConversationPattern
        title={conversationHandoff.title}
        platformName={conversationHandoff.platformName}
        assistantName={conversationHandoff.platformName}
        bootstrapSendSignal={conversationHandoff.bootstrapSendSignal}
        onBackToHome={() => setConversationHandoff(null)}
      />
    );
  }

  const activeCategory = FILTER_TABS[activeTabIndex]?.id ?? 'all';
  const filteredCards = MOCK_CARDS.filter((card) => {
    const matchCategory = activeCategory === 'all' || card.category === activeCategory;
    const matchSearch = !searchValue || card.title.includes(searchValue) || card.description.includes(searchValue);
    return matchCategory && matchSearch;
  });

  return (
    <div
      className="tfds-page-chat-home flex h-full min-h-0 min-w-0 w-full items-stretch overflow-hidden"
      style={{
        background: 'var(--color-blueGrey-200, #F2F4F7)',
        borderRadius: 0,
      }}
    >
      {/* 左侧 NavBar：单项，仅显示 AI */}
      <div className="flex shrink-0">
        <NavBar
          platform="ola"
          navItems={[{ id: 'ai', label: 'AI', iconName: 'bot-02-stroked' }]}
          selectedItemId={selectedItemId}
          onSelect={(nextKey) => setSelectedItemId(nextKey)}
        />
      </div>

      {/* 右侧内容区：整体滚动，Hero / 筛选 / 卡片一起滑动 */}
      <div className="flex flex-1 min-w-0 flex-col min-h-0 overflow-y-auto overflow-x-hidden">

        {/* ① Hero 区 */}
        <div
          className="flex flex-col items-center shrink-0"
          style={{ padding: '84px 40px 80px' }}
        >
          <h1
            className="m-0 text-center text-4xl [font-weight:var(--font-semibold)] leading-10"
            style={{
              color: 'var(--foreground, #0F1C35)',
              marginBottom: '6px',
            }}
          >
            今天想做什么？
          </h1>

          <p
            className="m-0 text-sm text-center"
            style={{
              color: 'var(--foreground-muted, rgba(15,28,53,0.45))',
              marginBottom: '48px',
            }}
          >
            直接描述你的需求，或从下方模板快速开始
          </p>

          <div className="w-full" style={{ maxWidth: '680px' }}>
            <ChatInput
              variant="default"
              placeholder="描述你想完成的任务…"
              onSend={startConversationFromHome}
            />
          </div>
        </div>

        {/* ② 筛选行：左侧胶囊 Tab + 右侧固定宽搜索，左右 40px */}
        <div
          className="flex min-w-0 shrink-0 items-center gap-4"
          style={{ padding: '16px 40px' }}
        >
          <div className="flex shrink-0">
            <Tabs
              variant="pill"
              size="sm"
              items={FILTER_TABS}
              defaultIndex={0}
              onChange={(index) => setActiveTabIndex(index)}
            />
          </div>
          <div className="ml-auto shrink-0" style={FILTER_SEARCH_WRAP_STYLE}>
            <Input
              placeholder="搜索标题、描述"
              prefix={<Icon name="search-md-stroked" size="sm" />}
              allowClear
              value={searchValue}
              onChange={(e) => setSearchValue(e.target.value)}
            />
          </div>
        </div>

        {/* ③ 卡片网格（当前直接坐浅灰页面底，所以统一使用白底 Card 做内容承载） */}
        <div
          className="shrink-0"
          style={{ padding: '0 40px 32px' }}
        >
          <div
            className="grid gap-4"
            style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(min(320px, 100%), 1fr))' }}
          >
            {filteredCards.map((card, index) => (
              <Card
                key={`${activeCategory}-${index}`}
                title={card.title}
                description={card.description}
                tags={card.tags}
                stats={card.stats}
                color="white"
                onAction={() => startConversationFromHome(card.title, {
                  source: 'chat-home-template-card',
                  templateTitle: card.title,
                })}
                actionAriaLabel={`使用模板：${card.title}`}
              />
            ))}
          </div>
        </div>

      </div>
    </div>
  );
}
