import { useState, useEffect, useMemo, useCallback } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { 
  DollarSign, 
  TrendingUp, 
  Receipt,
  CreditCard
} from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import { FinanceAgentStatusBar } from "./FinanceAgentStatusBar";
import { FinanceGoalCard, FinanceGoal } from "./FinanceGoalCard";
import { UnifiedInsightFeed, UnifiedInsight, CompletedTasksDialog } from "../shared";
import { FinancePendingApprovals, FinancePendingApproval } from "./FinancePendingApprovals";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { AgentSettingsDialog } from "../team";

interface FinanceAICockpitProps {
  onOpenSettings?: (agentType: string) => void;
  onNavigate?: (tab: string) => void;
}

export function FinanceAICockpit({ onOpenSettings, onNavigate }: FinanceAICockpitProps) {
  const [stats, setStats] = useState({
    totalRevenue: 0,
    todayRevenue: 0,
    monthRevenue: 0,
    averageOrderValue: 0,
    revenueGrowth: 0,
    pendingSettlement: 0
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchFinanceStats();
  }, []);

  const fetchFinanceStats = async () => {
    try {
      const { data: ordersData } = await supabase
        .from("orders")
        .select("total_amount, status, created_at");

      if (ordersData) {
        const today = new Date().toISOString().split('T')[0];
        const monthStart = new Date();
        monthStart.setDate(1);
        const lastMonthStart = new Date(monthStart);
        lastMonthStart.setMonth(lastMonthStart.getMonth() - 1);
        
        const totalRevenue = ordersData.reduce((sum, order) => sum + order.total_amount, 0);
        const todayRevenue = ordersData
          .filter(order => order.created_at.startsWith(today))
          .reduce((sum, order) => sum + order.total_amount, 0);
        const monthRevenue = ordersData
          .filter(order => new Date(order.created_at) >= monthStart)
          .reduce((sum, order) => sum + order.total_amount, 0);
        const lastMonthRevenue = ordersData
          .filter(order => {
            const date = new Date(order.created_at);
            return date >= lastMonthStart && date < monthStart;
          })
          .reduce((sum, order) => sum + order.total_amount, 0);
        
        const pendingSettlement = ordersData
          .filter(order => order.status === 'delivered')
          .reduce((sum, order) => sum + order.total_amount, 0);
        
        const revenueGrowth = lastMonthRevenue > 0 
          ? ((monthRevenue - lastMonthRevenue) / lastMonthRevenue) * 100 
          : 0;

        setStats({
          totalRevenue,
          todayRevenue,
          monthRevenue,
          averageOrderValue: ordersData.length > 0 ? totalRevenue / ordersData.length : 0,
          revenueGrowth,
          pendingSettlement
        });
      }
    } catch (error) {
      console.error("Error fetching finance stats:", error);
    } finally {
      setLoading(false);
    }
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0
    }).format(amount);
  };

  // 经理目标
  const managerGoal: FinanceGoal = {
    id: "1",
    title: "本月营收目标",
    description: "完成本月营收目标，确保现金流稳定，及时处理结算",
    targetValue: 100000,
    currentValue: stats.monthRevenue,
    unit: "元",
    deadline: new Date(Date.now() + 1000 * 60 * 60 * 24 * 18),
    assignedBy: "经理AI · 小管",
    priority: "high"
  };

  // 财务洞察 - 从AI获取
  const [insights, setInsights] = useState<UnifiedInsight[]>([]);
  const [insightsLoading, setInsightsLoading] = useState(false);

  const fetchInsights = useCallback(async () => {
    setInsightsLoading(true);
    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) {
        toast.error("请先登录");
        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) {
        const formattedInsights = data.insights.map((insight: any) => ({
          ...insight,
          timestamp: new Date(insight.timestamp)
        }));
        setInsights(formattedInsights);
        toast.success(`AI生成了 ${formattedInsights.length} 条财务洞察`);
      } else if (data?.error) {
        toast.error(`获取洞察失败: ${data.error}`);
      }
    } catch (error) {
      console.error('Failed to fetch insights:', error);
      toast.error("获取AI洞察失败");
    } finally {
      setInsightsLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchInsights();
  }, [fetchInsights]);

  // 待审批事项 - 从数据库获取真实数据
  const queryClient = useQueryClient();
  
  const { data: pendingApprovals = [], isLoading: approvalsLoading } = useQuery({
    queryKey: ['finance-pending-approvals'],
    queryFn: async () => {
      // 获取待处理的售后退款请求
      const { data: afterSalesData, error: afterSalesError } = await supabase
        .from('after_sales_requests')
        .select(`
          id,
          type,
          reason,
          description,
          refund_amount,
          status,
          created_at,
          order_id,
          product_id,
          products:product_id (name)
        `)
        .eq('status', 'pending')
        .order('created_at', { ascending: false });

      if (afterSalesError) {
        console.error('Error fetching after sales requests:', afterSalesError);
        throw afterSalesError;
      }

      // 转换为财务审批格式
      const approvals: FinancePendingApproval[] = (afterSalesData || []).map((item: any) => ({
        id: item.id,
        type: 'refund' as const,
        title: item.type === 'refund' ? '退款申请' : item.type === 'return' ? '退货退款' : '换货申请',
        amount: item.refund_amount || 0,
        reason: `${item.products?.name || '商品'} - ${item.reason}: ${item.description}`,
        aiConfidence: Math.floor(Math.random() * 20) + 80, // 模拟AI置信度
        priority: (Date.now() - new Date(item.created_at).getTime() > 24 * 60 * 60 * 1000) ? 'urgent' as const : 'normal' as const,
        createdAt: new Date(item.created_at)
      }));

      return approvals;
    }
  });

  // 获取已处理的售后请求数量
  const { data: executedCount = 0 } = useQuery({
    queryKey: ['finance-executed-count'],
    queryFn: async () => {
      const { count, error } = await supabase
        .from('after_sales_requests')
        .select('*', { count: 'exact', head: true })
        .in('status', ['approved', 'rejected']);
      
      if (error) {
        console.error('Error fetching executed count:', error);
        return 0;
      }
      return count || 0;
    }
  });

  const agentStats = useMemo(() => ({
    insightCount: insights.length,
    pendingCount: pendingApprovals.length,
    executedCount: executedCount
  }), [insights, pendingApprovals, executedCount]);

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

  // 根据洞察内容确定跳转目标
  const getInsightTargetTab = (insight: UnifiedInsight): string | null => {
    const { title, description } = insight;
    const content = `${title} ${description}`.toLowerCase();
    
    // 根据内容关键词跳转
    if (content.includes('订单') || content.includes('发货') || content.includes('物流')) {
      return 'transactions';
    }
    if (content.includes('退款') || content.includes('售后')) {
      return 'aftersales';
    }
    if (content.includes('营销') || content.includes('活动') || content.includes('优惠')) {
      return 'marketing';
    }
    if (content.includes('商品') || content.includes('库存')) {
      return 'products';
    }
    
    return 'transactions'; // 财务相关默认跳转到财务室
  };

  const handleInsightClick = (insight: UnifiedInsight) => {
    const targetTab = getInsightTargetTab(insight);
    if (targetTab && onNavigate) {
      onNavigate(targetTab);
      toast.info(`跳转到: ${targetTab === 'transactions' ? '财务室' : targetTab === 'aftersales' ? '客服室' : targetTab === 'marketing' ? '营销部' : '商品部'}`);
    } else {
      toast.info(`查看: ${insight.title}`);
    }
  };

  const handleApprove = async (id: string) => {
    try {
      const { error } = await supabase
        .from('after_sales_requests')
        .update({ 
          status: 'approved',
          processed_at: new Date().toISOString()
        })
        .eq('id', id);
      
      if (error) throw error;
      
      queryClient.invalidateQueries({ queryKey: ['finance-pending-approvals'] });
      toast.success('已批准退款申请');
    } catch (error) {
      console.error('Error approving request:', error);
      toast.error('操作失败');
    }
  };

  const handleReject = async (id: string) => {
    try {
      const { error } = await supabase
        .from('after_sales_requests')
        .update({ 
          status: 'rejected',
          processed_at: new Date().toISOString()
        })
        .eq('id', id);
      
      if (error) throw error;
      
      queryClient.invalidateQueries({ queryKey: ['finance-pending-approvals'] });
      toast.info('已拒绝退款申请');
    } catch (error) {
      console.error('Error rejecting request:', error);
      toast.error('操作失败');
    }
  };

  const [settingsOpen, setSettingsOpen] = useState(false);
  const [executedDialogOpen, setExecutedDialogOpen] = useState(false);

  return (
    <div className="space-y-6">
      {/* Agent Settings Dialog */}
      <AgentSettingsDialog 
        open={settingsOpen} 
        onOpenChange={setSettingsOpen}
        agentType="finance"
      />

      {/* 已处理任务弹窗 */}
      <CompletedTasksDialog 
        open={executedDialogOpen} 
        onOpenChange={setExecutedDialogOpen}
      />

      {/* 经理目标卡片 */}
      <FinanceGoalCard goal={managerGoal} />

      {/* Agent状态栏 */}
      <FinanceAgentStatusBar
        status="running"
        insightCount={agentStats.insightCount}
        pendingCount={agentStats.pendingCount}
        executedCount={agentStats.executedCount}
        onSettingsClick={() => onOpenSettings ? onOpenSettings('finance') : setSettingsOpen(true)}
        onExecutedClick={() => setExecutedDialogOpen(true)}
      />

      {/* 主内容区：洞察流 + 待审批 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <UnifiedInsightFeed
          title="财务洞察"
          insights={insights}
          loading={insightsLoading}
          height="280px"
          onAction={handleInsightAction}
          onClick={handleInsightClick}
          onRefresh={fetchInsights}
        />
        
        <FinancePendingApprovals
          approvals={pendingApprovals}
          onApprove={handleApprove}
          onReject={handleReject}
        />
      </div>

      {/* 关键指标卡片 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-lg bg-emerald-500/10 flex items-center justify-center">
                <DollarSign className="h-5 w-5 text-emerald-500" />
              </div>
              <div>
                <p className="text-2xl font-bold">{formatCurrency(stats.todayRevenue)}</p>
                <p className="text-xs text-muted-foreground">今日营收</p>
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-lg bg-blue-500/10 flex items-center justify-center">
                <TrendingUp className="h-5 w-5 text-blue-500" />
              </div>
              <div>
                <p className="text-2xl font-bold">{formatCurrency(stats.monthRevenue)}</p>
                <p className="text-xs text-muted-foreground">本月营收</p>
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-lg bg-amber-500/10 flex items-center justify-center">
                <CreditCard className="h-5 w-5 text-amber-500" />
              </div>
              <div>
                <p className="text-2xl font-bold">{formatCurrency(stats.pendingSettlement)}</p>
                <p className="text-xs text-muted-foreground">待结算</p>
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-lg bg-purple-500/10 flex items-center justify-center">
                <Receipt className="h-5 w-5 text-purple-500" />
              </div>
              <div>
                <p className="text-2xl font-bold">{formatCurrency(stats.averageOrderValue)}</p>
                <p className="text-xs text-muted-foreground">平均客单</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
