import { useState, useEffect, useMemo, useCallback } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { StatCard } from '@/components/shared/StatCard';
import { Progress } from '@/components/ui/progress';
import {
  Plus, Trash2, ArrowUp, ArrowDown, Pencil, Eye, Play, Square,
  ListChecks, Loader2, CheckCircle2, XCircle, AlertTriangle, Clock, Send
} from 'lucide-react';
import { defaultFunnelConfig } from '@/mocks/mockSmartInquiry';
import { fetchInquiryBatchOptions, fetchInquiryTasks, type InquiryBatchOption } from '@/services/inquiryService';
import { fetchAccounts } from '@/services/accountService';
import { fetchInquiryStatuses, stopInquiryBatch, triggerInquiryBatch, type InquiryProgress } from '@/services/automationService';
import { useAuth } from '@/hooks/useAuth';
import { useProcurementBatchOptions } from '@/hooks/useProcurementBatchOptions';
import type { InquiryRoundConfig, InquiryFunnelConfig, InquiryTask, InquiryTaskStatus, ChatMessage, ProcurementAccount1688 } from '@/types';
import { formatDate } from '@/lib/dateUtils';
import { toast } from 'sonner';

// ── Constants ────────────────────────────────────────────

const STORAGE_KEY = 'smart-inquiry-funnel-config';
const MAX_INQUIRY_ROUNDS = 100;
const DEFAULT_ROUND_TEMPLATES = defaultFunnelConfig.rounds;
const LEGACY_TEMPLATE_VARIABLE_MIGRATIONS: Record<string, string> = {
  商品标题: '标准化名称',
  title: '标准化名称',
  物料名称: '原始名称',
  material_name: '原始名称',
  规格型号: '原始规格',
  specification: '原始规格',
  数量: '数量',
  quantity: '数量',
  单位: '单位',
  unit: '单位',
  品牌: '品牌',
  brand: '品牌',
  技术标准: '备注',
  technical_standard: '备注',
  物料要求: '备注',
  material_requirement: '备注',
};

const LEGACY_DEFAULT_ROUND_MIGRATIONS = [
  {
    templateText: '老板，请问【商品标题】目前有现货吗？',
    passCondition: '商家确认有现货或可调货',
    replacement: DEFAULT_ROUND_TEMPLATES[0],
  },
  {
    templateText: '我们需要【规格型号】，起订量【数量】【单位】能做吗？',
    passCondition: '商家确认可满足规格和起订量要求',
    replacement: DEFAULT_ROUND_TEMPLATES[1],
  },
  {
    templateText: '如果按照这个数量采购【品牌】的，最低什么价格？交期大概要多久？',
    passCondition: '商家给出明确报价和交期',
    replacement: DEFAULT_ROUND_TEMPLATES[2],
  },
  {
    templateText: '产品符合【技术标准】吗？能开增值税专用发票吗？',
    passCondition: '商家确认符合标准且可开增值税专用发票',
    replacement: DEFAULT_ROUND_TEMPLATES[3],
  },
];

const AVAILABLE_VARIABLES = [
  { name: '标准化名称', desc: '标准化名称 (standardized_results.standardized_name)' },
  { name: '原始名称', desc: '原始名称 (standardized_results.original_name)' },
  { name: '标准化规格', desc: '标准化规格 (standardized_results.standardized_spec)' },
  { name: '原始规格', desc: '原始规格 (standardized_results.original_spec)' },
  { name: '数量', desc: '数量 (standardized_results.quantity)' },
  { name: '单位', desc: '单位 (standardized_results.standardized_unit)' },
  { name: '品牌', desc: '品牌 (standardized_results.brand)' },
  { name: '分类', desc: '分类 (standardized_results.category)' },
  { name: '主搜索词', desc: '主搜索词 (standardized_results.primary_search_term)' },
  { name: '备选搜索词', desc: '备选搜索词 (standardized_results.alt_search_terms)' },
  { name: '备注', desc: '备注 (standardized_results.notes)' },
  { name: '收货地址', desc: '收货地址 (standardized_results.delivery_address)' },
  { name: '发票种类', desc: '发票种类 (standardized_results.invoice_type)' },
  { name: '产品类型', desc: '产品类型 (standardized_results.product_type)' },
];

const ASK_CONTEXT_LABELS: Record<string, string> = {
  standardized_name: '标准化名称',
  original_name: '原始名称',
  standardized_spec: '标准化规格',
  original_spec: '原始规格',
  quantity: '数量',
  standardized_unit: '单位',
  brand: '品牌',
  category: '分类',
  primary_search_term: '主搜索词',
  alt_search_terms: '备选搜索词',
  notes: '备注',
  delivery_address: '收货地址',
  invoice_type: '发票种类',
  product_type: '产品类型',
  source_type: '来源类型',
  title: '商品标题',
  material_name: '物料名称',
  specification: '规格型号',
  unit: '单位',
  technical_standard: '技术标准',
  material_requirement: '物料要求',
};

const PASSED_STATUS_CLASS_NAME = 'bg-emerald-100 text-emerald-700 border-emerald-200';

const STATUS_CONFIG: Record<string, { label: string; className: string }> = {
  PENDING_SEND:     { label: '待发送',     className: 'bg-slate-100 text-slate-700 border-slate-200' },
  WAITING_REPLY:    { label: '等待回复',   className: 'bg-blue-100 text-blue-700 border-blue-200' },
  COMPLETED:        { label: '已完成',     className: 'bg-green-100 text-green-800 border-green-300' },
  REJECTED:         { label: '已拒绝',     className: 'bg-red-100 text-red-700 border-red-200' },
  TIMEOUT_REJECTED: { label: '超时',       className: 'bg-red-100 text-red-700 border-red-200' },
  HUMAN_TAKEOVER:   { label: '人工接管',   className: 'bg-amber-100 text-amber-700 border-amber-200' },
};

// ── Helpers ──────────────────────────────────────────────

