import { useState } from 'react';
import Modal from '../components/Modal';
import Button from '../components/Button';
import Filter from '../components/Filter';
import Icon from '../components/Icon';
import Input from '../components/Input';
import Table from '../components/Table';
import Tag from '../components/Tag';
import { PAGE_FRAME_CONTENT_MARGIN, PageHeader, WHITE_CARD_STYLE, useListInitialLoading } from './pageListShared';

/**
 * StrategyListPage — 策略管理列表页（页面示例0）
 *
 * 对应 Figma：OLA3.0 / node 14729:119273
 * 结构：顶部筛选栏 + Table 卡片型表单（父行 + 版本子行） + 底部分页
 */

const STATUS_VARIANT = {
  '线上生效': 'green',
  '暂未生效': 'grey',
  '草稿中':   'grey',
  '实验中':   'blue',
  '已发布':   'green',
  '已下线':   'grey',
};

export const STRATEGY_CARD_TABLE_MOCK = [
  {
    id: 'experience-1',
    title: '抖音社区-私信进线路由策略',
    status: '线上生效',
    subtitle: '识别私信意图并完成好友关系、违规咨询、账号服务分流',
    quoteCount: '99+',
    channels: '智能客服、人工坐席',
    description: '面向抖音社区私信进线的核心路由策略，覆盖陌生人消息、互关会话与高频骚扰识别。',
    category: '私信进线',
    updatedAt: '2026-04-21 10:30',
    versions: [
      { v: 4, title: '优化情绪升级转人工闸门', status: '草稿中', completion: '96%', execCount: 128, satisfaction: '94%', humanRate: '8%' },
      { v: 3, title: '新增非互关首条私信引导', status: '实验中', completion: '93%', execCount: 276, satisfaction: '91%', humanRate: '11%' },
      { v: 2, title: '更新好友关系异常分流', status: '已发布', completion: '98%', execCount: 512, satisfaction: '95%', humanRate: '7%' },
    ],
  },
  {
    id: 'experience-2',
    title: '抖音社区-好友关系异常咨询',
    status: '实验中',
    subtitle: '被拉黑、取关、互关状态变更的标准处置流程',
    quoteCount: '42',
    channels: '在线客服、服务工单',
    description: '处理用户关于好友关系异常的私信咨询，提供状态说明、规则解释与申诉入口引导。',
    category: '好友关系',
    updatedAt: '2026-04-20 18:45',
    versions: [
      { v: 2, title: '补充互关状态变更说明', status: '草稿中', completion: '88%', execCount: 74, satisfaction: '89%', humanRate: '15%' },
      { v: 1, title: '上线被拉黑拦截话术', status: '已发布', completion: '92%', execCount: 188, satisfaction: '90%', humanRate: '13%' },
    ],
  },
  {
    id: 'experience-3',
    title: '抖音社区-违规处罚解释策略',
    status: '线上生效',
    subtitle: '账号封禁、作品下架、直播中断的原因说明与申诉引导',
    quoteCount: '76',
    channels: '智能客服、人工坐席',
    description: '面向社区违规相关私信咨询，提供合规口径解释、规则链接与申诉材料清单。',
    category: '违规咨询',
    updatedAt: '2026-04-19 14:12',
    versions: [
      { v: 3, title: '更新封禁原因解释口径', status: '已发布', completion: '97%', execCount: 342, satisfaction: '93%', humanRate: '9%' },
      { v: 2, title: '增加申诉材料提示', status: '实验中', completion: '90%', execCount: 126, satisfaction: '88%', humanRate: '16%' },
      { v: 1, title: '补充直播中断处置说明', status: '已下线', completion: '84%', execCount: 61, satisfaction: '82%', humanRate: '21%' },
    ],
  },
  {
    id: 'experience-4',
    title: '抖音社区-私信拉黑举报处理',
    status: '线上生效',
    subtitle: '骚扰私信受理、证据收集与处置进度同步',
    quoteCount: '58',
    channels: '在线客服、审核工单',
    description: '用于私信骚扰与拉黑举报场景的自动受理，支持风险分级与处置结果回执。',
    category: '拉黑举报',
    updatedAt: '2026-04-18 09:20',
    versions: [
      { v: 2, title: '优化高危骚扰分级', status: '已发布', completion: '95%', execCount: 238, satisfaction: '92%', humanRate: '12%' },
      { v: 1, title: '补充举报证据采集', status: '实验中', completion: '89%', execCount: 105, satisfaction: '87%', humanRate: '18%' },
    ],
  },
  {
    id: 'experience-5',
    title: '抖音社区-陌生人消息管控',
    status: '草稿中',
    subtitle: '非互关私信频控、风险提示与引导关注',
    quoteCount: '18',
    channels: '智能客服、策略引擎',
    description: '面向陌生人私信场景，控制骚扰风险并提供合规的首次触达引导与频控说明。',
    category: '消息管控',
    updatedAt: '2026-04-17 16:05',
    versions: [
      { v: 2, title: '新增频控触发说明节点', status: '草稿中', completion: '78%', execCount: 42, satisfaction: '85%', humanRate: '19%' },
      { v: 1, title: '搭建非互关首触达流程', status: '已发布', completion: '91%', execCount: 214, satisfaction: '90%', humanRate: '14%' },
    ],
  },
];

