/**
 * 营销工作台 - 统一入口
 * 合并了AI驾驶舱和GenUI工作台
 * dashboard视图显示AI驾驶舱内容，其他视图显示GenUI动态内容
 */

import { useState, useEffect, useCallback, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { RefreshCw, LayoutDashboard, Ticket, Megaphone, Zap, BarChart3, HelpCircle, Gift, Users, Image, Wallet, CreditCard, History, Store } from 'lucide-react';
import { MembershipPlansView } from '../finance/MembershipPlansView';
import { supabase } from '@/integrations/supabase/client';
import { DynamicRenderer } from '@/ai/genui';
import type { UISchema, RenderContext } from '@/ai/genui/types';
import { toast } from 'sonner';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { subscribeToWorkbench, clearWorkbenchCache } from '@/services/workbenchEventBus';
import { 
  UnifiedInsightFeed, 
  UnifiedInsight, 
  CompletedTasksDialog,
  GenericAgentDashboard,
  GenericGoalCard,
  GenericPendingApprovals,
  type GoalData,
  type PendingApprovalItem,
} from '../shared';
import { AgentSettingsDialog } from '../team';
import { useGoals } from '@/hooks/useGoals';

// ============= AI 助手消息事件系统 =============
type AIMessageListener = (message: string) => void;
const aiMessageListeners = new Set<AIMessageListener>();

export const subscribeToMarketingAIMessage = (callback: AIMessageListener) => {
  aiMessageListeners.add(callback);
  return () => aiMessageListeners.delete(callback);
};

export const sendToMarketingAI = (message: string) => {
  aiMessageListeners.forEach(callback => callback(message));
};

// ============= 工作台 UI Schema 事件系统 =============
type WorkbenchUIListener = (schema: UISchema) => void;
const workbenchUIListeners = new Set<WorkbenchUIListener>();

export const subscribeToMarketingWorkbenchUI = (callback: WorkbenchUIListener) => {
  workbenchUIListeners.add(callback);
  return () => workbenchUIListeners.delete(callback);
};

export const updateMarketingWorkbenchUI = (schema: UISchema) => {
  workbenchUIListeners.forEach(callback => callback(schema));
};

// ============= 组件定义 =============

interface MarketingWorkbenchProps {
  onNavigate?: (view: string) => void;
  defaultView?: ViewType;
}

type ViewType = 'dashboard' | 'coupons' | 'campaigns' | 'flash_sales' | 'group_buy' | 'payment_gifts' | 'banners' | 'cross_store' | 'analytics' | 'membership' | 'membership-balances' | 'membership-transactions' | 'membership-plans' | 'help';

const VIEW_CONFIG: Record<ViewType, { label: string; icon: React.ReactNode; message: string; isStatic?: boolean; isDashboard?: boolean; genUIFunction?: string }> = {
  dashboard: { label: '工作台', icon: <LayoutDashboard className="h-4 w-4" />, message: '显示营销工作台概览', isDashboard: true },
  coupons: { label: '优惠券', icon: <Ticket className="h-4 w-4" />, message: '查看优惠券列表' },
  campaigns: { label: '活动', icon: <Megaphone className="h-4 w-4" />, message: '查看营销活动列表' },
  flash_sales: { label: '秒杀', icon: <Zap className="h-4 w-4" />, message: '查看秒杀活动' },
  group_buy: { label: '拼团', icon: <Users className="h-4 w-4" />, message: '查看多人拼团活动' },
  payment_gifts: { label: '支付有礼', icon: <Gift className="h-4 w-4" />, message: '查看支付有礼活动' },
  banners: { label: '内容', icon: <Image className="h-4 w-4" />, message: '查看内容管理' },
  cross_store: { label: '跨店营销', icon: <Store className="h-4 w-4" />, message: '查看跨店联合促销活动' },
  analytics: { label: '数据', icon: <BarChart3 className="h-4 w-4" />, message: '查看营销数据分析' },
  membership: { label: '会员储值', icon: <Wallet className="h-4 w-4" />, message: '显示会员储值概览', genUIFunction: 'finance-genui' },
  'membership-balances': { label: '余额管理', icon: <CreditCard className="h-4 w-4" />, message: '查看会员余额', genUIFunction: 'finance-genui' },
  'membership-transactions': { label: '交易记录', icon: <History className="h-4 w-4" />, message: '查看会员交易记录', genUIFunction: 'finance-genui' },
  'membership-plans': { label: '充值套餐', icon: <Gift className="h-4 w-4" />, message: '', isStatic: true },
  help: { label: '帮助', icon: <HelpCircle className="h-4 w-4" />, message: '显示营销操作帮助指南' },
};

// 主导航项
const MAIN_NAV_ITEMS: ViewType[] = ['dashboard', 'coupons', 'campaigns', 'flash_sales', 'group_buy', 'payment_gifts', 'banners', 'cross_store', 'analytics', 'membership', 'help'];

// 会员子导航项
const MEMBERSHIP_NAV_ITEMS: ViewType[] = ['membership', 'membership-balances', 'membership-transactions', 'membership-plans'];

// 将 Goal 转换为 GoalData 格式
const convertGoalToGoalData = (goal: ReturnType<typeof useGoals>['primaryGoal']): GoalData | null => {
  if (!goal) return null;
  return {
    id: goal.id,
    title: goal.title,
    description: goal.description,
    targetValue: goal.target_value,
    currentValue: goal.current_value,
    unit: goal.unit,
    deadline: new Date(goal.deadline),
    assignedBy: goal.assigned_by,
    priority: goal.priority as 'low' | 'medium' | 'high' | 'urgent'
  };
};

// 骨架屏
function WorkbenchSkeleton() {
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {[1, 2, 3, 4].map((i) => (
          <Card key={i}>
            <CardContent className="p-4">
              <Skeleton className="h-4 w-20 mb-2" />
              <Skeleton className="h-8 w-16" />
            </CardContent>
          </Card>
        ))}
      </div>
      <Card>
        <CardHeader><Skeleton className="h-5 w-32" /></CardHeader>
        <CardContent><Skeleton className="h-64 w-full" /></CardContent>
      </Card>
    </div>
  );
}

