
import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import {
  Plus, Edit, Trash2, TrendingUp, TrendingDown, DollarSign, Users, Calculator,
  CheckCircle2, Save, Building2, Settings, ChevronDown, ChevronUp, Loader2, Sparkles, Search, MapPin, Briefcase
} from "lucide-react";
import { useToast } from "@/components/ui/use-toast";

const MINIMUM_WAGE = 16.50;
const CATEGORIES = [
  "Kitchen and Culinary",
  "Concessions",
  "Facilities",
  "Bartending",
  "Security",
  "Event Staff",
  "Management",
  "Technical",
  "Other"
];

const VENDORS = [
  { name: "Legendary Event Staffing", region: "Bay Area", state: "California", city: "San Francisco", specialty: "Full Service Events", markup: 25, fee: 20, csat: 4.8 },
  { name: "Instawork", region: "National", state: "Multiple", city: "Multiple", specialty: "On-Demand Gig Platform", markup: 18, fee: 15, csat: 4.5 },
  { name: "The Party Staff", region: "Bay Area", state: "California", city: "San Francisco", specialty: "Event Staffing", markup: 24, fee: 19, csat: 4.2 },
  { name: "Elite Hospitality Staffing", region: "Bay Area", state: "California", city: "Oakland", specialty: "Hotels/Events", markup: 23, fee: 18, csat: 4.3 },
  { name: "Jeff Duerson Staffing", region: "Bay Area", state: "California", city: "San Jose", specialty: "Catering/Events", markup: 27, fee: 22, csat: 4.0 },
  { name: "Flagship Culinary Services", region: "Bay Area", state: "California", city: "Palo Alto", specialty: "Culinary", markup: 26, fee: 21, csat: 4.1 },
  { name: "LA Event Professionals", region: "Southern California", state: "California", city: "Los Angeles", specialty: "Event Staffing", markup: 22, fee: 18, csat: 4.4 },
  { name: "Hollywood Hospitality", region: "Southern California", state: "California", city: "Los Angeles", specialty: "Full Service Events", markup: 20, fee: 17, csat: 4.6 },
  { name: "San Diego Event Staff", region: "Southern California", state: "California", city: "San Diego", specialty: "Hospitality", markup: 21, fee: 17, csat: 4.3 },
  { name: "OC Staffing Solutions", region: "Southern California", state: "California", city: "Irvine", specialty: "Event-based staffing", markup: 25, fee: 20, csat: 4.1 },
];

const MARKET_AVERAGES = {
  "Banquet Captain": 47.76,
  "Barback": 36.13,
  "Barista": 43.11,
  "Busser": 39.23,
  "BW Bartender": 41.15,
  "Cashier/Standworker": 38.05,
  "Cook": 44.58,
  "Dinning Attendant": 41.56,
  "Dishwasher/ Steward": 38.38,
  "Executive Chef": 70.60,
  "FOH Cafe Attendant": 41.56,
  "Full Bartender": 47.76,
  "Grill Cook": 44.58,
  "Host/Hostess/Greeter": 41.56,
  "Internal Support": 41.56,
  "Lead Cook": 52.00,
  "Line Cook": 44.58,
  "Premium Server": 47.76,
  "Prep Cook": 37.98,
  "Receiver": 40.01,
  "Server": 41.56,
  "Sous Chef": 59.75,
  "Warehouse Worker": 41.15,
  "Baker": 44.58,
  "Janitor": 38.38,
  "Mixologist": 71.30,
  "Utilities": 38.38,
  "Scullery": 38.38,
  "Runner": 39.23,
  "Pantry Cook": 44.58,
  "Supervisor": 47.76,
  "Steward": 38.38,
  "Steward Supervisor": 42.25
};