function extractTemplateVariables(templateText: string) {
  const matches = templateText.match(/【([^】]+)】/g) ?? [];
  return [...new Set(matches.map((match) => match.slice(1, -1)).filter(Boolean))];
}

function migrateLegacyTemplateVariables(text: string) {
  if (!text.trim()) {
    return text;
  }

  return text.replace(/【([^】]+)】/g, (matched, variableName) => {
    const replacement = LEGACY_TEMPLATE_VARIABLE_MIGRATIONS[String(variableName).trim()];
    return replacement ? `【${replacement}】` : matched;
  });
}

function migrateLegacyRoundContent(templateText: string, passCondition: string) {
  const normalizedTemplateText = templateText.trim();
  const normalizedPassCondition = passCondition.trim();

  const legacyDefault = LEGACY_DEFAULT_ROUND_MIGRATIONS.find((item) => item.templateText === normalizedTemplateText);

  if (legacyDefault?.replacement) {
    return {
      templateText: legacyDefault.replacement.templateText,
      passCondition: !normalizedPassCondition || normalizedPassCondition === legacyDefault.passCondition
        ? legacyDefault.replacement.passCondition
        : migrateLegacyTemplateVariables(passCondition),
    };
  }

  return {
    templateText: migrateLegacyTemplateVariables(templateText),
    passCondition: migrateLegacyTemplateVariables(passCondition),
  };
}

function formatAskContextLabel(key: string) {
  return ASK_CONTEXT_LABELS[key] ?? key;
}

function clampLegacyActiveRoundCount(value: unknown, maxRoundCount: number) {
  const parsed = Number.parseInt(String(value ?? ''), 10);
  if (!Number.isFinite(parsed)) {
    return maxRoundCount;
  }

  return Math.max(0, Math.min(maxRoundCount, parsed));
}

function buildRoundConfig(
  index: number,
  overrides: Partial<InquiryRoundConfig> = {},
  fallbackEnabled: boolean = true,
): InquiryRoundConfig {
  const fallback = DEFAULT_ROUND_TEMPLATES[index - 1];
  const rawId = typeof overrides.id === 'string' ? overrides.id.trim() : '';
  const rawName = typeof overrides.name === 'string' ? overrides.name.trim() : '';
  const rawTemplateText = typeof overrides.templateText === 'string' ? overrides.templateText.trim() : '';
  const rawPassCondition = typeof overrides.passCondition === 'string'
    ? overrides.passCondition.trim()
    : (fallback?.passCondition ?? '');
  const migratedRoundContent = migrateLegacyRoundContent(rawTemplateText, rawPassCondition);
  const enabled = typeof overrides.enabled === 'boolean' ? overrides.enabled : fallbackEnabled;
  const templateText = migratedRoundContent.templateText || fallback?.templateText || '';
  const passCondition = migratedRoundContent.passCondition || fallback?.passCondition || '';

  return {
    id: rawId || fallback?.id || `r${index}`,
    round: index,
    name: rawName || fallback?.name || `第 ${index} 轮`,
    templateText,
    variables: extractTemplateVariables(templateText),
    passCondition,
    enabled,
  };
}

function buildDefaultFunnelConfig(): InquiryFunnelConfig {
  const rounds = DEFAULT_ROUND_TEMPLATES.map((round, index) => buildRoundConfig(index + 1, round));
  return {
    ...defaultFunnelConfig,
    rounds,
  };
}

function normalizeFunnelConfig(input: unknown): InquiryFunnelConfig {
  const fallbackConfig = buildDefaultFunnelConfig();
  if (!input || typeof input !== 'object') {
    return fallbackConfig;
  }

  const value = input as Partial<InquiryFunnelConfig> & { rounds?: unknown; activeRoundCount?: unknown };
  const explicitRounds: unknown[] | null = Array.isArray(value.rounds) ? value.rounds : null;
  const rawRounds = explicitRounds
    ? [...explicitRounds]
        .sort((left, right) => {
          const leftRound = Number((left as { round?: unknown } | null)?.round ?? 0);
          const rightRound = Number((right as { round?: unknown } | null)?.round ?? 0);
          return leftRound - rightRound;
        })
        .slice(0, MAX_INQUIRY_ROUNDS)
    : fallbackConfig.rounds;

  const legacyEnabledCount = explicitRounds
    ? clampLegacyActiveRoundCount(value.activeRoundCount, rawRounds.length)
    : rawRounds.length;

  const orderedRounds = rawRounds.map((round, index) => buildRoundConfig(
    index + 1,
    round && typeof round === 'object' ? round as Partial<InquiryRoundConfig> : {},
    index < legacyEnabledCount,
  ));

  return {
    id: typeof value.id === 'string' && value.id.trim() ? value.id.trim() : fallbackConfig.id,
    name: typeof value.name === 'string' && value.name.trim() ? value.name.trim() : fallbackConfig.name,
    rounds: orderedRounds,
    createdAt: typeof value.createdAt === 'string' && value.createdAt.trim() ? value.createdAt : fallbackConfig.createdAt,
    updatedAt: typeof value.updatedAt === 'string' && value.updatedAt.trim() ? value.updatedAt : fallbackConfig.updatedAt,
  };
}

function getEnabledRoundCount(rounds: InquiryRoundConfig[]) {
  return rounds.filter((round) => round.enabled).length;
}

function isPassedRoundStatus(status: string): status is `R${number}_PASSED` {
  return /^R\d+_PASSED$/.test(status);
}

function isInquiryTaskInProgress(status: InquiryTaskStatus) {
  return status === 'PENDING_SEND' || status === 'WAITING_REPLY' || isPassedRoundStatus(status);
}

function getStatusConfig(status: InquiryTaskStatus) {
  if (isPassedRoundStatus(status)) {
    const round = status.match(/^R(\d+)_PASSED$/)?.[1] ?? '';
    return {
      label: `R${round}通过`,
      className: PASSED_STATUS_CLASS_NAME,
    };
  }

  return STATUS_CONFIG[status] ?? STATUS_CONFIG.PENDING_SEND;
}