const MOCK_STRATEGIES = STRATEGY_CARD_TABLE_MOCK;

export const STRATEGY_FILTERS = [
  {
    label: '管理员',
    options: ['林小北', '陈一诺', '周知远', '顾清禾'],
  },
  {
    label: '发布状态',
    options: ['线上生效', '实验中', '暂未生效', '草稿中', '已发布'],
  },
  {
    label: '策略类型',
    options: ['私信进线', '好友关系', '违规咨询', '拉黑举报', '消息管控'],
  },
];

export default function StrategyListPage({ embedded = false, shellless = false, initialLoading } = {}) {
  const autoLoading = useListInitialLoading();
  const loading = initialLoading === false ? false : autoLoading;
  const [expandedId, setExpandedId] = useState('experience-1');
  const [fullModalOpen, setFullModalOpen] = useState(false);

  // embedded：嵌入灰底 / 双栏容器，去掉 BasePageFrame 外边距
  // shellless：嵌入 CopilotArtifactDetailPanel 正文槽，不再套第二层白卡壳
  const frameStyle = shellless
    ? undefined
    : embedded
      ? { ...WHITE_CARD_STYLE, width: '100%' }
      : { margin: PAGE_FRAME_CONTENT_MARGIN, ...WHITE_CARD_STYLE };

  const rootClassName = shellless
    ? 'tfds-page-strategy-list flex min-h-0 min-w-0 w-full flex-1 flex-col overflow-hidden'
    : embedded
      ? 'tfds-page-strategy-list flex w-full min-w-0 flex-col overflow-hidden'
      : 'tfds-page-strategy-list flex flex-1 min-h-0 min-w-0 flex-col overflow-hidden';

  return (
    <div
      className={rootClassName}
      style={frameStyle}
    >
      <div
        className="flex flex-1 min-h-0 min-w-0 flex-col"
        style={{ padding: shellless ? '16px 24px 24px' : '24px', gap: '16px' }}
      >
        {fullModalOpen && (
          <div
            className="absolute inset-0 z-50 flex flex-col bg-overlay"
            style={{ borderRadius: '12px' }}
          >
            <Modal
              layout="fullscreen"
              className="mt-auto"
              title="新建策略"
              subtitle={null}
              showFooterHint={false}
              confirmText="创建"
              cancelText="取消"
              onClose={() => setFullModalOpen(false)}
              onCancel={() => setFullModalOpen(false)}
              onConfirm={() => setFullModalOpen(false)}
            >
              <div className="flex flex-1 min-h-0" />
            </Modal>
          </div>
        )}

        <PageHeader
          title="策略管理"
          actions={
            <Button
              variant={shellless ? 'outline-black' : 'primary'}
              icon={<Icon name="plus-stroked" />}
              onClick={() => setFullModalOpen(true)}
            >
              新建策略
            </Button>
          }
        />

        <StrategyFilterBar filters={STRATEGY_FILTERS} />

        <Table
          variant="card-form"
          className="min-h-0 flex-1"
          dataSource={MOCK_STRATEGIES}
          loading={loading}
          rowKey="id"
          expandedRowKeys={expandedId ? [expandedId] : []}
          onExpandedRowKeysChange={(keys) => setExpandedId(keys[keys.length - 1] || null)}
          pagination={{
            current: 1,
            pageSize: 20,
            total: MOCK_STRATEGIES.length,
            pageSizeOptions: [10, 20],
          }}
        />
      </div>
    </div>
  );
}