const ROLE_CATEGORIES = {
  "Banquet Captain": "Event Staff",
  "Barback": "Bartending",
  "Barista": "Concessions",
  "Busser": "Event Staff",
  "BW Bartender": "Bartending",
  "Cashier/Standworker": "Concessions",
  "Cook": "Kitchen and Culinary",
  "Dinning Attendant": "Event Staff",
  "Dishwasher/ Steward": "Kitchen and Culinary",
  "Executive Chef": "Management",
  "FOH Cafe Attendant": "Concessions",
  "Full Bartender": "Bartending",
  "Grill Cook": "Kitchen and Culinary",
  "Host/Hostess/Greeter": "Event Staff",
  "Internal Support": "Other",
  "Lead Cook": "Kitchen and Culinary",
  "Line Cook": "Kitchen and Culinary",
  "Premium Server": "Event Staff",
  "Prep Cook": "Kitchen and Culinary",
  "Receiver": "Facilities",
  "Server": "Event Staff",
  "Sous Chef": "Management",
  "Warehouse Worker": "Facilities",
  "Baker": "Kitchen and Culinary",
  "Janitor": "Facilities",
  "Mixologist": "Bartending",
  "Utilities": "Facilities",
  "Scullery": "Kitchen and Culinary",
  "Runner": "Event Staff",
  "Pantry Cook": "Kitchen and Culinary",
  "Supervisor": "Management",
  "Steward": "Kitchen and Culinary",
  "Steward Supervisor": "Management"
};

