/**
 * 新任务 · 快速开始
 * 自然语义驱动的系统接管入口
 * 核心原则：用户用一句自然语言，系统完成首次判断并直接开始处理
 * 
 * API 集成：
 * - POST /api/cold_start/interpret - 冷启动解析
 * - POST /api/cold_start/confirm - 确认并建档
 * - POST /api/tenant/profile/update - 更新租户信息
 */

import { useState, useCallback } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Progress } from '@/components/ui/progress';
import {
  Check,
  Loader2,
  Building2,
  AlertCircle,
  RotateCcw,
  Send,
} from 'lucide-react';
import { toast } from 'sonner';
import { supabase } from '@/integrations/supabase/client';

interface MerchantOnboardingProps {
  onNavigate?: (tab: string) => void;
}

type PageState = 'idle' | 'analyzing' | 'suggesting' | 'running' | 'done' | 'failed';

// 系统上下文快照
interface ContextSnapshot {
  pending_orders: number;
  support_load_level: string;
}

// 冷启动解析返回结构
interface InterpretResponse {
  summary: string;
  explanation?: string;
  inferred_problem: string;
  confidence: number;
  suggested_action: string;
  action_steps: string[];
  target_route: string;
  result_message: string;
}

// 系统判断展示结构
interface SystemJudgment {
  coreProblem: string;
  impactScope: string;
  suggestedAction: string;
  actionSteps: string[];
  targetRoute: string;
  resultMessage: string;
  confidence: number;
}

// Mock 系统上下文数据
const getMockContextSnapshot = (): ContextSnapshot => ({
  pending_orders: 19,
  support_load_level: '偏高',
});

// 调用冷启动解析接口
const callInterpretAPI = async (
  rawInput: string,
  contextSnapshot: ContextSnapshot
): Promise<InterpretResponse> => {
  try {
    const { data, error } = await supabase.functions.invoke('cold-start-interpret', {
      body: {
        raw_input: rawInput,
        entry_point: 'new_task_fast_start',
        context_snapshot: contextSnapshot,
      },
    });

    if (error) throw error;
    return data;
  } catch (e) {
    // 降级到本地解析
    console.warn('Cold start interpret API unavailable, using local fallback');
    return localAnalyzeInput(rawInput);
  }
};

// 调用确认建档接口
const callConfirmAPI = async (
  rawInput: string,
  inferredProblem: string,
  confidence: number
): Promise<void> => {
  try {
    await supabase.functions.invoke('cold-start-confirm', {
      body: {
        raw_input: rawInput,
        inferred_problem: inferredProblem,
        confidence,
        user_confirmed: true,
      },
    });
  } catch (e) {
    // 静默失败，不影响用户体验
    console.warn('Cold start confirm API unavailable');
  }
};

// 调用租户信息更新接口
const callTenantProfileUpdate = async (companyName: string): Promise<void> => {
  if (!companyName.trim()) return;
  
  try {
    await supabase.functions.invoke('tenant-profile-update', {
      body: {
        company_name: companyName,
        source: 'task_execution',
      },
    });
  } catch (e) {
    // 静默失败
    console.warn('Tenant profile update API unavailable');
  }
};