export function MarketingWorkbench({ onNavigate, defaultView = 'dashboard' }: MarketingWorkbenchProps) {
  const [currentView, setCurrentView] = useState<ViewType>(defaultView);
  const [agentSettingsOpen, setAgentSettingsOpen] = useState(false);
  const [executedDialogOpen, setExecutedDialogOpen] = useState(false);
  
  // GenUI 状态
  const [uiSchema, setUiSchema] = useState<UISchema | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const schemaFromChatbotRef = useRef(false);
  
  // AI洞察状态
  const [insights, setInsights] = useState<UnifiedInsight[]>([]);
  const [insightsLoading, setInsightsLoading] = useState(false);
  
  // 获取目标数据
  const { primaryGoal, loading: goalsLoading } = useGoals('marketing');
  const goalData = convertGoalToGoalData(primaryGoal);
  
  const queryClient = useQueryClient();

  // 获取待审批营销请求
  const { data: pendingApprovals = [] } = useQuery({
    queryKey: ['marketing-pending-approvals'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('marketing_campaigns')
        .select('id, name, description, type, status, created_at')
        .eq('status', 'pending')
        .order('created_at', { ascending: false });

      if (error) throw error;

      return (data || []).map((item): PendingApprovalItem => ({
        id: item.id,
        type: 'campaign',
        title: item.name,
        description: item.description || item.type,
        items: 1,
        createdBy: 'AI',
        priority: 'normal',
        requestType: item.type
      }));
    }
  });

  // 审批操作
  const handleApproveAll = async (type: string) => {
    try {
      const { error } = await supabase
        .from('marketing_campaigns')
        .update({ status: 'approved', reviewed_at: new Date().toISOString() })
        .eq('status', 'pending');
      if (error) throw error;
      queryClient.invalidateQueries({ queryKey: ['marketing-pending-approvals'] });
      toast.success('已批量批准');
    } catch (error) {
      console.error('Error approving:', error);
      toast.error('操作失败');
    }
  };

  const handleRejectAll = async (type: string) => {
    try {
      const { error } = await supabase
        .from('marketing_campaigns')
        .update({ status: 'rejected', reviewed_at: new Date().toISOString() })
        .eq('status', 'pending');
      if (error) throw error;
      queryClient.invalidateQueries({ queryKey: ['marketing-pending-approvals'] });
      toast.info('已批量拒绝');
    } catch (error) {
      console.error('Error rejecting:', error);
      toast.error('操作失败');
    }
  };

  // 获取AI洞察
  const fetchInsights = useCallback(async () => {
    setInsightsLoading(true);
    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) return;

      const { data, error } = await supabase.functions.invoke('marketing-insights', {
        headers: { Authorization: `Bearer ${session.access_token}` },
      });

      if (error) throw error;
      
      if (data?.success && data?.insights?.length > 0) {
        setInsights(data.insights.map((insight: any) => ({
          id: insight.id,
          type: insight.type || 'suggestion',
          title: insight.title,
          description: insight.description,
          priority: insight.priority,
          metric: insight.metric,
          action: insight.action,
          time: insight.time || '刚刚'
        })));
      }
    } catch (error) {
      console.error('Failed to fetch insights:', error);
    } finally {
      setInsightsLoading(false);
    }
  }, []);

  // 获取GenUI Schema
  const fetchUISchema = useCallback(async (message: string, functionName: string = 'marketing-genui') => {
    setIsLoading(true);
    setError(null);

    try {
      const { data: { session } } = await supabase.auth.getSession();
      
      const { data, error: fnError } = await supabase.functions.invoke(functionName, {
        body: { message, context: { view: currentView } },
        headers: session?.access_token ? { Authorization: `Bearer ${session.access_token}` } : undefined
      });

      if (fnError) throw fnError;
      if (data?.ui_schema) setUiSchema(data.ui_schema);
    } catch (err) {
      console.error('Failed to fetch UI schema:', err);
      setError('加载失败，请重试');
    } finally {
      setIsLoading(false);
    }
  }, [currentView]);

  // 监听来自AI助手的UI更新（通过统一事件总线）- 必须在初始加载之前订阅
  useEffect(() => {
    const unsubscribe = subscribeToWorkbench('marketing', (schema) => {
      schemaFromChatbotRef.current = true;
      setUiSchema(schema);
      setIsLoading(false);
      setError(null);
      console.log('[MarketingWorkbench] Received UI schema from Chatbot');
    });
    return () => { 
      unsubscribe(); 
      clearWorkbenchCache('marketing');
      schemaFromChatbotRef.current = false;
    };
  }, []);

  // 初始加载 - 仅当没有从 chatbot 收到 schema 时才执行
  useEffect(() => {
    if (schemaFromChatbotRef.current) {
      console.log('[MarketingWorkbench] Skipping initial fetch - schema received from Chatbot');
      return;
    }
    
    if (currentView === 'dashboard') {
      fetchInsights();
      fetchUISchema(VIEW_CONFIG[currentView].message);
    } else if (!VIEW_CONFIG[currentView].isStatic) {
      const config = VIEW_CONFIG[currentView];
      fetchUISchema(config.message, config.genUIFunction || 'marketing-genui');
    }
  }, [currentView]);

  // 处理GenUI组件的action
  const handleAction = useCallback((action: string, params?: Record<string, unknown>) => {
    if (action === 'navigate' && params?.path) {
      onNavigate?.(params.path as string);
      return;
    }
    if (action === 'refresh') {
      sendToMarketingAI(VIEW_CONFIG[currentView].message);
      return;
    }
    const actionMessage = params 
      ? `执行操作: ${action}, 参数: ${JSON.stringify(params)}`
      : `执行操作: ${action}`;
    sendToMarketingAI(actionMessage);
  }, [currentView, onNavigate]);

  const renderContext: RenderContext = { onAction: handleAction, theme: 'light' };

  // 切换视图
  const handleViewClick = (view: ViewType) => {
    setCurrentView(view);
    if (!VIEW_CONFIG[view].isStatic && view !== 'dashboard') {
      setIsLoading(true);
      sendToMarketingAI(VIEW_CONFIG[view].message);
    }
  };

  // 洞察点击处理
  const handleInsightClick = (insight: UnifiedInsight) => {
    const content = `${insight.title} ${insight.description}`.toLowerCase();
    if (content.includes('优惠券')) handleViewClick('coupons');
    else if (content.includes('活动')) handleViewClick('campaigns');
    else if (content.includes('秒杀')) handleViewClick('flash_sales');
  };

  const handleInsightAction = (insightId: string, action: string) => {
    toast.info(`执行操作: ${action}`);
  };

  // 判断是否是会员相关视图
  const isMembershipView = currentView.startsWith('membership');

  // 渲染Dashboard视图
  const renderDashboardView = () => (
    <div className="space-y-4 h-full flex flex-col">
      <CompletedTasksDialog open={executedDialogOpen} onOpenChange={setExecutedDialogOpen} />

      {/* 顶部状态栏 */}
      <div className="grid grid-cols-12 gap-4">
        <div className="col-span-5">
          <GenericAgentDashboard agentType="marketing" onSettingsClick={() => setAgentSettingsOpen(true)} />
        </div>
        <div className="col-span-7">
          {goalData ? (
            <GenericGoalCard goal={goalData} />
          ) : (
            <Card className="h-full flex items-center justify-center">
              <CardContent className="text-muted-foreground text-sm">
                {goalsLoading ? '加载目标中...' : '暂无目标，请店长设定'}
              </CardContent>
            </Card>
          )}
        </div>
      </div>

      {/* GenUI 数据概览和图表 */}
      {isLoading ? (
        <WorkbenchSkeleton />
      ) : uiSchema ? (
        <DynamicRenderer
          schema={uiSchema}
          context={renderContext}
          className="animate-in fade-in-50 duration-300"
        />
      ) : null}

      {/* 主工作区：洞察 + 待审批 */}
      <div className="flex-1 grid grid-cols-12 gap-4 min-h-0">
        <div className="col-span-7 min-h-0">
          <UnifiedInsightFeed
            title="营销洞察"
            insights={insights}
            loading={insightsLoading}
            height="100%"
            onAction={handleInsightAction}
            onClick={handleInsightClick}
            onRefresh={fetchInsights}
            emptyText="暂无洞察"
            emptySubText="点击刷新获取AI分析"
          />
        </div>
        <div className="col-span-5 min-h-0">
          <GenericPendingApprovals
            approvals={pendingApprovals}
            onApprove={handleApproveAll}
            onReject={handleRejectAll}
          />
        </div>
      </div>

      <AgentSettingsDialog open={agentSettingsOpen} onOpenChange={setAgentSettingsOpen} agentType="marketing" />
    </div>
  );

  // 渲染GenUI视图
  const renderGenUIView = () => (
    <div className="h-full overflow-auto">
      {isLoading ? (
        <WorkbenchSkeleton />
      ) : error ? (
        <Card className="border-destructive">
          <CardContent className="p-6 text-center">
            <p className="text-destructive mb-4">{error}</p>
            <Button onClick={() => handleViewClick(currentView)}>重试</Button>
          </CardContent>
        </Card>
      ) : uiSchema ? (
        <DynamicRenderer schema={uiSchema} context={renderContext} className="animate-in fade-in-50 duration-300" />
      ) : (
        <Card>
          <CardHeader><CardTitle>等待AI响应</CardTitle></CardHeader>
          <CardContent><p className="text-muted-foreground">请使用右侧AI助手或点击上方按钮开始</p></CardContent>
        </Card>
      )}
    </div>
  );

  return (
    <div className="flex flex-col h-full">
      {/* 导航栏 */}
      <div className="flex items-center justify-between px-4 py-2 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
        <div className="inline-flex items-center rounded-lg border bg-muted/50 p-0.5">
          {MAIN_NAV_ITEMS.map((key) => {
            const config = VIEW_CONFIG[key];
            return (
              <button
                key={key}
                onClick={() => handleViewClick(key)}
                disabled={isLoading && currentView !== 'dashboard'}
                className={`
                  inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-md transition-all
                  disabled:opacity-50 disabled:cursor-not-allowed
                  ${currentView === key || (key === 'membership' && isMembershipView)
                    ? 'bg-primary text-primary-foreground shadow-sm' 
                    : 'text-muted-foreground hover:text-foreground hover:bg-muted'
                  }
                `}
              >
                {config.icon}
                <span className="hidden sm:inline">{config.label}</span>
              </button>
            );
          })}
        </div>
        
        <button
          onClick={() => currentView === 'dashboard' ? fetchInsights() : handleViewClick(currentView)}
          disabled={isLoading || insightsLoading}
          className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50"
        >
          <RefreshCw className={`h-4 w-4 ${(isLoading || insightsLoading) ? 'animate-spin' : ''}`} />
          <span className="hidden sm:inline">刷新</span>
        </button>
      </div>

      {/* 会员子导航 */}
      {isMembershipView && (
        <div className="flex items-center gap-2 px-4 py-2 border-b bg-muted/30">
          <span className="text-xs text-muted-foreground mr-2">会员储值:</span>
          {MEMBERSHIP_NAV_ITEMS.map((key) => {
            const config = VIEW_CONFIG[key];
            return (
              <button
                key={key}
                onClick={() => handleViewClick(key)}
                disabled={isLoading}
                className={`
                  inline-flex items-center gap-1 px-2 py-1 text-xs font-medium rounded transition-all
                  disabled:opacity-50 disabled:cursor-not-allowed
                  ${currentView === key 
                    ? 'bg-primary/10 text-primary' 
                    : 'text-muted-foreground hover:text-foreground hover:bg-muted'
                  }
                `}
              >
                {config.icon}
                <span>{config.label}</span>
              </button>
            );
          })}
        </div>
      )}

      {/* 主内容区 */}
      <div className="flex-1 overflow-hidden p-4">
        {currentView === 'membership-plans' ? (
          <MembershipPlansView />
        ) : currentView === 'dashboard' ? (
          renderDashboardView()
        ) : (
          renderGenUIView()
        )}
      </div>
    </div>
  );
}

export default MarketingWorkbench;
