import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import {
  DollarSign, TrendingUp, TrendingDown, AlertTriangle, CheckCircle,
  Target, Lightbulb, ArrowRight, PieChart, BarChart3, Wallet,
  Building2, Users, Package, Calendar, Zap, Brain, Shield
} from "lucide-react";

const ROLE_BUDGET_CONFIG = {
  procurement: {
    title: "Procurement Budget Control",
    color: "blue",
    metrics: ["vendor_spend", "rate_compliance", "savings_achieved"],
    focus: "Vendor rate optimization & consolidation"
  },
  operator: {
    title: "Operator Budget Overview",
    color: "emerald",
    metrics: ["sector_allocation", "labor_costs", "efficiency"],
    focus: "Cross-sector resource optimization"
  },
  sector: {
    title: "Sector Budget Allocation",
    color: "purple",
    metrics: ["site_costs", "overtime", "headcount"],
    focus: "Site-level cost management"
  },
  client: {
    title: "Your Staffing Budget",
    color: "green",
    metrics: ["order_costs", "vendor_rates", "savings"],
    focus: "Cost-effective staffing solutions"
  },
  vendor: {
    title: "Revenue & Margin Tracker",
    color: "amber",
    metrics: ["revenue", "margins", "utilization"],
    focus: "Maximize revenue & worker utilization"
  },
  admin: {
    title: "Platform Budget Intelligence",
    color: "slate",
    metrics: ["total_gmv", "platform_fees", "growth"],
    focus: "Platform-wide financial health"
  }
};

