import React, { useState, useMemo } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Progress } from "@/components/ui/progress";
import { 
  TrendingUp, TrendingDown, DollarSign, Users, Target, Zap, 
  ArrowRight, CheckCircle, AlertTriangle, BarChart3, PieChart,
  Calendar, Clock, Award, Shield, Sparkles, ArrowUpRight,
  Building2, Briefcase, Package, RefreshCw, Download, Filter, Wallet, Brain
} from "lucide-react";
import PageHeader from "@/components/common/PageHeader";
import SavingsOverviewCards from "@/components/savings/SavingsOverviewCards";
import ContractConversionMap from "@/components/savings/ContractConversionMap";
import PredictiveSavingsModel from "@/components/savings/PredictiveSavingsModel";
import DynamicSavingsDashboard from "@/components/savings/DynamicSavingsDashboard";
import LaborSpendAnalysis from "@/components/savings/LaborSpendAnalysis";
import VendorPerformanceMatrix from "@/components/savings/VendorPerformanceMatrix";
import BudgetUtilizationTracker from "@/components/budget/BudgetUtilizationTracker";
import SmartOperationStrategies from "@/components/vendor/SmartOperationStrategies";

export default function SavingsEngine() {
  const [activeTab, setActiveTab] = useState("overview");
  const [timeRange, setTimeRange] = useState("30days");

  const { data: user } = useQuery({
    queryKey: ['current-user-savings'],
    queryFn: () => base44.auth.me(),
  });

  const { data: assignments = [] } = useQuery({
    queryKey: ['assignments-savings'],
    queryFn: () => base44.entities.Assignment.list(),
    initialData: [],
  });

  const { data: vendors = [] } = useQuery({
    queryKey: ['vendors-savings'],
    queryFn: () => base44.entities.Vendor.list(),
    initialData: [],
  });

  const { data: workforce = [] } = useQuery({
    queryKey: ['workforce-savings'],
    queryFn: () => base44.entities.Workforce.list(),
    initialData: [],
  });

  const { data: orders = [] } = useQuery({
    queryKey: ['orders-savings'],
    queryFn: () => base44.entities.Order.list(),
    initialData: [],
  });

  const { data: rates = [] } = useQuery({
    queryKey: ['rates-savings'],
    queryFn: () => base44.entities.VendorRate.list(),
    initialData: [],
  });

  const userRole = user?.user_role || user?.role || "admin";

  // Calculate comprehensive metrics
  const metrics = useMemo(() => {
    const totalSpend = assignments.reduce((sum, a) => sum + (a.total_bill || 0), 0);
    const contractedSpend = assignments.filter(a => a.vendor_id).reduce((sum, a) => sum + (a.total_bill || 0), 0);
    const nonContractedSpend = totalSpend - contractedSpend;
    const contractedRatio = totalSpend > 0 ? (contractedSpend / totalSpend) * 100 : 0;

    // Calculate average rates
    const avgContractedRate = rates.filter(r => r.is_approved_rate).reduce((sum, r) => sum + (r.client_rate || 0), 0) / Math.max(rates.filter(r => r.is_approved_rate).length, 1);
    const avgNonContractedRate = rates.filter(r => !r.is_approved_rate).reduce((sum, r) => sum + (r.client_rate || 0), 0) / Math.max(rates.filter(r => !r.is_approved_rate).length, 1);
    
    // Potential savings from conversion
    const potentialSavingsPercent = avgNonContractedRate > avgContractedRate ? ((avgNonContractedRate - avgContractedRate) / avgNonContractedRate) * 100 : 15;
    const potentialSavings = nonContractedSpend * (potentialSavingsPercent / 100);

    // Performance metrics
    const avgReliability = workforce.reduce((sum, w) => sum + (w.reliability_index || 75), 0) / Math.max(workforce.length, 1);
    const noShowRate = workforce.reduce((sum, w) => sum + (w.no_shows || 0), 0) / Math.max(workforce.reduce((sum, w) => sum + (w.total_assignments || 1), 0), 1) * 100;
    const fillRate = assignments.filter(a => a.assignment_status === "Completed").length / Math.max(assignments.length, 1) * 100;

    return {
      totalSpend,
      contractedSpend,
      nonContractedSpend,
      contractedRatio,
      potentialSavings,
      potentialSavingsPercent,
      avgContractedRate: avgContractedRate || 45,
      avgNonContractedRate: avgNonContractedRate || 55,
      avgReliability,
      noShowRate,
      fillRate,
      activeVendors: vendors.filter(v => v.is_active).length,
      totalWorkforce: workforce.length,
      completedOrders: orders.filter(o => o.order_status === "Completed").length,
    };
  }, [assignments, vendors, workforce, orders, rates]);

  // Generate savings projections
  const projections = useMemo(() => {
    const dailySavings = metrics.potentialSavings / 30;
    return {
      sevenDays: dailySavings * 7,
      thirtyDays: metrics.potentialSavings,
      quarter: metrics.potentialSavings * 3,
      year: metrics.potentialSavings * 12,
    };
  }, [metrics]);

  const getRoleSpecificTitle = () => {
    switch (userRole) {
      case "procurement": return "Vendor Network Intelligence";
      case "operator": return "Workforce Optimization Hub";
      case "sector": return "Staffing Performance Center";
      case "client": return "Smart Staffing Savings";
      case "vendor": return "Your Competitive Edge";
      default: return "Workforce Optimization Engine";
    }
  };

  const getRoleSpecificSubtitle = () => {
    switch (userRole) {
      case "procurement": return "Consolidate vendors, optimize rates, and strengthen your preferred network";
      case "operator": return "Maximize utilization, reduce costs, and streamline vendor relationships";
      case "sector": return "Improve coverage, boost reliability, and optimize staffing costs";
      case "client": return "Get better rates by leveraging the Preferred Vendor Network";
      case "vendor": return "Showcase your performance metrics and win more business";
      default: return "Consolidate spend, optimize rates, and maximize vendor performance";
    }
  };

  // Get role-specific tabs
  const getRoleTabs = () => {
    switch (userRole) {
      case "procurement":
        return [
          { value: "overview", label: "Network Overview", icon: BarChart3 },
          { value: "budget", label: "Budget Control", icon: Wallet },
          { value: "strategies", label: "Operation Strategies", icon: Brain },
          { value: "vendors", label: "Vendor Scorecard", icon: Package },
          { value: "predictions", label: "Rate Analysis", icon: TrendingUp },
          { value: "conversion", label: "Tier Optimization", icon: Target },
        ];
      case "operator":
        return [
          { value: "overview", label: "Enterprise View", icon: BarChart3 },
          { value: "budget", label: "Budget Tracker", icon: Wallet },
          { value: "strategies", label: "Smart Strategies", icon: Brain },
          { value: "labor", label: "Labor Efficiency", icon: Users },
          { value: "predictions", label: "Cost Forecasts", icon: TrendingUp },
          { value: "vendors", label: "Vendor Mix", icon: Package },
        ];
      case "sector":
        return [
          { value: "overview", label: "Location Dashboard", icon: BarChart3 },
          { value: "budget", label: "Site Budget", icon: Wallet },
          { value: "strategies", label: "Optimization", icon: Brain },
          { value: "labor", label: "Staff Coverage", icon: Users },
          { value: "predictions", label: "Scheduling", icon: Calendar },
        ];
      case "client":
        return [
          { value: "overview", label: "My Events", icon: BarChart3 },
          { value: "budget", label: "My Budget", icon: Wallet },
          { value: "strategies", label: "Cost Strategies", icon: Brain },
          { value: "predictions", label: "Cost Savings", icon: TrendingUp },
          { value: "vendors", label: "Vendor Options", icon: Package },
        ];
      case "vendor":
        return [
          { value: "overview", label: "My Performance", icon: BarChart3 },
          { value: "budget", label: "Revenue Tracker", icon: Wallet },
          { value: "strategies", label: "Growth Strategies", icon: Brain },
          { value: "labor", label: "Workforce Stats", icon: Users },
          { value: "predictions", label: "Growth Opportunities", icon: TrendingUp },
        ];
      default:
        return [
          { value: "overview", label: "Overview", icon: BarChart3 },
          { value: "budget", label: "Budget Intelligence", icon: Wallet },
          { value: "strategies", label: "Smart Strategies", icon: Brain },
          { value: "conversion", label: "Conversion Map", icon: Target },
          { value: "predictions", label: "Predictions", icon: TrendingUp },
          { value: "labor", label: "Labor Analysis", icon: Users },
          { value: "vendors", label: "Vendor Matrix", icon: Package },
        ];
    }
  };

  const roleTabs = getRoleTabs();

  return (
    <div className="p-4 md:p-8 bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/20 min-h-screen">
      <div className="max-w-[1800px] mx-auto">
        <PageHeader
          title={getRoleSpecificTitle()}
          subtitle={getRoleSpecificSubtitle()}
          actions={
            <div className="flex items-center gap-2">
              <Button variant="outline" size="sm" onClick={() => window.print()}>
                <Download className="w-4 h-4 mr-2" />
                Export Report
              </Button>
              <Button size="sm" className="bg-[#0A39DF] hover:bg-[#0831b8]" onClick={() => window.location.reload()}>
                <Sparkles className="w-4 h-4 mr-2" />
                Run Analysis
              </Button>
            </div>
          }
        />

        {/* Time Range Selector */}
        <div className="flex items-center gap-2 mb-6">
          <span className="text-sm text-slate-500 font-medium">Analyze:</span>
          {[
            { value: "7days", label: "7 Days" },
            { value: "30days", label: "30 Days" },
            { value: "quarter", label: "Quarter" },
            { value: "year", label: "Year" },
          ].map((range) => (
            <Button
              key={range.value}
              variant={timeRange === range.value ? "default" : "outline"}
              size="sm"
              onClick={() => setTimeRange(range.value)}
              className={timeRange === range.value ? "bg-[#0A39DF]" : ""}
            >
              {range.label}
            </Button>
          ))}
        </div>

        {/* Overview Cards */}
        <SavingsOverviewCards metrics={metrics} projections={projections} timeRange={timeRange} userRole={userRole} />

        {/* Main Tabs - Role Specific */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="mt-8">
          <TabsList className="bg-white border border-slate-200 p-1 h-auto flex-wrap">
            {roleTabs.map((tab) => {
              const Icon = tab.icon;
              return (
                <TabsTrigger 
                  key={tab.value} 
                  value={tab.value} 
                  className="data-[state=active]:bg-[#0A39DF] data-[state=active]:text-white"
                >
                  <Icon className="w-4 h-4 mr-2" />
                  {tab.label}
                </TabsTrigger>
              );
            })}
          </TabsList>

          <TabsContent value="overview" className="mt-6">
            <DynamicSavingsDashboard 
              metrics={metrics} 
              projections={projections} 
              timeRange={timeRange}
              userRole={userRole}
            />
          </TabsContent>

          <TabsContent value="conversion" className="mt-6">
            <ContractConversionMap 
              assignments={assignments}
              vendors={vendors}
              workforce={workforce}
              metrics={metrics}
              userRole={userRole}
            />
          </TabsContent>

          <TabsContent value="predictions" className="mt-6">
            <PredictiveSavingsModel 
              metrics={metrics}
              projections={projections}
              assignments={assignments}
              rates={rates}
              userRole={userRole}
            />
          </TabsContent>

          <TabsContent value="labor" className="mt-6">
            <LaborSpendAnalysis 
              assignments={assignments}
              workforce={workforce}
              orders={orders}
              metrics={metrics}
              userRole={userRole}
            />
          </TabsContent>

          <TabsContent value="vendors" className="mt-6">
            <VendorPerformanceMatrix 
              vendors={vendors}
              assignments={assignments}
              rates={rates}
              metrics={metrics}
              userRole={userRole}
            />
          </TabsContent>

          <TabsContent value="budget" className="mt-6">
            <BudgetUtilizationTracker 
              userRole={userRole}
              events={orders}
              invoices={[]}
            />
          </TabsContent>

          <TabsContent value="strategies" className="mt-6">
            <SmartOperationStrategies 
              userRole={userRole}
              onSelectStrategy={(strategy) => console.log('Selected strategy:', strategy)}
            />
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}