// 本地降级解析逻辑
const localAnalyzeInput = (input: string): InterpretResponse => {
  const lowerInput = input.toLowerCase();
  
  if (lowerInput.includes('发货') || lowerInput.includes('订单') || lowerInput.includes('物流') || lowerInput.includes('超时')) {
    return {
      summary: '订单履约存在延迟风险',
      explanation: '近 24 小时内的未发货订单',
      inferred_problem: 'order_fulfillment_delay',
      confidence: 0.85,
      suggested_action: '立即扫描并标记高风险订单',
      action_steps: ['扫描近 24 小时订单', '识别超时风险订单', '生成优先处理清单'],
      target_route: 'aftersales',
      result_message: '已标记 3 个高风险订单，建议优先处理',
    };
  }
  
  if (lowerInput.includes('客服') || lowerInput.includes('消息') || lowerInput.includes('回复') || lowerInput.includes('扛不住')) {
    return {
      summary: '客服响应压力过大',
      explanation: '待处理的客户咨询消息',
      inferred_problem: 'support_overload',
      confidence: 0.88,
      suggested_action: '整理待回复消息并生成建议回复',
      action_steps: ['扫描待回复消息', '按紧急程度排序', '生成建议回复内容'],
      target_route: 'aftersales',
      result_message: '已整理 12 条消息，其中 3 条需紧急回复',
    };
  }
  
  if (lowerInput.includes('退款') || lowerInput.includes('对账') || lowerInput.includes('财务') || lowerInput.includes('账目')) {
    return {
      summary: '退款/对账流程需要梳理',
      explanation: '近期退款记录与账目明细',
      inferred_problem: 'finance_reconciliation',
      confidence: 0.82,
      suggested_action: '整理退款记录并标记异常项',
      action_steps: ['整理近期退款记录', '标记可能的异常项', '生成对账建议清单'],
      target_route: 'transactions',
      result_message: '已标记 2 笔异常退款，建议复核',
    };
  }
  
  if (lowerInput.includes('接手') || lowerInput.includes('现状') || lowerInput.includes('刚来') || lowerInput.includes('了解')) {
    return {
      summary: '需要快速了解系统现状',
      explanation: '全局业务数据概览',
      inferred_problem: 'system_overview',
      confidence: 0.90,
      suggested_action: '生成系统现状报告',
      action_steps: ['扫描各模块数据', '生成关键指标摘要', '标记需关注的异常项'],
      target_route: 'home',
      result_message: '现状报告已生成，发现 2 个需关注的问题',
    };
  }
  
  // 默认判断
  return {
    summary: '业务流程需要优化',
    explanation: '相关业务数据',
    inferred_problem: 'general_optimization',
    confidence: 0.70,
    suggested_action: '分析并生成处理建议',
    action_steps: ['理解你的需求', '分析相关数据', '生成处理方案'],
    target_route: 'home',
    result_message: '分析完成，已生成处理建议',
  };
};

const placeholderExamples = [
  "最近发货有点乱",
  "客服消息太多，团队扛不住",
  "我刚接手这个系统，先帮我看看现状",
];