function loadConfig(): InquiryFunnelConfig {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) {
      const normalized = normalizeFunnelConfig(JSON.parse(raw));
      const normalizedSerialized = JSON.stringify(normalized);
      if (normalizedSerialized !== raw) {
        localStorage.setItem(STORAGE_KEY, normalizedSerialized);
      }
      return normalized;
    }
  } catch { /* ignore */ }
  return buildDefaultFunnelConfig();
}

function saveConfig(config: InquiryFunnelConfig) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(normalizeFunnelConfig(config)));
}

function getRuntimeFunnelConfig(): InquiryFunnelConfig {
  const config = loadConfig();
  const rounds = [...config.rounds]
    .sort((left, right) => left.round - right.round)
    .filter(round => round.enabled && round.templateText.trim())
    .slice(0, MAX_INQUIRY_ROUNDS)
    .map((round, index) => ({
      ...round,
      round: index + 1,
      variables: extractTemplateVariables(round.templateText),
    }));

  return {
    ...config,
    rounds,
  };
}

function makeId() {
  return `r-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
}

function TaskStatusBadge({ status }: { status: InquiryTaskStatus }) {
  const cfg = getStatusConfig(status);
  return <Badge variant="outline" className={`whitespace-nowrap ${cfg.className}`}>{cfg.label}</Badge>;
}

function ChatBubbles({ messages }: { messages: ChatMessage[] }) {
  if (!messages.length) {
    return <p className="text-sm text-muted-foreground py-8 text-center">暂无聊天记录</p>;
  }
  return (
    <div className="space-y-2.5">
      {messages.map((m, i) => (
        <div key={i} className={`flex ${m.role === 'self' ? 'justify-end' : m.role === 'system' ? 'justify-center' : 'justify-start'}`}>
          <div className={`max-w-[78%] rounded-2xl px-3.5 py-2.5 text-xs leading-6 shadow-sm ${
            m.role === 'self' ? 'bg-blue-600 text-white'
              : m.role === 'system' ? 'bg-slate-100 text-slate-500 italic'
              : 'border border-slate-200 bg-white text-slate-800'
          }`}>
            {m.content}
          </div>
        </div>
      ))}
    </div>
  );
}

// ── Round Editor Dialog ──────────────────────────────────

interface RoundEditorProps {
  open: boolean;
  round: InquiryRoundConfig | null;
  onSave: (round: InquiryRoundConfig) => void;
  onClose: () => void;
}

function RoundEditorDialog({ open, round, onSave, onClose }: RoundEditorProps) {
  const [name, setName] = useState('');
  const [templateText, setTemplateText] = useState('');
  const [passCondition, setPassCondition] = useState('');

  useEffect(() => {
    if (round) {
      setName(round.name);
      setTemplateText(round.templateText);
      setPassCondition(round.passCondition);
    } else {
      setName('');
      setTemplateText('');
      setPassCondition('');
    }
  }, [round, open]);

  const detectedVars = useMemo(() => extractTemplateVariables(templateText), [templateText]);

  const handleSave = () => {
    if (!name.trim()) { toast.error('请输入轮次名称'); return; }
    if (!templateText.trim()) { toast.error('请输入话术模板'); return; }
    onSave({
      id: round?.id ?? makeId(),
      round: round?.round ?? 0,
      name: name.trim(),
      templateText: templateText.trim(),
      variables: extractTemplateVariables(templateText.trim()),
      passCondition: passCondition.trim(),
      enabled: round?.enabled ?? true,
    });
  };

  return (
    <Dialog open={open} onOpenChange={v => { if (!v) onClose(); }}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>{round?.id ? '编辑轮次' : '添加轮次'}</DialogTitle>
        </DialogHeader>

        <div className="space-y-4 py-2">
          <div>
            <label className="text-sm font-medium">轮次名称</label>
            <Input className="mt-1" value={name} onChange={e => setName(e.target.value)} placeholder="如：货源基础摸底" />
          </div>

          <div>
            <label className="text-sm font-medium">话术模板</label>
            <Textarea className="mt-1 min-h-[100px] font-mono text-sm" value={templateText} onChange={e => setTemplateText(e.target.value)}
              placeholder="使用【变量名】插入变量，如：老板，请问【标准化名称】目前有现货吗？" />
            <p className="mt-1 text-xs text-muted-foreground">
              使用 <code className="bg-muted px-1 rounded">【变量名】</code> 语法插入动态字段
            </p>
          </div>

          {/* Variable reference */}
          <div>
            <label className="text-sm font-medium">可用变量</label>
            <div className="mt-1.5 flex flex-wrap gap-1.5">
              {AVAILABLE_VARIABLES.map(v => (
                <Tooltip key={v.name}>
                  <TooltipTrigger asChild>
                    <button type="button"
                      className="inline-flex items-center rounded-md border bg-muted/50 px-2 py-0.5 text-xs text-muted-foreground hover:bg-muted transition-colors cursor-pointer"
                      onClick={() => setTemplateText(prev => prev + `【${v.name}】`)}>
                      {v.name}
                    </button>
                  </TooltipTrigger>
                  <TooltipContent>{v.desc}</TooltipContent>
                </Tooltip>
              ))}
            </div>
          </div>

          {detectedVars.length > 0 && (
            <div>
              <label className="text-sm font-medium">已引用变量</label>
              <div className="mt-1 flex flex-wrap gap-1.5">
                {detectedVars.map((v, i) => (
                  <Badge key={i} variant="secondary" className="text-xs">{v}</Badge>
                ))}
              </div>
            </div>
          )}

          <div>
            <label className="text-sm font-medium">通过条件描述</label>
            <Input className="mt-1" value={passCondition} onChange={e => setPassCondition(e.target.value)}
              placeholder="如：商家确认有现货或可调货" />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={onClose}>取消</Button>
          <Button onClick={handleSave}>保存</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ── Tab 1: Funnel Config ─────────────────────────────────

function FunnelConfigTab() {
  const [config, setConfig] = useState<InquiryFunnelConfig>(loadConfig);
  const [editingRound, setEditingRound] = useState<InquiryRoundConfig | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const enabledRoundCount = useMemo(() => getEnabledRoundCount(config.rounds), [config.rounds]);

  const persist = useCallback((next: InquiryFunnelConfig) => {
    const updated = normalizeFunnelConfig({ ...next, updatedAt: new Date().toISOString() });
    setConfig(updated);
    saveConfig(updated);
  }, []);

  const handleAdd = () => {
    if (config.rounds.length >= MAX_INQUIRY_ROUNDS) {
      toast.error(`当前自动化询价最多支持 ${MAX_INQUIRY_ROUNDS} 个轮次`);
      return;
    }

    setEditingRound(buildRoundConfig(config.rounds.length + 1, { id: '', templateText: '', enabled: true }));
    setDialogOpen(true);
  };

  const handleEdit = (r: InquiryRoundConfig) => {
    setEditingRound(r);
    setDialogOpen(true);
  };

  const handleSave = (r: InquiryRoundConfig) => {
    const idx = config.rounds.findIndex(x => x.id === r.id);
    let rounds: InquiryRoundConfig[];
    if (idx >= 0) {
      rounds = config.rounds.map((x, i) => i === idx ? { ...r, round: i + 1 } : x);
    } else {
      rounds = [...config.rounds, { ...r, id: makeId(), round: config.rounds.length + 1 }];
    }
    persist({ ...config, rounds });
    setDialogOpen(false);
    toast.success(idx >= 0 ? '轮次已更新' : '轮次已添加');
  };

  const handleDelete = (id: string) => {
    const rounds = config.rounds.filter(r => r.id !== id).map((r, i) => ({ ...r, round: i + 1 }));
    persist({ ...config, rounds });
    toast.success('轮次已删除');
  };

  const handleToggleEnabled = (id: string) => {
    let nextEnabled = false;
    const rounds = config.rounds.map((round) => {
      if (round.id !== id) {
        return round;
      }

      nextEnabled = !round.enabled;
      return {
        ...round,
        enabled: nextEnabled,
      };
    });

    persist({ ...config, rounds });
    toast.success(nextEnabled ? '轮次已启用' : '轮次已停用');
  };

  const handleMove = (idx: number, dir: -1 | 1) => {
    const rounds = [...config.rounds];
    const target = idx + dir;
    if (target < 0 || target >= rounds.length) return;
    [rounds[idx], rounds[target]] = [rounds[target], rounds[idx]];
    persist({ ...config, rounds: rounds.map((r, i) => ({ ...r, round: i + 1 })) });
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <h3 className="text-lg font-semibold">消息轮次配置</h3>
          {enabledRoundCount === 0 ? (
            <p className="mt-2 text-xs text-amber-600">当前未启用任何消息轮次，启动任务前至少启用 1 轮。</p>
          ) : enabledRoundCount < config.rounds.length ? (
            <p className="mt-2 text-xs text-muted-foreground">当前已启用 {enabledRoundCount} 轮，停用的轮次不会被自动发送。</p>
          ) : null}
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <Badge variant="secondary">已启用 {enabledRoundCount} / 已定义 {config.rounds.length} </Badge>
          <Button onClick={handleAdd} size="sm" disabled={config.rounds.length >= MAX_INQUIRY_ROUNDS}>
            <Plus className="h-4 w-4 mr-1" /> 添加轮次
          </Button>
        </div>
      </div>

      {/* Round cards */}
      {config.rounds.length === 0 ? (
        <Card className="border-dashed">
          <CardContent className="flex flex-col items-center justify-center py-12 text-muted-foreground">
            <ListChecks className="h-10 w-10 mb-3 opacity-40" />
            <p className="text-sm">尚未配置任何轮次</p>
            <Button variant="outline" size="sm" className="mt-4" onClick={handleAdd}>添加第一个轮次</Button>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-3">
          {config.rounds.map((r, idx) => (
            <Card key={r.id} className={`relative transition-shadow hover:shadow-md ${!r.enabled ? 'border-dashed opacity-70' : ''}`}>
              <CardHeader className="pb-2">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-blue-100 text-sm font-bold text-blue-700">
                      {r.round}
                    </span>
                    <div className="space-y-1">
                      <CardTitle className="text-base">{r.name}</CardTitle>
                      <div className="flex items-center gap-2">
                        <Badge variant={r.enabled ? 'secondary' : 'outline'} className="text-[11px]">
                          {r.enabled ? '已启用' : '已停用'}
                        </Badge>
                        {!r.enabled && <span className="text-xs text-muted-foreground">本轮已保留，但自动化询价时不会发送</span>}
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center gap-1">
                    <Button
                      variant={r.enabled ? 'secondary' : 'outline'}
                      size="sm"
                      className="h-8 px-3 text-xs"
                      onClick={() => handleToggleEnabled(r.id)}
                    >
                      {r.enabled ? '停用' : '启用'}
                    </Button>
                    <Button variant="ghost" size="icon" className="h-8 w-8" disabled={idx === 0} onClick={() => handleMove(idx, -1)}>
                      <ArrowUp className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="icon" className="h-8 w-8" disabled={idx === config.rounds.length - 1} onClick={() => handleMove(idx, 1)}>
                      <ArrowDown className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => handleEdit(r)}>
                      <Pencil className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive hover:text-destructive" onClick={() => handleDelete(r.id)}>
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-2 pt-0">
                <div className="rounded-md bg-muted/50 p-3">
                  <p className="text-sm font-mono text-foreground/80 leading-relaxed">{r.templateText}</p>
                </div>
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="text-xs text-muted-foreground">变量：</span>
                  {r.variables.length > 0 ? r.variables.map(v => (
                    <Badge key={v} variant="secondary" className="text-[11px]">{v}</Badge>
                  )) : <span className="text-xs text-muted-foreground">无</span>}
                </div>
                {r.passCondition && (
                  <p className="text-xs text-muted-foreground">
                    <span className="font-medium">通过条件：</span>{r.passCondition}
                  </p>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      <RoundEditorDialog open={dialogOpen} round={editingRound} onSave={handleSave} onClose={() => setDialogOpen(false)} />
    </div>
  );
}

// ── Tab 2: Inquiry Tasks ─────────────────────────────────

const ALL_STATUSES: InquiryTaskStatus[] = [
  'PENDING_SEND', 'WAITING_REPLY',
  'COMPLETED', 'REJECTED', 'TIMEOUT_REJECTED', 'HUMAN_TAKEOVER',
];

// ── Batch Run Status Badge ────────────────────────────────

type InquiryRunStatus = 'RUNNING' | 'STOPPING' | 'COMPLETED' | 'STOPPED' | 'FAILED';

interface InquiryRunCard {
  id: string;
  batch_id: string;
  account_id: string;
  account_name: string;
  status: InquiryRunStatus;
  total_tasks: number;
  completed_tasks: number;
  rejected_tasks: number;
  human_takeover_tasks: number;
  started_at: string;
  finished_at: string | null;
  current_item: string;
  error: string;
}

const BATCH_RUN_STATUS: Record<InquiryRunStatus, { label: string; className: string }> = {
  RUNNING:   { label: '运行中', className: 'bg-blue-100 text-blue-700 border-blue-200' },
  STOPPING:  { label: '停止中', className: 'bg-amber-100 text-amber-700 border-amber-200' },
  COMPLETED: { label: '已完成', className: 'bg-green-100 text-green-800 border-green-300' },
  STOPPED:   { label: '已停止', className: 'bg-slate-100 text-slate-700 border-slate-200' },
  FAILED:    { label: '失败', className: 'bg-red-100 text-red-700 border-red-200' },
};

function InquiryTasksTab() {
  const { user } = useAuth();
  const [batchFilter, setBatchFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [detailTask, setDetailTask] = useState<InquiryTask | null>(null);
  const [startDialogOpen, setStartDialogOpen] = useState(false);
  const [selectedBatchToStart, setSelectedBatchToStart] = useState('');
  const [selectedAccountId, setSelectedAccountId] = useState('');
  const [accounts, setAccounts] = useState<ProcurementAccount1688[]>([]);
  const [batchOptions, setBatchOptions] = useState<InquiryBatchOption[]>([]);
  const [allTasks, setAllTasks] = useState<InquiryTask[]>([]);
  const [inquiryProgresses, setInquiryProgresses] = useState<InquiryProgress[]>([]);
  const [loading, setLoading] = useState(true);
  const [starting, setStarting] = useState(false);
  const [stoppingBatchIds, setStoppingBatchIds] = useState<string[]>([]);
  const { batches: procurementBatches } = useProcurementBatchOptions();

  useEffect(() => {
    let cancelled = false;
    const syncDashboard = async (markLoaded = false) => {
      const [tasksRes, optionsRes, progressRes] = await Promise.allSettled([
        fetchInquiryTasks(),
        fetchInquiryBatchOptions(),
        fetchInquiryStatuses(),
      ]);

      if (cancelled) return;

      if (tasksRes.status === 'fulfilled') {
        setAllTasks(tasksRes.value);
      } else {
        console.error('Failed to fetch inquiry tasks:', tasksRes.reason);
      }

      if (optionsRes.status === 'fulfilled') {
        setBatchOptions(optionsRes.value);
      } else {
        console.error('Failed to fetch inquiry batches:', optionsRes.reason);
      }

      if (progressRes.status === 'fulfilled') {
        setInquiryProgresses(progressRes.value);
      } else {
        console.error('Failed to fetch inquiry progress:', progressRes.reason);
      }

      if (markLoaded) {
        setLoading(false);
      }
    };

    void syncDashboard(true);
    const intervalId = window.setInterval(() => {
      void syncDashboard(false);
    }, 3000);

    return () => {
      cancelled = true;
      window.clearInterval(intervalId);
    };
  }, []);

  useEffect(() => {
    if (!user?.id) return;
    let cancelled = false;
    (async () => {
      try {
        const accts = await fetchAccounts(user.id);
        if (!cancelled) setAccounts(accts);
      } catch (err) {
        console.error('Failed to fetch accounts:', err);
      }
    })();
    return () => { cancelled = true; };
  }, [user?.id]);

  useEffect(() => {
    if (!startDialogOpen) {
      setSelectedBatchToStart('');
      setSelectedAccountId('');
      return;
    }

    if (selectedBatchToStart && !batchOptions.some(option => option.batch_id === selectedBatchToStart)) {
      setSelectedBatchToStart('');
    }
  }, [startDialogOpen, selectedBatchToStart, batchOptions]);

  const filterBatchIds = useMemo(
    () => procurementBatches.map((batch) => batch.batch_id),
    [procurementBatches],
  );

  useEffect(() => {
    if (batchFilter !== 'all' && !filterBatchIds.includes(batchFilter)) {
      setBatchFilter('all');
    }
  }, [batchFilter, filterBatchIds]);

  const batchOptionMap = useMemo(
    () => new Map(batchOptions.map(option => [option.batch_id, option])),
    [batchOptions],
  );

  const activeInquiryRuns = useMemo(
    () => inquiryProgresses.filter(progress => progress.status === 'processing' || progress.status === 'stopping'),
    [inquiryProgresses],
  );

  const visibleInquiryRuns = useMemo(
    () => inquiryProgresses.filter(progress => progress.status !== 'idle'),
    [inquiryProgresses],
  );

  const activeProgressBatchIds = useMemo(
    () => new Set(activeInquiryRuns.map(progress => progress.batchId)),
    [activeInquiryRuns],
  );

  const busyAccountIds = useMemo(
    () => new Set(activeInquiryRuns.map(progress => progress.accountId)),
    [activeInquiryRuns],
  );

  const availableBatches = useMemo(() => {
    return batchOptions.filter(option => !activeProgressBatchIds.has(option.batch_id));
  }, [activeProgressBatchIds, batchOptions]);

  const availableAccounts = useMemo(
    () => accounts.filter(account => !busyAccountIds.has(account.id)),
    [accounts, busyAccountIds],
  );

  const filtered = useMemo(() => {
    let data = [...allTasks];
    if (batchFilter !== 'all') data = data.filter(t => t.batch_id === batchFilter);
    if (statusFilter !== 'all') data = data.filter(t => t.status === statusFilter);
    return data;
  }, [allTasks, batchFilter, statusFilter]);

  const stats = useMemo(() => {
    const source = batchFilter !== 'all'
      ? allTasks.filter(t => t.batch_id === batchFilter)
      : allTasks;
    const inProgress = source.filter(t => isInquiryTaskInProgress(t.status));
    const completed = source.filter(t => t.status === 'COMPLETED');
    const rejected = source.filter(t => t.status === 'REJECTED' || t.status === 'TIMEOUT_REJECTED');
    const humanTakeover = source.filter(t => t.status === 'HUMAN_TAKEOVER');
    return { total: source.length, inProgress: inProgress.length, completed: completed.length, rejected: rejected.length, humanTakeover: humanTakeover.length };
  }, [allTasks, batchFilter]);

  const selectedAccount = useMemo(() => accounts.find(a => a.id === selectedAccountId), [accounts, selectedAccountId]);

  const batchRuns = useMemo<InquiryRunCard[]>(() => {
    return visibleInquiryRuns
      .map((progress) => {
        let status: InquiryRunStatus;
        switch (progress.status) {
          case 'processing':
            status = 'RUNNING';
            break;
          case 'stopping':
            status = 'STOPPING';
            break;
          case 'stopped':
            status = 'STOPPED';
            break;
          case 'completed':
            status = 'COMPLETED';
            break;
          case 'failed':
            status = 'FAILED';
            break;
          default:
            status = 'STOPPED';
        }

        const accountName = accounts.find(account => account.id === progress.accountId)?.account_name
          ?? progress.accountId
          ?? '未知账户';

        return {
          id: `${progress.batchId}:${progress.startedAt ?? '0'}`,
          batch_id: progress.batchId,
          account_id: progress.accountId,
          account_name: accountName,
          status,
          total_tasks: progress.totalTasks,
          completed_tasks: progress.completedTasks,
          rejected_tasks: progress.rejectedTasks,
          human_takeover_tasks: progress.humanTakeoverTasks,
          started_at: progress.startedAt ?? new Date().toISOString(),
          finished_at: progress.finishedAt,
          current_item: progress.currentItem,
          error: progress.errors[0] ?? '',
        };
      })
      .sort((left, right) => new Date(right.started_at).getTime() - new Date(left.started_at).getTime())
      .slice(0, 8);
  }, [accounts, visibleInquiryRuns]);

  const selectedBatchOption = useMemo(
    () => batchOptionMap.get(selectedBatchToStart) ?? null,
    [batchOptionMap, selectedBatchToStart],
  );

  const handleStart = async () => {
    if (!selectedBatchToStart) { toast.error('请选择一个批次'); return; }
    if (!selectedAccountId) { toast.error('请选择一个 1688 账户'); return; }

    const funnelConfig = getRuntimeFunnelConfig();
    if (funnelConfig.rounds.length === 0) {
      toast.error('请至少配置一个有效的询价轮次');
      return;
    }

    setStarting(true);
    try {
      const account = accounts.find(a => a.id === selectedAccountId);
      if (!account) {
        toast.error('所选账户不存在');
        return;
      }

      const result = await triggerInquiryBatch({
        batch_id: selectedBatchToStart,
        account_id: selectedAccountId,
        funnel_config: funnelConfig,
      });
      setStartDialogOpen(false);
      setSelectedBatchToStart('');
      setSelectedAccountId('');
      toast.success(`批次 ${selectedBatchToStart} 询价任务已启动，共 ${result.totalTasks} 个商家候选`);
    } catch (err) {
      toast.error(`启动失败: ${err instanceof Error ? err.message : String(err)}`);
    } finally {
      setStarting(false);
    }
  };

  const handleStop = async (batchId: string) => {
    setStoppingBatchIds((current) => current.includes(batchId) ? current : [...current, batchId]);
    try {
      await stopInquiryBatch(batchId);
      toast.success(`批次 ${batchId} 的停止信号已发送`);
    } catch (err) {
      toast.error(`停止失败: ${err instanceof Error ? err.message : String(err)}`);
    } finally {
      setStoppingBatchIds((current) => current.filter(id => id !== batchId));
    }
  };

  useEffect(() => {
    if (selectedBatchToStart && activeProgressBatchIds.has(selectedBatchToStart)) {
      setSelectedBatchToStart('');
    }
  }, [activeProgressBatchIds, selectedBatchToStart]);

  useEffect(() => {
    if (selectedAccountId && busyAccountIds.has(selectedAccountId)) {
      setSelectedAccountId('');
    }
  }, [busyAccountIds, selectedAccountId]);

  return (
    <div className="space-y-6">
      {/* Action bar */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold">询价任务</h3>
          <p className="text-sm text-muted-foreground mt-0.5">每次询价按批次维度执行，自动跑完该批次全部采购内容</p>
        </div>
        <Button onClick={() => setStartDialogOpen(true)}>
          <Play className="h-4 w-4 mr-1.5" /> 开始询价
        </Button>
      </div>

      {/* Active batch runs */}
      {batchRuns.length > 0 && (
        <div className="space-y-3">
          <h4 className="text-sm font-semibold text-muted-foreground">批次执行状态</h4>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {batchRuns.map(run => {
              const finishedCount = run.completed_tasks + run.rejected_tasks + run.human_takeover_tasks;
              const progress = run.total_tasks > 0 ? Math.round((finishedCount / run.total_tasks) * 100) : 0;
              const statusCfg = BATCH_RUN_STATUS[run.status];
              return (
                <Card key={run.id} className="transition-shadow hover:shadow-md">
                  <CardContent className="p-4">
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center gap-2 min-w-0">
                        <Badge variant="outline" className={statusCfg.className}>{statusCfg.label}</Badge>
                        <span className="text-sm font-medium truncate">{run.batch_id}</span>
                        <Badge variant="secondary" className="text-xs shrink-0">{run.account_name}</Badge>
                      </div>
                      {run.status === 'RUNNING' && (
                        <Button
                          variant="outline"
                          size="sm"
                          className="h-7 text-destructive hover:text-destructive shrink-0"
                          onClick={() => handleStop(run.batch_id)}
                          disabled={stoppingBatchIds.includes(run.batch_id)}
                        >
                          <Square className="h-3.5 w-3.5 mr-1" /> 停止
                        </Button>
                      )}
                    </div>
                    <Progress value={progress} className="h-2 mb-2" />
                    <div className="flex items-center justify-between text-xs text-muted-foreground">
                      <span>完成 {run.completed_tasks} / 拒绝 {run.rejected_tasks} / 人工接管 {run.human_takeover_tasks} / 共 {run.total_tasks}</span>
                      <span>{progress}%</span>
                    </div>
                    {run.current_item && (
                      <p className="text-xs text-muted-foreground mt-1 line-clamp-2">当前: {run.current_item}</p>
                    )}
                    {run.error && (
                      <p className="text-xs text-destructive mt-1">{run.error}</p>
                    )}
                    <p className="text-xs text-muted-foreground mt-1">
                      启动于 {formatDate(run.started_at)}
                      {run.finished_at && <> · 结束于 {formatDate(run.finished_at)}</>}
                    </p>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        </div>
      )}

      {/* Stat cards */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <StatCard title="总任务数" value={stats.total} icon={<ListChecks className="h-5 w-5" />} />
        <StatCard title="进行中" value={stats.inProgress} icon={<Loader2 className="h-5 w-5" />} />
        <StatCard title="已完成" value={stats.completed} icon={<CheckCircle2 className="h-5 w-5" />} />
        <StatCard title="已拒绝 / 超时" value={stats.rejected} icon={<XCircle className="h-5 w-5" />} />
        <StatCard title="人工接管" value={stats.humanTakeover} icon={<AlertTriangle className="h-5 w-5" />} />
      </div>

      {/* Filters */}
      <div className="flex items-center gap-3 flex-wrap">
        <Select value={batchFilter} onValueChange={setBatchFilter}>
          <SelectTrigger className="w-[260px]">
            <SelectValue placeholder="筛选批次" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">全部批次</SelectItem>
            {filterBatchIds.map((batchId) => <SelectItem key={batchId} value={batchId}>{batchId}</SelectItem>)}
          </SelectContent>
        </Select>

        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="筛选状态" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">全部状态</SelectItem>
            {ALL_STATUSES.map(s => <SelectItem key={s} value={s}>{STATUS_CONFIG[s].label}</SelectItem>)}
          </SelectContent>
        </Select>
      </div>

      {/* Table */}
      <div className="rounded-lg border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-[200px]">商家名称</TableHead>
              <TableHead>商品标题</TableHead>
              <TableHead className="w-[80px] text-center">轮次</TableHead>
              <TableHead className="w-[100px] text-center">状态</TableHead>
              <TableHead className="w-[100px] text-center">重试次数</TableHead>
              <TableHead className="w-[160px]">最近交互</TableHead>
              <TableHead className="w-[70px] text-center">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filtered.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="h-32 text-center text-muted-foreground">{loading ? '加载中...' : '暂无数据'}</TableCell>
              </TableRow>
            ) : filtered.map(task => (
              <TableRow key={task.id} className="cursor-pointer hover:bg-muted/50" onClick={() => setDetailTask(task)}>
                <TableCell className="font-medium truncate max-w-[200px]">{task.merchant_name}</TableCell>
                <TableCell className="truncate max-w-[280px]">{task.title}</TableCell>
                <TableCell className="text-center">
                  <span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-blue-50 text-xs font-semibold text-blue-700">
                    {task.current_round}
                  </span>
                </TableCell>
                <TableCell className="text-center"><TaskStatusBadge status={task.status} /></TableCell>
                <TableCell className="text-center text-sm text-muted-foreground">{task.retry_count}</TableCell>
                <TableCell className="text-sm text-muted-foreground">{task.last_interacted_at ? formatDate(task.last_interacted_at) : '—'}</TableCell>
                <TableCell className="text-center">
                  <Button variant="ghost" size="icon" className="h-8 w-8" onClick={e => { e.stopPropagation(); setDetailTask(task); }}>
                    <Eye className="h-4 w-4" />
                  </Button>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      {/* Detail Sheet */}
      <Sheet open={!!detailTask} onOpenChange={v => { if (!v) setDetailTask(null); }}>
        <SheetContent className="sm:max-w-lg overflow-y-auto">
          {detailTask && (
            <>
              <SheetHeader>
                <SheetTitle className="text-base">{detailTask.merchant_name}</SheetTitle>
              </SheetHeader>

              <div className="mt-4 space-y-5">
                {/* Meta */}
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div>
                    <span className="text-muted-foreground">商品：</span>
                    <span className="font-medium">{detailTask.title}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">批次：</span>
                    <span className="font-medium">{detailTask.batch_id}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">当前轮次：</span>
                    <span className="font-semibold text-blue-700">{detailTask.current_round}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">状态：</span>
                    <TaskStatusBadge status={detailTask.status} />
                  </div>
                  <div>
                    <span className="text-muted-foreground">重试次数：</span>
                    <span>{detailTask.retry_count}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">创建时间：</span>
                    <span>{formatDate(detailTask.created_at)}</span>
                  </div>
                </div>

                {/* Extracted data */}
                {detailTask.extracted_data && Object.keys(detailTask.extracted_data).length > 0 && (
                  <div>
                    <h4 className="text-sm font-semibold mb-2 flex items-center gap-1.5">
                      <CheckCircle2 className="h-4 w-4 text-green-600" /> 提取数据
                    </h4>
                    <div className="rounded-md border p-3 grid grid-cols-2 gap-2 text-sm">
                      {Object.entries(detailTask.extracted_data).map(([k, v]) => (
                        <div key={k}>
                          <span className="text-muted-foreground">{k}：</span>
                          <span className="font-medium">{String(v)}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Ask context */}
                <div>
                  <h4 className="text-sm font-semibold mb-2 flex items-center gap-1.5">
                    <Send className="h-4 w-4 text-blue-600" /> 询价上下文
                  </h4>
                  <div className="flex flex-wrap gap-1.5">
                    {Object.entries(detailTask.ask_context).filter(([, v]) => v).map(([k, v]) => (
                      <Badge key={k} variant="outline" className="text-xs">
                        {formatAskContextLabel(k)}: {v}
                      </Badge>
                    ))}
                  </div>
                </div>

                {/* Chat history */}
                <div>
                  <h4 className="text-sm font-semibold mb-3 flex items-center gap-1.5">
                    <Clock className="h-4 w-4 text-slate-500" /> 聊天记录
                  </h4>
                  <ChatBubbles messages={detailTask.chat_history} />
                </div>
              </div>
            </>
          )}
        </SheetContent>
      </Sheet>

      {/* Start inquiry dialog */}
      <Dialog open={startDialogOpen} onOpenChange={setStartDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>开始询价</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-2">
            <p className="text-sm text-muted-foreground">
              选择一个批次和 1688 账户，系统将使用该账户自动对该批次下已搜索出的商家候选执行漏斗式询价，直至全部完成或手动停止。
            </p>
            <div>
              <label className="text-sm font-medium">选择批次</label>
              <Select value={selectedBatchToStart} onValueChange={setSelectedBatchToStart}>
                <SelectTrigger className="mt-1">
                  <SelectValue placeholder="请选择批次" />
                </SelectTrigger>
                <SelectContent>
                  {batchOptions.length === 0 ? (
                    <SelectItem value="__none" disabled>暂无可询价批次，请先完成 1688 搜索</SelectItem>
                  ) : availableBatches.length === 0 ? (
                    <SelectItem value="__none" disabled>当前可询价批次正在运行中</SelectItem>
                  ) : (
                    availableBatches.map(option => {
                      const labelCount = option.candidate_count > 0 ? `${option.candidate_count} 个候选商家` : `${option.task_count} 个已建任务`;
                      return <SelectItem key={option.batch_id} value={option.batch_id}>{option.batch_id}（{labelCount}）</SelectItem>;
                    })
                  )}
                </SelectContent>
              </Select>
            </div>
            <div>
              <label className="text-sm font-medium">选择 1688 账户</label>
              <Select value={selectedAccountId} onValueChange={setSelectedAccountId}>
                <SelectTrigger className="mt-1">
                  <SelectValue placeholder="请选择 1688 账户" />
                </SelectTrigger>
                <SelectContent>
                  {accounts.length === 0 ? (
                    <SelectItem value="__none" disabled>暂无账户，请先在右上角用户菜单的「采购账户管理」中添加</SelectItem>
                  ) : availableAccounts.length === 0 ? (
                    <SelectItem value="__none" disabled>当前 1688 账户都在运行中，请先停止任务或新增账户</SelectItem>
                  ) : (
                    accounts.map(a => (
                      <SelectItem key={a.id} value={a.id} disabled={busyAccountIds.has(a.id)}>
                        {a.account_name}
                        {a.login_status === 'success' ? ' ✅' : a.login_status === 'failed' ? ' ❌' : ''}
                        {busyAccountIds.has(a.id) ? '（运行中）' : ''}
                        {a.remark ? ` (${a.remark})` : ''}
                      </SelectItem>
                    ))
                  )}
                </SelectContent>
              </Select>
            </div>
            {selectedBatchToStart && selectedAccountId && (
              <div className="rounded-md border p-3 text-sm space-y-1">
                <p><span className="text-muted-foreground">批次：</span><span className="font-medium">{selectedBatchToStart}</span></p>
                <p><span className="text-muted-foreground">候选商家：</span><span className="font-medium">{selectedBatchOption?.candidate_count ?? allTasks.filter(t => t.batch_id === selectedBatchToStart).length}</span></p>
                <p><span className="text-muted-foreground">已建任务：</span><span className="font-medium">{selectedBatchOption?.task_count ?? allTasks.filter(t => t.batch_id === selectedBatchToStart).length}</span></p>
                <p><span className="text-muted-foreground">执行账户：</span><span className="font-medium">{selectedAccount?.account_name}</span></p>
                <p><span className="text-muted-foreground">执行方式：</span>自动初始化询价任务后，按漏斗轮次逐个商家发送、巡检回复并推进状态</p>
              </div>
            )}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setStartDialogOpen(false)}>取消</Button>
            <Button onClick={handleStart} disabled={!selectedBatchToStart || !selectedAccountId || starting}>
              <Play className="h-4 w-4 mr-1.5" /> 启动
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

// ── Main Page ────────────────────────────────────────────

export default function SmartInquiry() {
  const [searchParams] = useSearchParams();
  const activeTab = searchParams.get('tab') === 'tasks' ? 'tasks' : 'config';

  return (
    <div className="h-full flex flex-col gap-4">
      <Tabs value={activeTab} className="w-full">
        <TabsContent value="config" className="mt-0">
          <FunnelConfigTab />
        </TabsContent>

        <TabsContent value="tasks" className="mt-0">
          <InquiryTasksTab />
        </TabsContent>
      </Tabs>
    </div>
  );
}
