/**
 * 客服工作台 - 统一入口
 * 合并了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, Package, Users, Headphones, HelpCircle
} from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { DynamicRenderer } from '@/ai/genui';
import type { UISchema, RenderContext } from '@/ai/genui/types';
import { ServiceOrdersView } from './ServiceOrdersView';
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 subscribeToAIMessage = (callback: AIMessageListener) => {
  aiMessageListeners.add(callback);
  return () => aiMessageListeners.delete(callback);
};

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

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

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

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

// ============= 类型定义 =============

interface ServiceWorkbenchProps {
  onNavigate?: (view: string) => void;
}

type ViewType = 'dashboard' | 'aftersales' | 'orders' | 'customers' | 'help';

const VIEW_CONFIG: Record<ViewType, { label: string; icon: React.ReactNode; message: string; isStatic?: boolean; isDashboard?: boolean }> = {
  dashboard: { label: '工作台', icon: <LayoutDashboard className="h-4 w-4" />, message: '显示客服工作台概览', isDashboard: true },
  aftersales: { label: '售后工单', icon: <Headphones className="h-4 w-4" />, message: '查看待处理的售后工单列表' },
  orders: { label: '订单管理', icon: <Package className="h-4 w-4" />, message: '', isStatic: true },
  customers: { label: '客户列表', icon: <Users 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'
  };
};
// WorkbenchSkeleton 骨架屏定义在下方

// 骨架屏
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 ServiceWorkbench({ onNavigate }: ServiceWorkbenchProps) {
  const [currentView, setCurrentView] = useState<ViewType>('dashboard');
  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('service');
  const goalData = convertGoalToGoalData(primaryGoal);
  
  const queryClient = useQueryClient();

  // 获取待审批售后请求
  const { data: pendingApprovals = [] } = useQuery({
    queryKey: ['service-pending-approvals'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('after_sales_requests')
        .select(`
          id, type, reason, description, refund_amount, status, created_at,
          products:product_id (name)
        `)
        .eq('status', 'pending')
        .order('created_at', { ascending: false });

      if (error) throw error;

      const typeGroups: Record<string, any[]> = {};
      (data || []).forEach(item => {
        const key = item.type;
        if (!typeGroups[key]) typeGroups[key] = [];
        typeGroups[key].push(item);
      });

      return Object.entries(typeGroups).map(([type, items]): PendingApprovalItem => ({
        id: items[0].id,
        type: type === 'refund' ? 'refund_batch' : type === 'return' ? 'return_batch' : 'other',
        title: type === 'refund' ? '退款申请' : type === 'return' ? '退货申请' : '换货申请',
        description: `${items.length}个请求待处理`,
        items: items.length,
        createdBy: 'AI',
        priority: items.some(i => Date.now() - new Date(i.created_at).getTime() > 24 * 60 * 60 * 1000) ? 'urgent' : 'normal',
        requestType: type,
        amount: items.reduce((sum, i) => sum + (i.refund_amount || 0), 0)
      }));
    }
  });

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

  const handleRejectAll = async (type: string) => {
    try {
      const { error } = await supabase
        .from('after_sales_requests')
        .update({ status: 'rejected', processed_at: new Date().toISOString() })
        .eq('status', 'pending')
        .eq('type', type);
      if (error) throw error;
      queryClient.invalidateQueries({ queryKey: ['service-pending-approvals'] });
      toast.info('已批量拒绝');
    } catch (error) {
      console.error('Error rejecting requests:', 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('service-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('service-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('service', (schema) => {
      schemaFromChatbotRef.current = true;
      setUiSchema(schema);
      setIsLoading(false);
      setError(null);
      console.log('[ServiceWorkbench] Received UI schema from Chatbot');
    });
    return () => { 
      unsubscribe(); 
      clearWorkbenchCache('service');
      schemaFromChatbotRef.current = false;
    };
  }, []);

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

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

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

  // 洞察点击处理
  const handleInsightClick = (insight: UnifiedInsight) => {
    const content = `${insight.title} ${insight.description}`.toLowerCase();
    if (content.includes('订单') || content.includes('发货')) onNavigate?.('transactions');
    else if (content.includes('营销') || content.includes('活动')) onNavigate?.('marketing');
    else if (content.includes('商品') || content.includes('库存')) onNavigate?.('products');
    else onNavigate?.('aftersales');
  };

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

  // 渲染Dashboard视图（原AI驾驶舱 + GenUI数据概览）
  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="service" 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="AI洞察"
            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="service" />
    </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">
          {(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">
        {currentView === 'orders' ? (
          <ServiceOrdersView />
        ) : currentView === 'dashboard' ? (
          renderDashboardView()
        ) : (
          renderGenUIView()
        )}
      </div>
    </div>
  );
}

export default ServiceWorkbench;