export function MerchantOnboarding({ onNavigate }: MerchantOnboardingProps) {
  const [pageState, setPageState] = useState<PageState>('idle');
  const [naturalInput, setNaturalInput] = useState('');
  const [judgment, setJudgment] = useState<SystemJudgment | null>(null);
  const [inferredProblem, setInferredProblem] = useState('');
  const [companyName, setCompanyName] = useState('');
  const [progress, setProgress] = useState(0);
  const [currentStep, setCurrentStep] = useState('');
  const [contextSnapshot] = useState<ContextSnapshot>(getMockContextSnapshot());
  
  const [placeholderIndex, setPlaceholderIndex] = useState(0);

  // 轮换 placeholder
  const currentPlaceholder = placeholderExamples[placeholderIndex];

  const handleSubmit = useCallback(async () => {
    if (!naturalInput.trim()) return;
    
    setPageState('analyzing');
    
    try {
      // 调用冷启动解析接口
      const response = await callInterpretAPI(naturalInput, contextSnapshot);
      
      // 转换为系统判断结构
      const result: SystemJudgment = {
        coreProblem: response.summary,
        impactScope: response.explanation || '相关业务数据',
        suggestedAction: response.suggested_action,
        actionSteps: response.action_steps,
        targetRoute: response.target_route,
        resultMessage: response.result_message,
        confidence: response.confidence,
      };
      
      setJudgment(result);
      setInferredProblem(response.inferred_problem);
      setPageState('suggesting');
    } catch (error) {
      console.error('Failed to analyze input:', error);
      setPageState('failed');
    }
  }, [naturalInput, contextSnapshot]);

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSubmit();
    }
  };

  const handleConfirm = useCallback(async () => {
    if (!judgment) return;
    
    // 静默调用确认建档接口（用户无感知）
    callConfirmAPI(naturalInput, inferredProblem, judgment.confidence);
    
    setPageState('running');
    setProgress(0);
    
    let stepIndex = 0;
    const steps = judgment.actionSteps;
    
    const interval = setInterval(() => {
      if (stepIndex < steps.length) {
        setCurrentStep(`正在${steps[stepIndex]}…`);
        setProgress(((stepIndex + 1) / steps.length) * 100);
        stepIndex++;
      } else {
        clearInterval(interval);
        
        // 如果用户填写了公司名称，静默更新
        if (companyName.trim()) {
          callTenantProfileUpdate(companyName);
        }
        
        setTimeout(() => {
          setPageState('done');
          toast.success(judgment.resultMessage, { duration: 4000 });
          // 跳转
          setTimeout(() => {
            onNavigate?.(judgment.targetRoute);
          }, 1500);
        }, 500);
      }
    }, 800);
  }, [judgment, naturalInput, inferredProblem, companyName, onNavigate]);

  const handleChangeDirection = () => {
    setPageState('idle');
    setJudgment(null);
    // 保留输入，让用户可以修改
  };

  const handleRetry = () => {
    if (judgment) {
      handleConfirm();
    }
  };

  const handleReset = () => {
    setPageState('idle');
    setJudgment(null);
    setNaturalInput('');
    setProgress(0);
    setCurrentStep('');
    setInferredProblem('');
  };

  return (
    <div className="min-h-[calc(100vh-120px)] bg-background">
      <div className="max-w-2xl mx-auto px-4 py-12">
        
        {/* ===== 区块1: 自然语义输入 ===== */}
        {pageState === 'idle' && (
          <div className="space-y-6">
            {/* 系统判断前提式标题 */}
            <div className="text-center space-y-2">
              <h1 className="text-2xl font-semibold text-foreground">
                我正在查看你当前的运营状态
              </h1>
              <p className="text-lg text-muted-foreground">
                你现在最想优先解决哪一件？
              </p>
            </div>
            
            {/* 系统已知状态摘要（弱视觉） */}
            <div className="text-center">
              <p className="text-xs text-muted-foreground/60">
                当前状态：今日有 {contextSnapshot.pending_orders} 个订单待处理 · 客服消息量{contextSnapshot.support_load_level}
              </p>
            </div>
            
            <div className="relative">
              <Textarea
                value={naturalInput}
                onChange={(e) => setNaturalInput(e.target.value)}
                onKeyDown={handleKeyDown}
                placeholder={currentPlaceholder}
                className="min-h-[120px] text-lg resize-none pr-14 focus-visible:ring-primary"
                autoFocus
                onFocus={() => {
                  // 切换 placeholder
                  setPlaceholderIndex((prev) => (prev + 1) % placeholderExamples.length);
                }}
              />
              <Button
                size="icon"
                onClick={handleSubmit}
                disabled={!naturalInput.trim()}
                className="absolute right-3 bottom-3 h-10 w-10 rounded-full"
              >
                <Send className="h-4 w-4" />
              </Button>
            </div>
            
            <p className="text-center text-sm text-muted-foreground">
              用你自己的话描述就好，系统会理解并开始处理
            </p>
          </div>
        )}

        {/* ===== 分析中状态 ===== */}
        {pageState === 'analyzing' && (
          <div className="text-center space-y-4 py-16">
            <Loader2 className="h-8 w-8 animate-spin text-primary mx-auto" />
            <p className="text-muted-foreground">正在理解你的情况…</p>
          </div>
        )}

        {/* ===== 区块2: 系统理解卡 ===== */}
        {pageState === 'suggesting' && judgment && (
          <div className="space-y-6">
            {/* 用户输入回显（弱化） */}
            <div className="text-center">
              <p className="text-sm text-muted-foreground/70">
                "{naturalInput}"
              </p>
            </div>

            {/* 系统理解卡（精简结构） */}
            <Card className="border-primary/20">
              <CardContent className="p-6 space-y-4">
                {/* 核心问题理解 */}
                <div className="space-y-1">
                  <p className="text-sm text-muted-foreground">我理解你当前的核心问题是</p>
                  <p className="text-xl font-medium text-foreground">{judgment.coreProblem}</p>
                </div>

                {/* 场景说明（判断说明） */}
                <div className="space-y-1">
                  <p className="text-sm text-muted-foreground">这通常发生在</p>
                  <p className="text-foreground">{judgment.impactScope}</p>
                </div>
              </CardContent>
            </Card>

            {/* 双按钮 */}
            <div className="space-y-3">
              <Button 
                size="lg" 
                onClick={handleConfirm}
                className="w-full h-12 text-base"
              >
                我先从这里处理
              </Button>
              
              <Button
                variant="ghost"
                size="lg"
                onClick={handleChangeDirection}
                className="w-full h-10 text-sm text-muted-foreground hover:text-foreground"
              >
                不太对，换个说法
              </Button>
            </div>
          </div>
        )}

        {/* ===== 区块3: 执行态反馈 + 顺手建档 ===== */}
        {pageState === 'running' && judgment && (
          <div className="space-y-6">
            <Card>
              <CardContent className="p-6 space-y-6">
                {/* 进度显示 */}
                <div className="space-y-3">
                  <div className="flex items-center gap-3">
                    <Loader2 className="h-5 w-5 animate-spin text-primary" />
                    <span className="text-foreground font-medium">{currentStep}</span>
                  </div>
                  <Progress value={progress} className="h-2" />
                </div>
                
                {/* 顺手建档：唯一允许的信息采集 */}
                <div className="pt-4 border-t border-border/50">
                  <div className="flex items-start gap-3">
                    <Building2 className="h-5 w-5 text-muted-foreground mt-0.5 flex-shrink-0" />
                    <div className="flex-1 space-y-2">
                      <p className="text-sm text-muted-foreground">
                        我会把这次处理结果整理成后续可复用的规则和视图。
                        如果你有公司或店铺名称，我可以直接帮你标注。
                        <span className="text-xs ml-1 opacity-60">（可跳过）</span>
                      </p>
                      <Input
                        value={companyName}
                        onChange={(e) => setCompanyName(e.target.value)}
                        placeholder="例如：星辰科技"
                        className="max-w-xs h-9 text-sm"
                      />
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 安抚说明 */}
            <div className="text-center text-sm text-muted-foreground space-y-1">
              <p>数据仅用于本次分析，不会自动执行任何操作</p>
              <p>处理结果可随时撤销或调整</p>
            </div>
          </div>
        )}

        {/* ===== 完成状态 ===== */}
        {pageState === 'done' && judgment && (
          <div className="text-center space-y-4 py-16">
            <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-green-100 text-green-600 dark:bg-green-900/30 dark:text-green-400 mb-4">
              <Check className="h-8 w-8" />
            </div>
            <h2 className="text-xl font-medium text-foreground">处理完成</h2>
            <p className="text-muted-foreground">正在跳转到工作台...</p>
          </div>
        )}

        {/* ===== 失败状态 ===== */}
        {pageState === 'failed' && (
          <div className="text-center space-y-4 py-16">
            <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-destructive/10 text-destructive mb-4">
              <AlertCircle className="h-8 w-8" />
            </div>
            <h2 className="text-xl font-medium text-foreground">处理失败</h2>
            <p className="text-muted-foreground">请稍后重试或联系客服</p>
            <div className="flex items-center justify-center gap-3 pt-4">
              <Button onClick={handleRetry} className="gap-2">
                <RotateCcw className="h-4 w-4" />
                重试
              </Button>
              <Button variant="outline" onClick={handleReset}>
                重新开始
              </Button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default MerchantOnboarding;