export default function VendorRateCard() {
  const [selectedVendor, setSelectedVendor] = useState("all");
  const [activeCategory, setActiveCategory] = useState("all");
  const [expandedVendors, setExpandedVendors] = useState({});
  const [generatingDemoData, setGeneratingDemoData] = useState(false);
  
  // NEW: Search and filter states
  const [searchVendor, setSearchVendor] = useState("");
  const [searchLocation, setSearchLocation] = useState("");
  const [searchState, setSearchState] = useState("");
  const [searchPosition, setSearchPosition] = useState("");

  const { toast } = useToast();
  const queryClient = useQueryClient();

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

  const userRole = user?.user_role || user?.role || "admin";
  const isVendor = userRole === "vendor";
  const isAdminOrProcurement = userRole === "admin" || userRole === "procurement";

  const calculateClientRate = (wage, markupPercent, feePercent) => {
    const baseWage = parseFloat(wage);
    const markupAmount = baseWage * (parseFloat(markupPercent) / 100);
    const subtotal = baseWage + markupAmount;
    const feeAmount = subtotal * (parseFloat(feePercent) / 100);
    return (subtotal + feeAmount).toFixed(2);
  };

  const analyzePricing = (role, clientRate) => {
    const marketAvg = MARKET_AVERAGES[role];
    if (!marketAvg) return { status: "competitive", message: "No market data", color: "text-blue-600", bg: "bg-blue-50", icon: CheckCircle2 };

    const diff = ((clientRate - marketAvg) / marketAvg) * 100;

    if (diff < -15) return { status: "underpriced", message: `${Math.abs(diff).toFixed(0)}% below market`, color: "text-red-600", bg: "bg-red-50", icon: TrendingDown };
    if (diff > 20) return { status: "overpriced", message: `${diff.toFixed(0)}% above market`, color: "text-orange-600", bg: "bg-orange-50", icon: TrendingUp };
    if (diff >= -5 && diff <= 10) return { status: "optimal", message: "Optimal pricing", color: "text-green-600", bg: "bg-green-50", icon: CheckCircle2 };
    return { status: "competitive", message: "Competitive", color: "text-blue-600", bg: "bg-blue-50", icon: CheckCircle2 };
  };

  // Generate rates for ALL vendors
  const generateAllVendorRates = async () => {
    setGeneratingDemoData(true);
    
    const allRoles = Object.keys(MARKET_AVERAGES);
    const totalRates = (VENDORS.length - 1) * allRoles.length; // -1 for Legendary which already has rates
    
    toast({
      title: "🚀 Generating All Vendor Rates",
      description: `Creating ${totalRates} rate cards for ${VENDORS.length - 1} vendors...`,
    });

    try {
      let totalCreated = 0;
      
      for (const vendor of VENDORS) {
        // Skip Legendary since it already has rates
        if (vendor.name === "Legendary Event Staffing") continue;
        
        for (const [roleName, marketRate] of Object.entries(MARKET_AVERAGES)) {
          const category = ROLE_CATEGORIES[roleName] || "Other";
          
          // Calculate employee wage based on region
          let baseWageMultiplier = 0.65; // Default 65% of market
          if (vendor.region === "Bay Area") baseWageMultiplier = 0.70;
          else if (vendor.region === "Southern California") baseWageMultiplier = 0.67;
          else if (vendor.region === "National") baseWageMultiplier = 0.62;
          
          const employeeWage = Math.max(MINIMUM_WAGE, marketRate * baseWageMultiplier);
          const clientRate = calculateClientRate(employeeWage, vendor.markup, vendor.fee);
          const clientRateNum = parseFloat(clientRate);
          
          // Determine competitive status (within ±15% of market)
          const diff = ((clientRateNum - marketRate) / marketRate) * 100;
          const isCompetitive = diff >= -15 && diff <= 15;
          
          // CSTA compliance (CA vendors with proper fee structure)
          const isCSTA = vendor.state === "California" && vendor.fee <= 25;
          
          // Compliance verified (wage meets minimum + has proper documentation)
          const isCompliant = employeeWage >= MINIMUM_WAGE; // This is directly related to minimum_wage_compliance

          await base44.entities.VendorRate.create({
            vendor_name: vendor.name,
            category: category,
            role_name: roleName,
            employee_wage: parseFloat(employeeWage.toFixed(2)),
            markup_percentage: vendor.markup,
            vendor_fee_percentage: vendor.fee,
            client_rate: clientRateNum,
            is_active: true,
            minimum_wage_compliance: employeeWage >= MINIMUM_WAGE,
            pricing_status: analyzePricing(roleName, clientRateNum).status,
            market_average: marketRate,
            notes: `${vendor.region} - ${vendor.specialty}`,
            client_visibility: "all",
            competitive_status: isCompetitive,
            csta_compliant: isCSTA,
            compliance_verified: isCompliant
          });
          
          totalCreated++;
        }
      }

      queryClient.invalidateQueries({ queryKey: ['vendor-rates'] });
      
      toast({
        title: "✅ All Vendor Rates Generated!",
        description: `Created ${totalCreated} rate cards across ${VENDORS.length - 1} vendors (${allRoles.length} services each)`,
      });
      
    } catch (error) {
      console.error("Error generating vendor rates:", error);
      toast({
        title: "Error Generating Rates",
        description: error.message || "Something went wrong",
        variant: "destructive",
      });
    } finally {
      setGeneratingDemoData(false);
    }
  };

  const { data: rates = [], isLoading } = useQuery({
    queryKey: ['vendor-rates', selectedVendor, userRole, user?.company_name],
    queryFn: async () => {
      const allRates = await base44.entities.VendorRate.list();
      
      if (isVendor && user?.company_name) {
        return allRates.filter(r => r.vendor_name === user.company_name);
      }
      
      if (selectedVendor === "all") return allRates;
      return allRates.filter(r => r.vendor_name === selectedVendor);
    },
  });

  const { data: vendorSettings = [] } = useQuery({
    queryKey: ['vendor-default-settings'],
    queryFn: async () => {
      return await base44.entities.VendorDefaultSettings.list();
    },
    initialData: [],
  });

  const toggleVendorExpanded = (vendorName) => {
    setExpandedVendors(prev => ({
      ...prev,
      [vendorName]: !prev[vendorName]
    }));
  };

  const ratesByVendor = rates.reduce((acc, rate) => {
    if (!acc[rate.vendor_name]) acc[rate.vendor_name] = [];
    acc[rate.vendor_name].push(rate);
    return acc;
  }, {});

  // UPDATED: Enhanced filtering with search including state
  const filteredRatesByVendor = Object.entries(ratesByVendor).reduce((acc, [vendorName, vendorRates]) => {
    // Filter by vendor name search
    if (searchVendor.trim() && !vendorName.toLowerCase().includes(searchVendor.toLowerCase())) {
      return acc;
    }

    // Filter by location search (check vendor location from VENDORS list)
    const vendorInfo = VENDORS.find(v => v.name === vendorName);
    if (searchLocation.trim() && vendorInfo) {
      const locationMatch = 
        vendorInfo.region?.toLowerCase().includes(searchLocation.toLowerCase()) ||
        vendorInfo.city?.toLowerCase().includes(searchLocation.toLowerCase());
      if (!locationMatch) {
        return acc;
      }
    }

    // Filter by state search
    if (searchState.trim() && vendorInfo) {
      const stateMatch = vendorInfo.state?.toLowerCase().includes(searchState.toLowerCase());
      if (!stateMatch) {
        return acc;
      }
    }

    // Filter by category
    let filtered = activeCategory === "all"
      ? vendorRates
      : vendorRates.filter(r => r.category === activeCategory);

    // Filter by position/role search
    if (searchPosition.trim()) {
      filtered = filtered.filter(r => 
        r.role_name?.toLowerCase().includes(searchPosition.toLowerCase())
      );
    }

    if (filtered.length > 0) {
      acc[vendorName] = filtered;
    }
    return acc;
  }, {});

  const clearAllFilters = () => {
    setSearchVendor("");
    setSearchLocation("");
    setSearchState("");
    setSearchPosition("");
    setActiveCategory("all");
    setSelectedVendor("all");
  };

  const hasActiveFilters = searchVendor || searchLocation || searchState || searchPosition || activeCategory !== "all";

  return (
    <div className="p-4 md:p-8 bg-gradient-to-br from-slate-50 to-slate-100 min-h-screen">
      <div className="max-w-7xl mx-auto">
        <style>{`
          .toggle-blue[data-state="checked"] {
            background-color: #0A39DF !important;
          }
        `}</style>

        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-3xl font-bold text-[#1C323E]">Vendor Rate Cards</h1>
            <p className="text-slate-600 mt-1">Manage vendor rates, markup, and pricing across all locations</p>
          </div>
          
          <div className="flex gap-2">
            {isAdminOrProcurement && Object.keys(ratesByVendor).length < 5 && (
              <Button
                onClick={generateAllVendorRates}
                disabled={generatingDemoData}
                className="bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 text-white shadow-lg"
              >
                {generatingDemoData ? (
                  <>
                    <Loader2 className="w-5 h-5 mr-2 animate-spin" />
                    Generating...
                  </>
                ) : (
                  <>
                    <Sparkles className="w-5 h-5 mr-2" />
                    Generate All Vendor Rates
                  </>
                )}
              </Button>
            )}
          </div>
        </div>

        {/* UPDATED: Search & Filter Section - Now with 4 fields */}
        <Card className="border-slate-200 mb-6">
          <CardContent className="p-6">
            <div className="flex items-center justify-between mb-4">
              <Label className="text-sm font-semibold text-slate-700">Search & Filter</Label>
              {hasActiveFilters && (
                <Button 
                  variant="ghost" 
                  size="sm" 
                  onClick={clearAllFilters}
                  className="text-slate-500 hover:text-slate-700"
                >
                  Clear All Filters
                </Button>
              )}
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <div className="space-y-2">
                <Label htmlFor="search-vendor" className="text-xs text-slate-600">Search by Vendor</Label>
                <div className="relative">
                  <Building2 className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <Input
                    id="search-vendor"
                    type="text"
                    placeholder="Enter vendor name..."
                    value={searchVendor}
                    onChange={(e) => setSearchVendor(e.target.value)}
                    className="pl-10 border-slate-300"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="search-location" className="text-xs text-slate-600">Search by Region</Label>
                <div className="relative">
                  <MapPin className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <Input
                    id="search-location"
                    type="text"
                    placeholder="Bay Area, LA, National..."
                    value={searchLocation}
                    onChange={(e) => setSearchLocation(e.target.value)}
                    className="pl-10 border-slate-300"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="search-state" className="text-xs text-slate-600">Search by State</Label>
                <div className="relative">
                  <MapPin className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <Input
                    id="search-state"
                    type="text"
                    placeholder="California, Multiple..."
                    value={searchState}
                    onChange={(e) => setSearchState(e.target.value)}
                    className="pl-10 border-slate-300"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="search-position" className="text-xs text-slate-600">Search by Position</Label>
                <div className="relative">
                  <Briefcase className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <Input
                    id="search-position"
                    type="text"
                    placeholder="Cook, Server, Bartender..."
                    value={searchPosition}
                    onChange={(e) => setSearchPosition(e.target.value)}
                    className="pl-10 border-slate-300"
                  />
                </div>
              </div>
            </div>
            
            {/* Search Results Summary */}
            {hasActiveFilters && (
              <div className="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                <p className="text-sm text-blue-900">
                  <Search className="w-4 h-4 inline mr-2" />
                  Found <strong>{Object.keys(filteredRatesByVendor).length}</strong> vendors with <strong>{Object.values(filteredRatesByVendor).flat().length}</strong> total services
                </p>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Summary Stats */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          <Card className="border-slate-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-slate-600">Total Vendors</p>
                  <p className="text-2xl font-bold text-[#1C323E]">{Object.keys(filteredRatesByVendor).length}</p>
                </div>
                <Building2 className="w-8 h-8 text-[#0A39DF]" />
              </div>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-slate-600">Total Services</p>
                  <p className="text-2xl font-bold text-[#1C323E]">
                    {Object.values(filteredRatesByVendor).flat().length}
                  </p>
                </div>
                <Users className="w-8 h-8 text-emerald-600" />
              </div>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-slate-600">Competitive Rates</p>
                  <p className="text-2xl font-bold text-[#1C323E]">
                    {Object.values(filteredRatesByVendor).flat().filter(r => r.competitive_status).length}
                  </p>
                </div>
                <TrendingUp className="w-8 h-8 text-green-600" />
              </div>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-slate-600">Avg Partner Rate</p>
                  <p className="text-2xl font-bold text-[#1C323E]">
                    ${(Object.values(filteredRatesByVendor).flat().reduce((sum, r) => sum + parseFloat(r.client_rate || 0), 0) / (Object.values(filteredRatesByVendor).flat().length || 1)).toFixed(2)}
                  </p>
                </div>
                <DollarSign className="w-8 h-8 text-blue-600" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Category Tabs */}
        <div className="mb-6">
          <Card className="border-slate-200">
            <CardContent className="p-4">
              <Label className="text-sm font-medium mb-3 block text-slate-700">Service Category</Label>
              <div className="flex flex-wrap gap-2">
                <button
                  onClick={() => setActiveCategory("all")}
                  className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                    activeCategory === "all"
                      ? "bg-[#0A39DF] text-white shadow-md"
                      : "bg-white text-slate-600 border border-slate-200 hover:border-[#0A39DF] hover:text-[#0A39DF]"
                  }`}
                >
                  All Services
                </button>
                {CATEGORIES.map(cat => (
                  <button
                    key={cat}
                    onClick={() => setActiveCategory(cat)}
                    className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                      activeCategory === cat
                        ? "bg-[#0A39DF] text-white shadow-md"
                        : "bg-white text-slate-600 border border-slate-200 hover:border-[#0A39DF] hover:text-[#0A39DF]"
                    }`}
                  >
                    {cat}
                  </button>
                ))}
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Vendor Cards */}
        <div className="space-y-4">
          {Object.keys(filteredRatesByVendor).length === 0 ? (
            <div className="text-center py-16 bg-white rounded-xl border border-slate-200">
              {hasActiveFilters ? (
                <>
                  <Search className="w-16 h-16 mx-auto text-slate-300 mb-4" />
                  <h3 className="text-xl font-semibold text-slate-900 mb-2">No Matching Results</h3>
                  <p className="text-slate-600 mb-6">Try adjusting your search filters</p>
                  <Button onClick={clearAllFilters} variant="outline">
                    Clear All Filters
                  </Button>
                </>
              ) : (
                <>
                  <Building2 className="w-16 h-16 mx-auto text-slate-300 mb-4" />
                  <h3 className="text-xl font-semibold text-slate-900 mb-2">No Rates Found</h3>
                  <p className="text-slate-600 mb-6">Generate rates for all vendors to get started</p>
                  {isAdminOrProcurement && (
                    <Button
                      onClick={generateAllVendorRates}
                      className="bg-[#0A39DF] hover:bg-[#0A39DF]/90"
                      disabled={generatingDemoData}
                    >
                      {generatingDemoData ? (
                        <>
                          <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                          Generating...
                        </>
                      ) : (
                        <>
                          <Sparkles className="w-4 h-4 mr-2" />
                          Generate All Vendor Rates
                        </>
                      )}
                    </Button>
                  )}
                </>
              )}
            </div>
          ) : (
            Object.entries(filteredRatesByVendor).map(([vendorName, vendorRates]) => {
              const vendorDefaults = vendorSettings.find(s => s.vendor_name === vendorName);
              const vendorInfo = VENDORS.find(v => v.name === vendorName);
              const isExpanded = expandedVendors[vendorName];
              
              // Calculate vendor-level tags
              const competitiveCount = vendorRates.filter(r => r.competitive_status).length;
              const cstaCompliantCount = vendorRates.filter(r => r.csta_compliant).length;
              const complianceCount = vendorRates.filter(r => r.compliance_verified).length;
              const totalRates = vendorRates.length;

              return (
                <Card key={vendorName} className="border-slate-200 shadow-sm hover:shadow-md transition-shadow">
                  <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b border-slate-100 p-4">
                    <div className="flex items-center justify-between">
                      <div 
                        className="flex items-center gap-3 flex-1 cursor-pointer" 
                        onClick={() => toggleVendorExpanded(vendorName)}
                      >
                        <div className="w-12 h-12 bg-gradient-to-br from-[#0A39DF] to-[#1C323E] rounded-xl flex items-center justify-center flex-shrink-0">
                          <Building2 className="w-6 h-6 text-white" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 mb-1">
                            <CardTitle className="text-base font-semibold text-[#1C323E]">{vendorName}</CardTitle>
                            {isExpanded ? (
                              <ChevronUp className="w-4 h-4 text-slate-400 flex-shrink-0" />
                            ) : (
                              <ChevronDown className="w-4 h-4 text-slate-400 flex-shrink-0" />
                            )}
                          </div>
                          
                          {vendorInfo && (
                            <p className="text-xs text-slate-500 mb-2">{vendorInfo.city}, {vendorInfo.state} • {vendorInfo.specialty}</p>
                          )}
                          
                          <div className="flex items-center gap-2 mt-2 flex-wrap">
                            {vendorDefaults && (
                              <>
                                <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200 text-xs font-medium">
                                  <TrendingUp className="w-3 h-3 mr-1" />
                                  Markup: {vendorDefaults.default_markup_percentage}%
                                </Badge>
                                <Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-200 text-xs font-medium">
                                  <DollarSign className="w-3 h-3 mr-1" />
                                  VA: {vendorDefaults.default_vendor_fee_percentage}%
                                </Badge>
                              </>
                            )}
                            {totalRates > 0 && complianceCount === totalRates && (
                              <Badge className="bg-green-100 text-green-700 text-xs font-medium border-0">
                                <CheckCircle2 className="w-3 h-3 mr-1" />
                                Full Compliance
                              </Badge>
                            )}
                            {totalRates > 0 && competitiveCount / totalRates >= 0.8 && (
                              <Badge className="bg-blue-100 text-blue-700 text-xs font-medium border-0">
                                <TrendingUp className="w-3 h-3 mr-1" />
                                Competitive
                              </Badge>
                            )}
                            {vendorInfo && vendorInfo.csat && (
                              <Badge className="bg-emerald-100 text-emerald-700 text-xs font-medium border-0">
                                ⭐ CSAT {vendorInfo.csat.toFixed(1)}
                              </Badge>
                            )}
                            <span className="text-xs text-slate-500 font-medium">
                              {vendorRates.length} {vendorRates.length === 1 ? 'service' : 'services'}
                            </span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </CardHeader>

                  {isExpanded && (
                    <CardContent className="p-6">
                      <div className="space-y-3">
                        {vendorRates.map(rate => {
                          const analysis = analyzePricing(rate.role_name, rate.client_rate);
                          const Icon = analysis.icon;

                          const baseWage = rate.employee_wage;
                          const markupAmount = baseWage * (rate.markup_percentage / 100);
                          const subtotal = baseWage + markupAmount;
                          const feeAmount = subtotal * (rate.vendor_fee_percentage / 100);

                          return (
                            <div
                              key={rate.id}
                              className="flex items-center justify-between p-4 bg-slate-50 rounded-lg border border-slate-200 hover:border-[#0A39DF] transition-all"
                            >
                              <div className="flex items-center gap-4 flex-1">
                                <div className="w-48">
                                  <p className="font-semibold text-[#1C323E]">{rate.role_name}</p>
                                  <p className="text-xs text-slate-500">$/hourly</p>
                                  <div className="flex items-center gap-1 mt-1 flex-wrap">
                                    <Badge variant="outline" className="text-[10px]">
                                      {rate.category}
                                    </Badge>
                                    {rate.competitive_status && (
                                      <Badge className="bg-green-100 text-green-700 text-[10px] h-auto px-2 py-0.5">
                                        Competitive
                                      </Badge>
                                    )}
                                    {rate.csta_compliant && (
                                      <Badge className="bg-blue-100 text-blue-700 text-[10px] h-auto px-2 py-0.5">
                                        CSTA
                                      </Badge>
                                    )}
                                    {rate.compliance_verified && (
                                      <Badge className="bg-emerald-100 text-emerald-700 text-[10px] h-auto px-2 py-0.5">
                                        Compliance
                                      </Badge>
                                    )}
                                  </div>
                                </div>

                                <div className="flex-1 min-w-[300px]">
                                  <div className="flex items-center gap-2 mb-2">
                                    <div className="flex-1 bg-slate-200 rounded-full h-6 overflow-hidden flex text-xs font-semibold">
                                      <div
                                        className="bg-emerald-500 flex items-center justify-center text-white"
                                        style={{ width: `${(baseWage / parseFloat(rate.client_rate || 1)) * 100}%` }}
                                        title={`Employee Wage: $${baseWage.toFixed(2)}/hr`}
                                      >
                                        ${baseWage.toFixed(2)}
                                      </div>
                                      <div
                                        className="bg-blue-500 flex items-center justify-center text-white"
                                        style={{ width: `${(markupAmount / parseFloat(rate.client_rate || 1)) * 100}%` }}
                                        title={`Markup: ${rate.markup_percentage}% = $${markupAmount.toFixed(2)}/hr`}
                                      >
                                        {rate.markup_percentage}%
                                      </div>
                                      <div
                                        className="bg-purple-500 flex items-center justify-center text-white"
                                        style={{ width: `${(feeAmount / parseFloat(rate.client_rate || 1)) * 100}%` }}
                                        title={`Vendor Fee: ${rate.vendor_fee_percentage}% = $${feeAmount.toFixed(2)}/hr`}
                                      >
                                        {rate.vendor_fee_percentage}%
                                      </div>
                                    </div>
                                  </div>
                                  <div className="flex items-center justify-between text-[10px] text-slate-600">
                                    <span>Wage: ${baseWage.toFixed(2)}</span>
                                    <span>Markup: {rate.markup_percentage}% (+${markupAmount.toFixed(2)})</span>
                                    <span>VA Fee: {rate.vendor_fee_percentage}% (+${feeAmount.toFixed(2)})</span>
                                  </div>
                                </div>

                                <div className="w-24 text-right">
                                  <p className="text-2xl font-bold text-[#0A39DF]">${rate.client_rate}</p>
                                  <p className="text-xs text-slate-500">/hourly</p>
                                </div>

                                <div className="w-32">
                                  <div className={`flex items-center gap-2 px-3 py-2 rounded-lg ${analysis.bg}`}>
                                    <Icon className={`w-4 h-4 ${analysis.color}`} />
                                    <div>
                                      <p className={`text-xs font-semibold ${analysis.color}`}>{analysis.status.charAt(0).toUpperCase() + analysis.status.slice(1)}</p>
                                      <p className="text-[10px] text-slate-600">{analysis.message}</p>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    </CardContent>
                  )}
                </Card>
              );
            })
          )}
        </div>
      </div>
    </div>
  );
}
