/**
 * 商品工作台 - 统一入口
 * 合并了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, Bot, Package, FolderTree, Tag, BarChart3, HelpCircle } from 'lucide-react';
import { ProductsManager } from '../ProductsManager';
import { CategoriesManager } from '../CategoriesManager';
import { BrandsManager } from '../BrandsManager';
import { supabase } from '@/integrations/supabase/client';
import { DynamicRenderer } from '@/ai/genui';
import type { UISchema, RenderContext } from '@/ai/genui/types';
import { toast } from 'sonner';
import { subscribeToWorkbench, clearWorkbenchCache } from '@/services/workbenchEventBus';
import { useQuery, useQueryClient } from '@tanstack/react-query';
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 subscribeToProductAIMessage = (callback: AIMessageListener) => {
  aiMessageListeners.add(callback);
  return () => aiMessageListeners.delete(callback);
};

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

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

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

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

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

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

type ViewType = 'dashboard' | 'products' | 'categories' | 'brands' | 'analytics' | 'help';

const VIEW_CONFIG: Record<ViewType, { label: string; icon: React.ReactNode; message: string; isStatic?: boolean; isDashboard?: boolean }> = {
  dashboard: { label: '工作台', icon: <Bot className="h-4 w-4" />, message: '显示商品工作台概览', isDashboard: true },
  products: { label: '商品管理', icon: <Package className="h-4 w-4" />, message: '', isStatic: true },
  categories: { label: '分类管理', icon: <FolderTree className="h-4 w-4" />, message: '', isStatic: true },
  brands: { label: '品牌管理', icon: <Tag className="h-4 w-4" />, message: '', isStatic: true },
  analytics: { label: '数据分析', icon: <BarChart3 className="h-4 w-4" />, message: '显示商品数据分析' },
  help: { label: '帮助', icon: <HelpCircle className="h-4 w-4" />, message: '显示商品操作帮助指南' },
};

// 将 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 ProductWorkbench({ onNavigate, defaultView = 'dashboard' }: ProductWorkbenchProps) {
  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('product');
  const goalData = convertGoalToGoalData(primaryGoal);
  
  const queryClient = useQueryClient();

  // 获取待审批商品请求
  const { data: pendingApprovals = [] } = useQuery({
    queryKey: ['product-pending-approvals'],
    queryFn: async () => {
      // 暂时返回空数组，可以根据业务需求添加审批逻辑
      const approvals: PendingApprovalItem[] = [];
      return approvals;
    }
  });

  // 审批操作
  const handleApproveAll = async (type: string) => {
    toast.success('已批量批准');
    queryClient.invalidateQueries({ queryKey: ['product-pending-approvals'] });
  };

  const handleRejectAll = async (type: string) => {
    toast.info('已批量拒绝');
    queryClient.invalidateQueries({ queryKey: ['product-pending-approvals'] });
  };

  // 获取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('product-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,
          time: insight.time || '刚刚'
        })));
      }
    } catch (error) {
      console.error('Failed to fetch insights:', error);
    } finally {
      setInsightsLoading(false);
    }
  }, []);

  // 获取GenUI Schema
  const fetchUISchema = useCallback(async (message: string) => {
    setIsLoading(true);
    setError(null);

    try {
      const { data: { session } } = await supabase.auth.getSession();
      
      const { data, error: fnError } = await supabase.functions.invoke('product-genui', {
        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('product', (schema) => {
      schemaFromChatbotRef.current = true;
      setUiSchema(schema);
      setIsLoading(false);
      setError(null);
      console.log('[ProductWorkbench] Received UI schema from Chatbot');
    });
    return () => { 
      unsubscribe(); 
      clearWorkbenchCache('product');
      schemaFromChatbotRef.current = false;
    };
  }, []);

  // 初始加载 - 仅当没有从 chatbot 收到 schema 时才执行
  useEffect(() => {
    if (schemaFromChatbotRef.current) {
      console.log('[ProductWorkbench] Skipping initial fetch - schema received from Chatbot');
      return;
    }
    
    if (currentView === 'dashboard') {
      fetchInsights();
      fetchUISchema(VIEW_CONFIG[currentView].message);
    } else if (!VIEW_CONFIG[currentView].isStatic) {
      fetchUISchema(VIEW_CONFIG[currentView].message);
    }
  }, [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') {
      sendToProductAI(VIEW_CONFIG[currentView].message);
      return;
    }
    const actionMessage = params 
      ? `执行操作: ${action}, 参数: ${JSON.stringify(params)}`
      : `执行操作: ${action}`;
    sendToProductAI(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);
      sendToProductAI(VIEW_CONFIG[view].message);
    }
  };

  // 洞察点击处理
  const handleInsightClick = (insight: UnifiedInsight) => {
    const content = `${insight.title} ${insight.description}`.toLowerCase();
    if (content.includes('库存')) handleViewClick('products');
    else if (content.includes('分类')) handleViewClick('categories');
    else if (content.includes('品牌')) handleViewClick('brands');
  };

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

  // 渲染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="product" 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="product" />
    </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>
  );

  // 渲染静态页面
  const renderStaticView = () => {
    switch (currentView) {
      case 'products':
        return <ProductsManager />;
      case 'categories':
        return <CategoriesManager />;
      case 'brands':
        return <BrandsManager />;
      default:
        return null;
    }
  };

  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">
          {(Object.entries(VIEW_CONFIG) as [ViewType, typeof VIEW_CONFIG[ViewType]][]).map(([key, config]) => (
            <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 
                  ? '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>

      {/* 主内容区 */}
      <div className="flex-1 overflow-hidden p-4">
        {VIEW_CONFIG[currentView].isStatic ? renderStaticView() : 
         currentView === 'dashboard' ? renderDashboardView() : 
         renderGenUIView()}
      </div>
    </div>
  );
}

export default ProductWorkbench;