export function StrategyCard({ strategy, expanded = false, onToggle }) {
  const { title, status, subtitle, versions = [] } = strategy;
  return (
    <div className="rounded-lg border border-border-default bg-white">
      <div
        className="flex cursor-pointer items-center gap-3 px-4 py-3"
        onClick={onToggle}
        role="button"
        tabIndex={0}
        onKeyDown={(e) => e.key === 'Enter' && onToggle?.()}
      >
        <div className="flex min-w-0 flex-1 flex-col gap-0.5">
          <div className="flex items-center gap-2">
            <span className="truncate text-sm font-medium text-blueGrey-900">{title}</span>
            <Tag variant={STATUS_VARIANT[status] ?? 'grey'} size="s">{status}</Tag>
          </div>
          {subtitle && <span className="text-xs text-blueGrey-500">{subtitle}</span>}
        </div>
        <Icon
          name={expanded ? 'chevron-up-stroked' : 'chevron-down-stroked'}
          className="h-4 w-4 shrink-0 text-blueGrey-400"
        />
      </div>
      {expanded && versions.length > 0 && (
        <div className="border-t border-border-default">
          {versions.map((ver) => (
            <div key={ver.v} className="flex items-center gap-3 px-4 py-2.5 text-xs text-blueGrey-600 even:bg-fill">
              <span className="shrink-0 font-medium">v{ver.v}</span>
              <span className="min-w-0 flex-1 truncate">{ver.title}</span>
              <Tag variant={STATUS_VARIANT[ver.status] ?? 'grey'} size="s">{ver.status}</Tag>
              <span className="shrink-0 tabular-nums">{ver.execCount} 执行</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export function TablePagination({ total = 0, pageSize = 20, current = 1, onChange }) {
  const totalPages = Math.ceil(total / pageSize);
  return (
    <div className="flex shrink-0 items-center justify-between gap-2 text-xs text-blueGrey-500">
      <span>共 {total} 条</span>
      <div className="flex items-center gap-1">
        <button
          className="flex h-7 w-7 items-center justify-center rounded hover:bg-fill disabled:opacity-40"
          disabled={current <= 1}
          onClick={() => onChange?.(current - 1)}
        >
          <Icon name="chevron-left-stroked" className="h-4 w-4" />
        </button>
        <span className="px-2">
          {current} / {totalPages}
        </span>
        <button
          className="flex h-7 w-7 items-center justify-center rounded hover:bg-fill disabled:opacity-40"
          disabled={current >= totalPages}
          onClick={() => onChange?.(current + 1)}
        >
          <Icon name="chevron-right-stroked" className="h-4 w-4" />
        </button>
      </div>
    </div>
  );
}

export function StrategyFilterBar({ filters = [] }) {
  return (
    <div className="flex shrink-0 flex-wrap items-center gap-2">
      <Input
        placeholder="搜索"
        prefix={<Icon name="search-md-stroked" />}
        className="shrink-0"
        style={{ flex: '0 0 240px', '--size-input-width': '240px' }}
      />

      {filters.map((item) => (
        <Filter key={item.label} {...item} />
      ))}
    </div>
  );
}