export default function BudgetUtilizationTracker({ 
  userRole = 'admin', 
  events = [], 
  invoices = [],
  budgetData = null 
}) {
  const [selectedPeriod, setSelectedPeriod] = useState("month");
  const config = ROLE_BUDGET_CONFIG[userRole] || ROLE_BUDGET_CONFIG.admin;
  
  // Calculate budget metrics
  const totalSpent = invoices.reduce((sum, inv) => sum + (inv.amount || 0), 0) || 15000;
  const totalBudget = budgetData?.total_budget || totalSpent * 1.2;
  const utilizationRate = ((totalSpent / totalBudget) * 100).toFixed(1);
  const remainingBudget = totalBudget - totalSpent;
  
  // Savings calculation
  const potentialSavings = totalSpent * 0.12; // 12% potential savings
  const achievedSavings = totalSpent * 0.05; // 5% already achieved
  
  // Trend data
  const trend = utilizationRate < 80 ? "under" : utilizationRate < 95 ? "on_track" : "over";
  
  // Smart recommendations based on role and budget status
  const getSmartRecommendations = () => {
    const recommendations = [];
    
    if (userRole === 'procurement') {
      if (utilizationRate > 90) {
        recommendations.push({
          priority: "high",
          action: "Renegotiate top 3 vendor contracts",
          impact: `Save $${(totalSpent * 0.08).toLocaleString()}`,
          icon: DollarSign
        });
      }
      recommendations.push({
        priority: "medium",
        action: "Consolidate 5 underperforming vendors",
        impact: "18% rate reduction",
        icon: Package
      });
      recommendations.push({
        priority: "low",
        action: "Lock in Q1 rates before price increases",
        impact: "Protect against 5% inflation",
        icon: Shield
      });
    } else if (userRole === 'operator') {
      recommendations.push({
        priority: "high",
        action: "Reallocate 12 workers from Sector A to B",
        impact: "+15% fill rate improvement",
        icon: Users
      });
      recommendations.push({
        priority: "medium",
        action: "Reduce overtime in kitchen roles by 20%",
        impact: `Save $${(totalSpent * 0.04).toLocaleString()}/month`,
        icon: TrendingDown
      });
    } else if (userRole === 'sector') {
      recommendations.push({
        priority: "high",
        action: "Review 3 sites with >110% budget usage",
        impact: "Prevent $8,200 overage",
        icon: AlertTriangle
      });
      recommendations.push({
        priority: "medium",
        action: "Shift Tuesday/Wednesday staffing levels",
        impact: "15% efficiency gain",
        icon: Calendar
      });
    } else if (userRole === 'client') {
      recommendations.push({
        priority: "high",
        action: "Switch 2 orders to Preferred Vendor rates",
        impact: `Save $${(totalSpent * 0.06).toLocaleString()}`,
        icon: DollarSign
      });
      recommendations.push({
        priority: "medium",
        action: "Lock recurring staff for top 3 positions",
        impact: "15% rate lock guarantee",
        icon: Shield
      });
    } else if (userRole === 'vendor') {
      recommendations.push({
        priority: "high",
        action: "Fill 12 idle workers with pending orders",
        impact: `+$${(potentialSavings * 0.8).toLocaleString()} revenue`,
        icon: Users
      });
      recommendations.push({
        priority: "medium",
        action: "Upsell premium rates to 3 new clients",
        impact: "+8% margin improvement",
        icon: TrendingUp
      });
    } else {
      recommendations.push({
        priority: "high",
        action: "Enable 2 more automation workflows",
        impact: "+$12K/month platform savings",
        icon: Zap
      });
      recommendations.push({
        priority: "medium",
        action: "Approve 5 pending vendor applications",
        impact: "Unlock $45K GMV potential",
        icon: Building2
      });
    }
    
    return recommendations;
  };
  
  const recommendations = getSmartRecommendations();
  
  // Budget breakdown by category
  const budgetBreakdown = [
    { name: "Labor Costs", amount: totalSpent * 0.65, percentage: 65, color: "bg-blue-500" },
    { name: "Vendor Fees", amount: totalSpent * 0.12, percentage: 12, color: "bg-purple-500" },
    { name: "Overtime", amount: totalSpent * 0.15, percentage: 15, color: "bg-amber-500" },
    { name: "Other", amount: totalSpent * 0.08, percentage: 8, color: "bg-slate-400" }
  ];

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className={`w-12 h-12 bg-${config.color}-100 rounded-xl flex items-center justify-center`}>
            <Wallet className={`w-6 h-6 text-${config.color}-600`} />
          </div>
          <div>
            <h2 className="text-xl font-bold text-slate-900">{config.title}</h2>
            <p className="text-sm text-slate-500">{config.focus}</p>
          </div>
        </div>
        <div className="flex gap-2">
          {["week", "month", "quarter", "year"].map(period => (
            <Button
              key={period}
              size="sm"
              variant={selectedPeriod === period ? "default" : "outline"}
              onClick={() => setSelectedPeriod(period)}
              className={selectedPeriod === period ? "bg-[#0A39DF]" : ""}
            >
              {period.charAt(0).toUpperCase() + period.slice(1)}
            </Button>
          ))}
        </div>
      </div>

      {/* Main Budget Card */}
      <Card className={`border-2 ${trend === 'under' ? 'border-green-200 bg-green-50/30' : trend === 'on_track' ? 'border-blue-200 bg-blue-50/30' : 'border-red-200 bg-red-50/30'}`}>
        <CardContent className="p-6">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
            {/* Total Spent */}
            <div>
              <p className="text-xs text-slate-500 uppercase tracking-wider mb-1">Total Spent</p>
              <p className="text-3xl font-bold text-slate-900">${totalSpent.toLocaleString()}</p>
              <p className="text-sm text-slate-500">of ${totalBudget.toLocaleString()} budget</p>
            </div>
            
            {/* Utilization Rate */}
            <div>
              <p className="text-xs text-slate-500 uppercase tracking-wider mb-1">Utilization</p>
              <div className="flex items-center gap-2">
                <p className={`text-3xl font-bold ${trend === 'under' ? 'text-green-600' : trend === 'on_track' ? 'text-blue-600' : 'text-red-600'}`}>
                  {utilizationRate}%
                </p>
                {trend === 'under' && <TrendingDown className="w-5 h-5 text-green-500" />}
                {trend === 'on_track' && <Target className="w-5 h-5 text-blue-500" />}
                {trend === 'over' && <TrendingUp className="w-5 h-5 text-red-500" />}
              </div>
              <Progress 
                value={parseFloat(utilizationRate)} 
                className={`h-2 mt-2 ${trend === 'over' ? '[&>div]:bg-red-500' : trend === 'on_track' ? '[&>div]:bg-blue-500' : '[&>div]:bg-green-500'}`}
              />
            </div>
            
            {/* Remaining Budget */}
            <div>
              <p className="text-xs text-slate-500 uppercase tracking-wider mb-1">Remaining</p>
              <p className={`text-3xl font-bold ${remainingBudget > 0 ? 'text-green-600' : 'text-red-600'}`}>
                ${Math.abs(remainingBudget).toLocaleString()}
              </p>
              <p className="text-sm text-slate-500">
                {remainingBudget > 0 ? 'Available to spend' : 'Over budget'}
              </p>
            </div>
            
            {/* Savings Opportunity */}
            <div className="bg-purple-50 rounded-xl p-4 border-2 border-purple-200">
              <p className="text-xs text-purple-600 uppercase tracking-wider font-semibold mb-1">
                💡 Savings Potential
              </p>
              <p className="text-2xl font-bold text-purple-700">${potentialSavings.toLocaleString()}</p>
              <div className="flex items-center gap-2 mt-1">
                <Badge className="bg-green-100 text-green-700 text-[10px]">
                  ${achievedSavings.toLocaleString()} achieved
                </Badge>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* AI-Powered Recommendations */}
      <Card className="bg-gradient-to-r from-[#1C323E] to-[#0A39DF] text-white overflow-hidden">
        <CardContent className="p-5">
          <div className="flex items-center gap-2 mb-4">
            <Brain className="w-5 h-5" />
            <span className="font-bold">AI Budget Advisor</span>
            <Badge className="bg-white/20 text-white border-0 text-[10px]">Smart Recommendations</Badge>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            {recommendations.map((rec, idx) => {
              const Icon = rec.icon;
              return (
                <div 
                  key={idx} 
                  className={`p-4 rounded-xl ${rec.priority === 'high' ? 'bg-white/20' : 'bg-white/10'} backdrop-blur-sm`}
                >
                  <div className="flex items-center gap-2 mb-2">
                    <Icon className="w-4 h-4" />
                    <Badge className={`text-[10px] ${rec.priority === 'high' ? 'bg-red-500' : rec.priority === 'medium' ? 'bg-amber-500' : 'bg-green-500'}`}>
                      {rec.priority}
                    </Badge>
                  </div>
                  <p className="text-sm font-medium mb-1">{rec.action}</p>
                  <p className="text-xs text-white/70">{rec.impact}</p>
                  <Button 
                    size="sm" 
                    variant="secondary" 
                    className="mt-2 h-7 text-xs bg-white text-[#0A39DF] hover:bg-white/90"
                    onClick={() => window.location.href = rec.priority === 'high' ? '/VendorManagement' : '/Reports'}
                  >
                    Take Action <ArrowRight className="w-3 h-3 ml-1" />
                  </Button>
                </div>
              );
            })}
          </div>
        </CardContent>
      </Card>

      {/* Budget Breakdown */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <PieChart className="w-5 h-5 text-[#0A39DF]" />
              Spend Breakdown
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {budgetBreakdown.map((item, idx) => (
                <div key={idx}>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-sm font-medium">{item.name}</span>
                    <span className="text-sm text-slate-600">${item.amount.toLocaleString()} ({item.percentage}%)</span>
                  </div>
                  <div className="w-full bg-slate-100 rounded-full h-2">
                    <div 
                      className={`${item.color} h-2 rounded-full transition-all`}
                      style={{ width: `${item.percentage}%` }}
                    />
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <BarChart3 className="w-5 h-5 text-[#0A39DF]" />
              Budget Health Score
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-center py-4">
              <div className={`w-24 h-24 mx-auto rounded-full flex items-center justify-center text-3xl font-bold ${trend === 'under' ? 'bg-green-100 text-green-700' : trend === 'on_track' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'}`}>
                {trend === 'under' ? 'A+' : trend === 'on_track' ? 'B+' : 'C'}
              </div>
              <p className="mt-3 font-semibold text-slate-900">
                {trend === 'under' ? 'Excellent Budget Management' : trend === 'on_track' ? 'Good - Monitor Closely' : 'Action Required'}
              </p>
              <p className="text-sm text-slate-500 mt-1">
                {trend === 'under' 
                  ? 'You have room for strategic investments' 
                  : trend === 'on_track' 
                  ? 'Stay on track with current spending pace'
                  : 'Immediate cost reduction recommended'
                }
              </p>
            </div>
            
            <div className="grid grid-cols-3 gap-3 mt-4">
              <div className="text-center p-3 bg-slate-50 rounded-lg">
                <p className="text-lg font-bold text-green-600">↓12%</p>
                <p className="text-[10px] text-slate-500">vs Last Period</p>
              </div>
              <div className="text-center p-3 bg-slate-50 rounded-lg">
                <p className="text-lg font-bold text-blue-600">94%</p>
                <p className="text-[10px] text-slate-500">Forecast Accuracy</p>
              </div>
              <div className="text-center p-3 bg-slate-50 rounded-lg">
                <p className="text-lg font-bold text-purple-600">$8.2K</p>
                <p className="text-[10px] text-slate-500">Saved This Month</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Quick Decision Panel */}
      <Card className="border-l-4 border-l-purple-500 bg-purple-50">
        <CardContent className="p-4">
          <div className="flex items-start gap-3">
            <Lightbulb className="w-5 h-5 text-purple-600 mt-0.5" />
            <div className="flex-1">
              <p className="font-semibold text-purple-900">Quick Decision for {config.title.split(' ')[0]}</p>
              <p className="text-sm text-purple-700 mt-1">
                {userRole === 'procurement' && "Lock in 3 vendor contracts at current rates before Q1 price increases — potential 8% savings on $125K annual spend."}
                {userRole === 'operator' && "Reallocate 15% of Sector B's overtime budget to temporary staffing — same output, 22% cost reduction."}
                {userRole === 'sector' && "Approve shift consolidation for Tuesdays — reduces 4 overlapping positions, saves $1,800/week."}
                {userRole === 'client' && "Switch to annual contract with Preferred Vendor — locks in 15% discount, saves $6,400/year."}
                {userRole === 'vendor' && "Accept 3 pending orders at standard rates — fills idle capacity, adds $12K revenue this month."}
                {userRole === 'admin' && "Enable automated invoice reconciliation — reduces processing time 60%, saves $8K/month in admin costs."}
              </p>
            </div>
            <Button 
              size="sm" 
              className="bg-purple-600 hover:bg-purple-700"
              onClick={() => window.location.href = '/SavingsEngine'}
            >
              Execute <ArrowRight className="w-3 h-3 ml-1" />
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}