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 { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import {
  Sparkles, Target, TrendingUp, DollarSign, Users, Clock,
  Shield, Zap, Brain, CheckCircle, ArrowRight, BarChart3,
  Building2, MapPin, Calendar, Lightbulb, AlertTriangle
} from "lucide-react";

const STRATEGY_CATEGORIES = [
  { id: "cost", label: "Cost Optimization", icon: DollarSign, color: "green" },
  { id: "efficiency", label: "Operational Efficiency", icon: Zap, color: "blue" },
  { id: "quality", label: "Quality & Compliance", icon: Shield, color: "purple" },
  { id: "growth", label: "Revenue Growth", icon: TrendingUp, color: "amber" }
];

const SMART_STRATEGIES = {
  cost: [
    {
      id: "vendor_consolidation",
      title: "Vendor Consolidation Program",
      description: "Reduce vendor count by 40% while maintaining service quality through strategic consolidation",
      impact: "15-25% cost reduction",
      timeframe: "90 days",
      roi: "$45,000/year",
      steps: [
        "Analyze current vendor performance scores",
        "Identify overlap in service coverage",
        "Negotiate volume discounts with top performers",
        "Transition low-performers to preferred vendors"
      ],
      metrics: ["Vendor count reduction", "Rate savings %", "Fill rate impact"]
    },
    {
      id: "rate_optimization",
      title: "Dynamic Rate Optimization",
      description: "AI-powered rate adjustments based on demand, seasonality, and market conditions",
      impact: "8-12% savings on labor costs",
      timeframe: "30 days",
      roi: "$28,000/year",
      steps: [
        "Enable real-time market rate monitoring",
        "Set rate caps based on role and region",
        "Auto-negotiate when rates exceed thresholds",
        "Lock in favorable rates for recurring positions"
      ],
      metrics: ["Average rate reduction", "Market position", "Compliance rate"]
    },
    {
      id: "overtime_reduction",
      title: "Smart Overtime Management",
      description: "Predictive scheduling to minimize costly overtime while maintaining coverage",
      impact: "30-40% OT reduction",
      timeframe: "45 days",
      roi: "$18,000/year",
      steps: [
        "Analyze historical overtime patterns",
        "Implement 8-hour shift maximums",
        "Cross-train workers for flexibility",
        "Use AI for shift optimization"
      ],
      metrics: ["OT hours/week", "Cost per shift", "Worker satisfaction"]
    }
  ],
  efficiency: [
    {
      id: "auto_assignment",
      title: "Automated Assignment Engine",
      description: "AI matches workers to shifts based on skills, location, availability, and performance",
      impact: "85% faster assignment",
      timeframe: "14 days",
      roi: "$22,000/year",
      steps: [
        "Enable smart matching algorithm",
        "Define assignment rules and priorities",
        "Set up worker preference profiles",
        "Activate real-time notifications"
      ],
      metrics: ["Time to fill", "Assignment accuracy", "Worker acceptance rate"]
    },
    {
      id: "predictive_scheduling",
      title: "Predictive Demand Scheduling",
      description: "Forecast staffing needs 2-4 weeks ahead using historical data and event calendars",
      impact: "95% schedule accuracy",
      timeframe: "21 days",
      roi: "$15,000/year",
      steps: [
        "Integrate historical demand data",
        "Connect event and holiday calendars",
        "Train prediction models",
        "Automate schedule generation"
      ],
      metrics: ["Forecast accuracy", "Understaffing incidents", "Overstaffing costs"]
    },
    {
      id: "digital_timesheet",
      title: "Digital Timesheet Automation",
      description: "Eliminate manual time tracking with GPS-verified clock-in/out and auto-approval",
      impact: "90% admin time saved",
      timeframe: "7 days",
      roi: "$12,000/year",
      steps: [
        "Deploy mobile clock-in app",
        "Configure geofencing rules",
        "Set up auto-approval thresholds",
        "Enable real-time dashboard"
      ],
      metrics: ["Timesheet accuracy", "Processing time", "Dispute rate"]
    }
  ],
  quality: [
    {
      id: "compliance_monitoring",
      title: "Real-Time Compliance Dashboard",
      description: "Continuous monitoring of certifications, background checks, and regulatory requirements",
      impact: "100% compliance rate",
      timeframe: "14 days",
      roi: "Risk mitigation",
      steps: [
        "Integrate all compliance data sources",
        "Set up expiration alerts (30/60/90 days)",
        "Automate renewal reminders",
        "Generate audit-ready reports"
      ],
      metrics: ["Compliance score", "Expired certifications", "Audit pass rate"]
    },
    {
      id: "performance_scoring",
      title: "Worker Performance Index",
      description: "Data-driven scoring system for reliability, quality, and client satisfaction",
      impact: "25% quality improvement",
      timeframe: "30 days",
      roi: "$8,000/year",
      steps: [
        "Define performance metrics",
        "Collect feedback from all parties",
        "Calculate composite scores",
        "Reward top performers"
      ],
      metrics: ["Average rating", "Repeat request rate", "Client satisfaction"]
    },
    {
      id: "incident_reduction",
      title: "Proactive Incident Prevention",
      description: "AI identifies high-risk assignments before issues occur",
      impact: "60% fewer incidents",
      timeframe: "45 days",
      roi: "Risk mitigation",
      steps: [
        "Analyze historical incident data",
        "Identify risk patterns",
        "Flag high-risk assignments",
        "Implement preventive protocols"
      ],
      metrics: ["Incident rate", "Response time", "Resolution rate"]
    }
  ],
  growth: [
    {
      id: "market_expansion",
      title: "Strategic Market Expansion",
      description: "Data-driven identification of high-opportunity markets for vendor growth",
      impact: "+35% addressable market",
      timeframe: "60 days",
      roi: "$65,000/year",
      steps: [
        "Analyze demand gaps by region",
        "Identify underserved sectors",
        "Recruit targeted vendor partners",
        "Launch market-specific campaigns"
      ],
      metrics: ["New markets entered", "Revenue per market", "Market share"]
    },
    {
      id: "client_retention",
      title: "Client Loyalty Program",
      description: "Tiered benefits and exclusive rates for high-volume clients",
      impact: "40% higher retention",
      timeframe: "30 days",
      roi: "$42,000/year",
      steps: [
        "Segment clients by value",
        "Design tier benefits",
        "Implement loyalty tracking",
        "Launch exclusive offerings"
      ],
      metrics: ["Client retention rate", "CLV increase", "Referral rate"]
    },
    {
      id: "upsell_automation",
      title: "Smart Upsell Engine",
      description: "AI identifies opportunities to expand services with existing clients",
      impact: "+18% revenue per client",
      timeframe: "21 days",
      roi: "$28,000/year",
      steps: [
        "Analyze client usage patterns",
        "Identify cross-sell opportunities",
        "Automate personalized offers",
        "Track conversion rates"
      ],
      metrics: ["Upsell rate", "Average order value", "Service expansion"]
    }
  ]
};

export default function SmartOperationStrategies({ userRole = 'vendor', onSelectStrategy }) {
  const [selectedCategory, setSelectedCategory] = useState("cost");
  const [expandedStrategy, setExpandedStrategy] = useState(null);
  
  const strategies = SMART_STRATEGIES[selectedCategory] || [];
  
  // Calculate total potential savings
  const totalPotentialSavings = Object.values(SMART_STRATEGIES)
    .flat()
    .reduce((sum, strategy) => {
      const roiMatch = strategy.roi.match(/\$(\d+,?\d*)/);
      if (roiMatch) {
        return sum + parseInt(roiMatch[1].replace(',', ''));
      }
      return sum;
    }, 0);

  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-gradient-to-r from-[#0A39DF] to-[#1C323E] rounded-xl flex items-center justify-center">
            <Brain className="w-6 h-6 text-white" />
          </div>
          <div>
            <h2 className="text-xl font-bold text-slate-900">Smart Operation Strategies</h2>
            <p className="text-sm text-slate-500">AI-powered recommendations to optimize your operations</p>
          </div>
        </div>
        <Badge className="bg-green-100 text-green-700 text-sm px-3 py-1">
          ${totalPotentialSavings.toLocaleString()}/year potential
        </Badge>
      </div>

      {/* Impact Summary */}
      <Card className="bg-gradient-to-r from-emerald-50 to-blue-50 border-2 border-emerald-200">
        <CardContent className="p-4">
          <div className="grid grid-cols-4 gap-4">
            <div className="text-center">
              <p className="text-2xl font-bold text-emerald-700">15-25%</p>
              <p className="text-xs text-emerald-600">Cost Reduction</p>
            </div>
            <div className="text-center">
              <p className="text-2xl font-bold text-blue-700">85%</p>
              <p className="text-xs text-blue-600">Faster Operations</p>
            </div>
            <div className="text-center">
              <p className="text-2xl font-bold text-purple-700">100%</p>
              <p className="text-xs text-purple-600">Compliance Rate</p>
            </div>
            <div className="text-center">
              <p className="text-2xl font-bold text-amber-700">+35%</p>
              <p className="text-xs text-amber-600">Revenue Growth</p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Category Tabs */}
      <div className="flex gap-2 flex-wrap">
        {STRATEGY_CATEGORIES.map(cat => {
          const Icon = cat.icon;
          const isActive = selectedCategory === cat.id;
          return (
            <Button
              key={cat.id}
              variant={isActive ? "default" : "outline"}
              onClick={() => setSelectedCategory(cat.id)}
              className={isActive ? "bg-[#0A39DF]" : ""}
            >
              <Icon className="w-4 h-4 mr-2" />
              {cat.label}
            </Button>
          );
        })}
      </div>

      {/* Strategy Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {strategies.map((strategy) => {
          const isExpanded = expandedStrategy === strategy.id;
          return (
            <Card 
              key={strategy.id} 
              className={`cursor-pointer transition-all hover:shadow-lg ${isExpanded ? 'md:col-span-3 border-2 border-[#0A39DF]' : ''}`}
              onClick={() => setExpandedStrategy(isExpanded ? null : strategy.id)}
            >
              <CardContent className="p-5">
                <div className="flex items-start justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <Sparkles className="w-5 h-5 text-[#0A39DF]" />
                    <Badge className="bg-green-100 text-green-700 text-[10px]">{strategy.impact}</Badge>
                  </div>
                  <Badge variant="outline" className="text-[10px]">{strategy.timeframe}</Badge>
                </div>
                
                <h3 className="font-bold text-slate-900 mb-2">{strategy.title}</h3>
                <p className="text-sm text-slate-600 mb-3">{strategy.description}</p>
                
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-1 text-sm">
                    <DollarSign className="w-4 h-4 text-green-600" />
                    <span className="font-semibold text-green-700">{strategy.roi}</span>
                  </div>
                  <Button size="sm" variant="ghost" className="text-[#0A39DF]">
                    {isExpanded ? 'Collapse' : 'Details'} <ArrowRight className="w-3 h-3 ml-1" />
                  </Button>
                </div>

                {/* Expanded Content */}
                {isExpanded && (
                  <div className="mt-4 pt-4 border-t space-y-4">
                    <div>
                      <h4 className="font-semibold text-sm mb-2 flex items-center gap-2">
                        <Target className="w-4 h-4 text-blue-600" />
                        Implementation Steps
                      </h4>
                      <div className="space-y-2">
                        {strategy.steps.map((step, idx) => (
                          <div key={idx} className="flex items-start gap-2">
                            <div className="w-5 h-5 rounded-full bg-blue-100 text-blue-700 flex items-center justify-center text-xs font-bold flex-shrink-0">
                              {idx + 1}
                            </div>
                            <span className="text-sm text-slate-600">{step}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                    
                    <div>
                      <h4 className="font-semibold text-sm mb-2 flex items-center gap-2">
                        <BarChart3 className="w-4 h-4 text-purple-600" />
                        Key Metrics to Track
                      </h4>
                      <div className="flex gap-2 flex-wrap">
                        {strategy.metrics.map((metric, idx) => (
                          <Badge key={idx} variant="outline" className="text-xs">
                            {metric}
                          </Badge>
                        ))}
                      </div>
                    </div>

                    <div className="flex gap-3">
                      <Button 
                        className="flex-1 bg-[#0A39DF] hover:bg-[#0831b8]"
                        onClick={(e) => {
                          e.stopPropagation();
                          onSelectStrategy?.(strategy);
                        }}
                      >
                        <CheckCircle className="w-4 h-4 mr-2" />
                        Implement Strategy
                      </Button>
                      <Button 
                        variant="outline" 
                        onClick={(e) => {
                          e.stopPropagation();
                          window.location.href = '/Support';
                        }}
                      >
                        Schedule Demo
                      </Button>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          );
        })}
      </div>

      {/* Quick Win Section */}
      <Card className="border-l-4 border-l-amber-500 bg-amber-50">
        <CardContent className="p-4">
          <div className="flex items-start gap-3">
            <Lightbulb className="w-5 h-5 text-amber-600 mt-0.5" />
            <div className="flex-1">
              <p className="font-semibold text-amber-900">Quick Win: Start with Rate Optimization</p>
              <p className="text-sm text-amber-700 mt-1">
                Enable dynamic rate optimization today — no implementation required. 
                AI will start identifying savings opportunities within 24 hours with an average 
                8-12% reduction in labor costs.
              </p>
            </div>
            <Button 
              size="sm" 
              className="bg-amber-600 hover:bg-amber-700"
              onClick={() => window.location.href = '/VendorRates'}
            >
              Enable Now <Zap className="w-3 h-3 ml-1" />
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}