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

import React, { 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 { supabase } from '@/integrations/supabase/client';
import { DynamicRenderer } from '@/ai/genui';
import type { UISchema, RenderContext } from '@/ai/genui/types';
import { MembershipPlansView } from './MembershipPlansView';
import { FinanceOrdersView } from './FinanceOrdersView';
import { 
  LayoutDashboard, 
  Receipt, 
  RefreshCw, 
  HelpCircle,
  BarChart3,
  Undo2,
  Wallet,
  CreditCard,
  Users,
  History
} from 'lucide-react';
import { toast } from 'sonner';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { subscribeToWorkbench, hasCachedSchema, 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 subscribeToFinanceAIMessage = (callback: AIMessageListener) => {
  aiMessageListeners.add(callback);
  return () => aiMessageListeners.delete(callback);
};

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

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

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

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

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

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

type ViewType = 'dashboard' | 'orders' | 'refunds' | 'analytics' | 'help' | 'membership' | 'membership-balances' | 'membership-transactions' | 'membership-plans';

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 },
  orders: { label: '收款管理', icon: <Receipt className="h-4 w-4" />, message: '', isStatic: true },
  refunds: { label: '退款审批', icon: <Undo2 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: '显示会员储值概览' },
  'membership-balances': { label: '会员余额', icon: <Users className="h-4 w-4" />, message: '显示会员余额列表' },
  'membership-transactions': { label: '交易记录', icon: <History className="h-4 w-4" />, message: '显示储值交易记录' },
  'membership-plans': { label: '充值套餐', icon: <CreditCard className="h-4 w-4" />, message: '', isStatic: true },
  help: { label: '帮助', icon: <HelpCircle className="h-4 w-4" />, message: '显示财务操作帮助指南' },
};

// 主导航项
const MAIN_NAV_ITEMS: ViewType[] = ['dashboard', 'orders', 'refunds', 'analytics', 'membership', 'help'];

// 将 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 FinanceWorkbench({ onNavigate, defaultView = 'dashboard' }: FinanceWorkbenchProps) {
  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); // 跟踪是否从 chatbot 收到了 schema
  
  // AI洞察状态
  const [insights, setInsights] = useState<UnifiedInsight[]>([]);
  const [insightsLoading, setInsightsLoading] = useState(false);
  
  // 获取目标数据
  const { primaryGoal, loading: goalsLoading } = useGoals('finance');
  const goalData = convertGoalToGoalData(primaryGoal);
  
  const queryClient = useQueryClient();

  // 获取待审批退款请求
  const { data: pendingApprovals = [] } = useQuery({
    queryKey: ['finance-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')
        .eq('type', 'refund')
        .order('created_at', { ascending: false });

      if (error) throw error;

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

      return Object.entries(typeGroups).map(([type, items]): PendingApprovalItem => ({
        id: items[0].id,
        type: 'refund_batch',
        title: '退款申请',
        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', 'refund');
      if (error) throw error;
      queryClient.invalidateQueries({ queryKey: ['finance-pending-approvals'] });
      toast.success('已批量批准退款');
    } catch (error) {
      console.error('Error approving refunds:', 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', 'refund');
      if (error) throw error;
      queryClient.invalidateQueries({ queryKey: ['finance-pending-approvals'] });
      toast.info('已批量拒绝退款');
    } catch (error) {
      console.error('Error rejecting refunds:', 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('finance-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,
          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, view?: ViewType) => {
    setIsLoading(true);
    setError(null);

    const targetView = view || currentView;

    try {
      const { data: { session } } = await supabase.auth.getSession();
      
      const { data, error: fnError } = await supabase.functions.invoke('finance-genui', {
        body: { message, view: targetView },
        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('finance', (schema) => {
      schemaFromChatbotRef.current = true; // 标记收到了 chatbot 的 schema
      setUiSchema(schema);
      setIsLoading(false);
      setError(null);
      // 切换到 dashboard 视图以显示 GenUI 内容
      setCurrentView('dashboard');
      console.log('[FinanceWorkbench] Received UI schema from Chatbot, switching to dashboard view');
    });
    return () => { 
      unsubscribe(); 
      // 组件卸载时清除缓存，避免下次挂载时重复使用旧数据
      clearWorkbenchCache('finance');
      schemaFromChatbotRef.current = false;
    };
  }, []);

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

  // 洞察点击处理
  const handleInsightClick = (insight: UnifiedInsight) => {
    const content = `${insight.title} ${insight.description}`.toLowerCase();
    if (content.includes('退款')) handleViewClick('refunds');
    else if (content.includes('收款')) handleViewClick('orders');
    else if (content.includes('会员')) handleViewClick('membership');
  };

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

  // 判断当前是否在会员管理子视图中
  const isInMembershipSubview = currentView.startsWith('membership');
  const activeMainNav = isInMembershipSubview ? 'membership' : currentView;

  // 渲染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="finance" 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
            title="待审批退款"
            approvals={pendingApprovals}
            onApprove={handleApproveAll}
            onReject={handleRejectAll}
          />
        </div>
      </div>

      <AgentSettingsDialog open={agentSettingsOpen} onOpenChange={setAgentSettingsOpen} agentType="finance" />
    </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
                  ${activeMainNav === 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 || VIEW_CONFIG[currentView].isStatic}
          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>

      {/* 会员管理子导航 */}
      {isInMembershipSubview && (
        <div className="flex items-center gap-2 px-4 py-2 border-b bg-muted/30">
          <span className="text-sm text-muted-foreground">会员管理:</span>
          {(['membership', 'membership-balances', 'membership-transactions', 'membership-plans'] as ViewType[]).map((key) => {
            const config = VIEW_CONFIG[key];
            const isActive = currentView === 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
                  ${isActive
                    ? 'bg-primary/10 text-primary border border-primary/20'
                    : 'text-muted-foreground hover:text-foreground hover:bg-muted'
                  }
                `}
              >
                {config.icon}
                {key === 'membership' ? '概览' : config.label}
              </button>
            );
          })}
        </div>
      )}

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

export default FinanceWorkbench;
