import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { 
  Target, ArrowRight, CheckCircle, AlertTriangle, 
  TrendingUp, Users, DollarSign, Zap, Star, Shield, Layers
} from "lucide-react";
import ConversionModal from "./ConversionModal";

export default function ContractConversionMap({ assignments, vendors, workforce, metrics, userRole }) {
  const [selectedOpportunity, setSelectedOpportunity] = useState(null);
  
  // Role-specific opportunities with fallback spend values
  const baseSpend = metrics.totalSpend || 250000; // Default $250k if no data
  
  const getProcurementOpportunities = () => [
    {
      id: 1,
      category: "Vendor Tier Consolidation",
      description: "Consolidate Tier 3 vendors into Tier 1 preferred network for better rates",
      currentSpend: baseSpend * 0.25,
      currentRate: metrics.avgNonContractedRate || 52,
      targetRate: metrics.avgContractedRate || 42,
      potentialSavings: (baseSpend * 0.25) * 0.19,
      savingsPercent: 19,
      priority: "high",
      count: Math.max(Math.floor(vendors.length * 0.4), 5),
      countLabel: "vendors",
      recommendation: "Consolidate to Preferred Network",
      benefits: ["19% rate reduction", "Stronger SLAs", "Simplified vendor management"],
      tierFrom: "Standard Vendors",
      tierTo: "Preferred Network",
    },
    {
      id: 2,
      category: "Multi-Vendor Spend Consolidation",
      description: "Reduce vendor fragmentation by consolidating spend with top 3 partners",
      currentSpend: baseSpend * 0.20,
      currentRate: 48,
      targetRate: 40,
      potentialSavings: (baseSpend * 0.20) * 0.17,
      savingsPercent: 17,
      priority: "high",
      count: 5,
      countLabel: "vendors to consolidate",
      recommendation: "Volume-based rate negotiation",
      benefits: ["Volume discounts", "Single invoice processing", "Better compliance"],
      tierFrom: "5+ Vendors",
      tierTo: "2 Partners",
    },
    {
      id: 3,
      category: "Rate Card Optimization",
      description: "Renegotiate rates with underperforming vendors or replace with preferred",
      currentSpend: baseSpend * 0.15,
      currentRate: 65,
      targetRate: 55,
      potentialSavings: (baseSpend * 0.15) * 0.15,
      savingsPercent: 15,
      priority: "medium",
      count: Math.max(Math.floor(vendors.length * 0.2), 3),
      countLabel: "vendors above market",
      recommendation: "Rate renegotiation or replacement",
      benefits: ["Market-aligned rates", "Performance guarantees", "Contract leverage"],
      tierFrom: "Above Market",
      tierTo: "Competitive Rates",
    },
    {
      id: 4,
      category: "Regional Vendor Optimization",
      description: "Add regional preferred vendors to reduce travel costs and improve response",
      currentSpend: baseSpend * 0.12,
      currentRate: 50,
      targetRate: 44,
      potentialSavings: (baseSpend * 0.12) * 0.12,
      savingsPercent: 12,
      priority: "medium",
      count: 3,
      countLabel: "regions underserved",
      recommendation: "Onboard regional vendors",
      benefits: ["Local expertise", "Reduced travel fees", "Faster fulfillment"],
      tierFrom: "National Only",
      tierTo: "Regional Network",
    },
  ];

  const getClientOpportunities = () => [
    {
      id: 1,
      category: "Staff Rate Optimization",
      description: "Request staff through preferred vendors for lower hourly rates",
      currentSpend: baseSpend * 0.25,
      currentRate: metrics.avgNonContractedRate || 52,
      targetRate: metrics.avgContractedRate || 42,
      potentialSavings: (baseSpend * 0.25) * 0.19,
      savingsPercent: 19,
      priority: "high",
      count: Math.max(Math.floor(workforce.length * 0.3), 5),
      countLabel: "staff positions",
      recommendation: "Use Preferred Vendor Network",
      benefits: ["Lower hourly rates", "Same quality staff", "Better reliability"],
      tierFrom: "Standard Rates",
      tierTo: "Preferred Rates",
    },
    {
      id: 2,
      category: "Recurring Staff Savings",
      description: "Convert recurring positions to contracted rates for consistent savings",
      currentSpend: baseSpend * 0.20,
      currentRate: 48,
      targetRate: 40,
      potentialSavings: (baseSpend * 0.20) * 0.17,
      savingsPercent: 17,
      priority: "high",
      count: Math.max(Math.floor(workforce.length * 0.25), 4),
      countLabel: "recurring positions",
      recommendation: "Lock in contracted rates",
      benefits: ["Predictable costs", "Priority staffing", "Dedicated workforce"],
      tierFrom: "Spot Rates",
      tierTo: "Contracted",
    },
    {
      id: 3,
      category: "Skill-Matched Staffing",
      description: "Match staff skills to reduce overtime and improve productivity",
      currentSpend: baseSpend * 0.15,
      currentRate: 65,
      targetRate: 55,
      potentialSavings: (baseSpend * 0.15) * 0.15,
      savingsPercent: 15,
      priority: "medium",
      count: Math.max(Math.floor(workforce.length * 0.2), 3),
      countLabel: "positions",
      recommendation: "Request skill-verified staff",
      benefits: ["Less overtime", "Higher productivity", "Fewer replacements"],
      tierFrom: "General Staff",
      tierTo: "Skill-Matched",
    },
    {
      id: 4,
      category: "Favorite Staff Pool",
      description: "Build a pool of preferred workers for consistent quality and rates",
      currentSpend: baseSpend * 0.12,
      currentRate: 50,
      targetRate: 44,
      potentialSavings: (baseSpend * 0.12) * 0.12,
      savingsPercent: 12,
      priority: "medium",
      count: Math.max(Math.floor(workforce.length * 0.15), 3),
      countLabel: "workers to add",
      recommendation: "Create favorite staff list",
      benefits: ["Familiar with your operations", "Faster onboarding", "Priority booking"],
      tierFrom: "Random Assignment",
      tierTo: "Preferred Workers",
    },
  ];

  const opportunities = userRole === "client" ? getClientOpportunities() : getProcurementOpportunities();

  const priorityColors = {
    high: { bg: "bg-white", border: "border-slate-200", text: "text-slate-900", badge: "bg-red-100 text-red-700" },
    medium: { bg: "bg-white", border: "border-slate-200", text: "text-slate-900", badge: "bg-amber-100 text-amber-700" },
    low: { bg: "bg-white", border: "border-slate-200", text: "text-slate-900", badge: "bg-slate-100 text-slate-700" },
  };

  const totalPotentialSavings = opportunities.reduce((sum, o) => sum + o.potentialSavings, 0);
  const totalCount = opportunities.reduce((sum, o) => sum + o.count, 0);
  const countLabel = userRole === "client" ? "staff positions" : "vendors";

  return (
    <div className="space-y-6">
      {/* Summary Banner */}
      <Card className="bg-[#1C323E] text-white border-0">
        <CardContent className="p-6">
          <div className="flex items-center justify-between flex-wrap gap-4">
            <div>
              <div className="flex items-center gap-2 mb-2">
                <Layers className="w-6 h-6" />
                <h3 className="text-xl font-bold">Rate & Vendor Optimization</h3>
              </div>
              <p className="text-slate-300">
                {userRole === "client" 
                  ? `Optimize ${totalCount} staff positions for better rates`
                  : `Consolidate ${totalCount} ${countLabel} into preferred network`
                }
              </p>
              <p className="text-sm text-slate-400 mt-1">
                {userRole === "client"
                  ? "Lower rates • Same quality staff • Better reliability"
                  : "Lower rates • Stronger partnerships • Simplified management"
                }
              </p>
            </div>
            <div className="text-right bg-white/10 rounded-xl p-4">
              <p className="text-sm text-slate-300">Total Optimization Potential</p>
              <p className="text-4xl font-bold">${totalPotentialSavings.toLocaleString(undefined, { maximumFractionDigits: 0 })}</p>
              <p className="text-sm text-slate-300">annual savings</p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* How Rate Optimization Works */}
      <Card className="border border-slate-200">
        <CardContent className="p-5">
          <h4 className="font-bold text-slate-900 mb-4 flex items-center gap-2">
            <Zap className="w-5 h-5 text-[#0A39DF]" />
            How Rate Optimization Works
          </h4>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className="text-center p-3 bg-slate-50 rounded-lg">
              <div className="w-10 h-10 bg-[#0A39DF] text-white rounded-full flex items-center justify-center mx-auto mb-2">
                <span className="text-lg font-bold">1</span>
              </div>
              <p className="text-sm font-medium text-slate-900">Identify Workers</p>
              <p className="text-xs text-slate-500 mt-1">Workers with higher-tier vendors</p>
            </div>
            <div className="text-center p-3 bg-slate-50 rounded-lg">
              <div className="w-10 h-10 bg-[#0A39DF] text-white rounded-full flex items-center justify-center mx-auto mb-2">
                <span className="text-lg font-bold">2</span>
              </div>
              <p className="text-sm font-medium text-slate-900">Compare Rates</p>
              <p className="text-xs text-slate-500 mt-1">Match to preferred vendor rates</p>
            </div>
            <div className="text-center p-3 bg-slate-50 rounded-lg">
              <div className="w-10 h-10 bg-[#0A39DF] text-white rounded-full flex items-center justify-center mx-auto mb-2">
                <span className="text-lg font-bold">3</span>
              </div>
              <p className="text-sm font-medium text-slate-900">Reassign</p>
              <p className="text-xs text-slate-500 mt-1">Move to preferred vendors</p>
            </div>
            <div className="text-center p-3 bg-slate-50 rounded-lg">
              <div className="w-10 h-10 bg-emerald-600 text-white rounded-full flex items-center justify-center mx-auto mb-2">
                <span className="text-lg font-bold">4</span>
              </div>
              <p className="text-sm font-medium text-slate-900">Save</p>
              <p className="text-xs text-slate-500 mt-1">Lower rates, same quality</p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Rate Tier Visualization */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card className="border-amber-300 bg-amber-50">
          <CardContent className="p-5 text-center">
            <div className="w-12 h-12 bg-amber-500 rounded-lg flex items-center justify-center mx-auto mb-3">
              <DollarSign className="w-6 h-6 text-white" />
            </div>
            <h4 className="font-semibold text-slate-900">Standard Tier</h4>
            <p className="text-3xl font-bold text-amber-600 mt-2">
              ${(metrics.avgNonContractedRate || 52).toFixed(0)}/hr
            </p>
            <p className="text-sm text-slate-500 mt-1">Higher rates • Less volume</p>
          </CardContent>
        </Card>

        <Card className="border-[#0A39DF] border-2 bg-blue-50">
          <CardContent className="p-5 text-center relative">
            <Badge className="absolute -top-3 left-1/2 -translate-x-1/2 bg-[#0A39DF] text-white">
              OPTIMIZE
            </Badge>
            <div className="w-12 h-12 bg-[#0A39DF] rounded-lg flex items-center justify-center mx-auto mb-3 mt-1">
              <ArrowRight className="w-6 h-6 text-white" />
            </div>
            <h4 className="font-semibold text-slate-900">Ready to Optimize</h4>
            <p className="text-3xl font-bold text-[#0A39DF] mt-2">
              {totalCount} {countLabel}
            </p>
            <p className="text-sm text-slate-500 mt-1">Eligible for optimization</p>
          </CardContent>
        </Card>

        <Card className="border-emerald-300 bg-emerald-50">
          <CardContent className="p-5 text-center">
            <div className="w-12 h-12 bg-emerald-600 rounded-lg flex items-center justify-center mx-auto mb-3">
              <Shield className="w-6 h-6 text-white" />
            </div>
            <h4 className="font-semibold text-slate-900">Preferred Tier</h4>
            <p className="text-3xl font-bold text-emerald-600 mt-2">
              ${(metrics.avgContractedRate || 42).toFixed(0)}/hr
            </p>
            <p className="text-sm text-slate-500 mt-1">Better rates • Volume discounts</p>
          </CardContent>
        </Card>
      </div>

      {/* Optimization Opportunity Cards */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {opportunities.map((opportunity) => {
          const colors = priorityColors[opportunity.priority];
          
          return (
            <Card key={opportunity.id} className={`${colors.bg} ${colors.border} border-2 hover:shadow-lg transition-all`}>
              <CardHeader className="pb-2">
                <div className="flex items-start justify-between">
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <Badge className={colors.badge}>
                        {opportunity.priority === "high" ? "HIGH IMPACT" : "MEDIUM IMPACT"}
                      </Badge>
                      <Badge variant="outline" className="bg-white">
                        {opportunity.tierFrom} → {opportunity.tierTo}
                      </Badge>
                    </div>
                    <CardTitle className={`text-lg ${colors.text}`}>{opportunity.category}</CardTitle>
                    <p className="text-sm text-slate-500 mt-1">{opportunity.description}</p>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {/* Rate Comparison */}
                  <div className="bg-white rounded-lg p-3 border">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm font-medium text-slate-700">Rate Comparison</span>
                      <Badge className="bg-green-100 text-green-700">
                        Save {opportunity.savingsPercent}%
                      </Badge>
                    </div>
                    <div className="flex items-center gap-3">
                      <div className="flex-1">
                        <p className="text-xs text-slate-500">Current</p>
                        <p className="text-lg font-bold text-amber-600">${opportunity.currentRate}/hr</p>
                      </div>
                      <ArrowRight className="w-5 h-5 text-purple-500" />
                      <div className="flex-1">
                        <p className="text-xs text-slate-500">Optimized</p>
                        <p className="text-lg font-bold text-emerald-600">${opportunity.targetRate}/hr</p>
                      </div>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-3 text-sm">
                    <div className="bg-white/70 rounded-lg p-2">
                      <p className="text-slate-500 text-xs">Current Spend</p>
                      <p className="font-bold text-slate-900">${opportunity.currentSpend.toLocaleString(undefined, { maximumFractionDigits: 0 })}</p>
                    </div>
                    <div className="bg-white/70 rounded-lg p-2">
                      <p className="text-slate-500 text-xs">Annual Savings</p>
                      <p className="font-bold text-green-600">${opportunity.potentialSavings.toLocaleString(undefined, { maximumFractionDigits: 0 })}</p>
                    </div>
                  </div>

                  <div className="flex items-center gap-2 text-sm">
                    <Users className="w-4 h-4 text-slate-400" />
                    <span className="text-slate-600">{opportunity.count} {opportunity.countLabel} eligible</span>
                  </div>

                  <div className="flex flex-wrap gap-2">
                    {opportunity.benefits.map((benefit, idx) => (
                      <Badge key={idx} variant="outline" className="text-xs bg-white">
                        <CheckCircle className="w-3 h-3 mr-1 text-green-500" />
                        {benefit}
                      </Badge>
                    ))}
                  </div>

                  <Button className="w-full bg-[#0A39DF] hover:bg-[#0831b8]" onClick={() => setSelectedOpportunity(opportunity)}>
                    <Zap className="w-4 h-4 mr-2" />
                    Optimize Now
                  </Button>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>

      {/* Vendor Recommendations */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Star className="w-5 h-5 text-amber-500" />
            Recommended Vendors for Conversion
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {vendors.slice(0, 3).map((vendor, idx) => (
              <div key={vendor.id || idx} className="p-4 bg-slate-50 rounded-xl border border-slate-200">
                <div className="flex items-center gap-3 mb-3">
                  <div className="w-10 h-10 bg-[#0A39DF] rounded-lg flex items-center justify-center">
                    <Shield className="w-5 h-5 text-white" />
                  </div>
                  <div>
                    <p className="font-semibold text-slate-900">{vendor.legal_name || `Preferred Vendor ${idx + 1}`}</p>
                    <p className="text-xs text-slate-500">{vendor.region || "National"}</p>
                  </div>
                </div>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-slate-500">Avg Rate</span>
                    <span className="font-medium">${(metrics.avgContractedRate - idx * 2).toFixed(2)}/hr</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-500">Reliability</span>
                    <span className="font-medium text-green-600">{95 - idx}%</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-500">Workforce</span>
                    <span className="font-medium">{vendor.workforce_count || 150 - idx * 20}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <ConversionModal
        open={!!selectedOpportunity}
        onClose={() => setSelectedOpportunity(null)}
        opportunity={selectedOpportunity}
        vendors={vendors}
        userRole={userRole}
      />
    </div>
  );
}