import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useToast } from "@/components/ui/use-toast";
import {
  Target, Users, DollarSign, CheckCircle, ArrowRight,
  Building2, Clock, Sparkles, AlertTriangle, Send, Shield,
  FileText, MapPin, Phone, Mail, Star, XCircle, UserPlus,
  Briefcase, CheckSquare, AlertCircle
} from "lucide-react";

export default function ConversionModal({ open, onClose, opportunity, vendors = [], userRole }) {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [step, setStep] = useState(1);
  const [conversionType, setConversionType] = useState(""); // "existing" or "new"
  const [selectedVendor, setSelectedVendor] = useState("");
  const [selectedWorkers, setSelectedWorkers] = useState([]);
  const [notes, setNotes] = useState("");
  const [urgency, setUrgency] = useState("normal");
  
  // New vendor referral fields
  const [newVendor, setNewVendor] = useState({
    legal_name: "",
    contact_name: "",
    email: "",
    phone: "",
    region: "",
    services: "",
    reason: "",
    estimated_rate: "",
  });

  // For Clients: Mock workers for the opportunity
  const affectedWorkers = Array.from({ length: opportunity?.count || 5 }, (_, i) => ({
    id: `worker-${i + 1}`,
    name: `Worker ${i + 1}`,
    role: ["Server", "Bartender", "Cook", "Host", "Busser"][i % 5],
    currentRate: 22 + Math.random() * 10,
    assignments: Math.floor(Math.random() * 20) + 5,
  }));

  // For Procurement: Mock vendors to consolidate
  const affectedVendors = Array.from({ length: opportunity?.count || 5 }, (_, i) => ({
    id: `vendor-aff-${i + 1}`,
    name: ["Bay Area Events", "Quick Staff Inc.", "Metro Workforce", "City Staffing Co.", "Premier Temps"][i % 5],
    tier: i < 2 ? "Tier 1" : i < 4 ? "Tier 2" : "Tier 3",
    currentSpend: 15000 + Math.random() * 20000,
    rate: 45 + Math.random() * 15,
    reliability: 75 + Math.random() * 20,
  }));

  const isProcurement = userRole === "procurement" || userRole === "admin" || userRole === "operator";

  const createTaskMutation = useMutation({
    mutationFn: (taskData) => base44.entities.Task.create(taskData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
    },
  });

  const createVendorInviteMutation = useMutation({
    mutationFn: (inviteData) => base44.entities.VendorInvite.create(inviteData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vendor-invites'] });
    },
  });

  const handleClose = () => {
    setStep(1);
    setConversionType("");
    setSelectedVendor("");
    setSelectedWorkers([]);
    setNotes("");
    setUrgency("normal");
    setNewVendor({
      legal_name: "",
      contact_name: "",
      email: "",
      phone: "",
      region: "",
      services: "",
      reason: "",
      estimated_rate: "",
    });
    onClose();
  };

  const handleSubmit = async () => {
    if (conversionType === "new") {
      // Create Vendor Referral Task for Procurement
      const referralTask = {
        task_name: `Vendor Referral: ${newVendor.legal_name}`,
        team_id: "procurement",
        description: `**New Vendor Referral Request**\n\n**Vendor Details:**\n- Company: ${newVendor.legal_name}\n- Contact: ${newVendor.contact_name}\n- Email: ${newVendor.email}\n- Phone: ${newVendor.phone}\n- Region: ${newVendor.region}\n\n**Services Needed:** ${newVendor.services}\n\n**Estimated Rate:** ${newVendor.estimated_rate}\n\n**Reason for Request:** ${newVendor.reason}\n\n**Conversion Opportunity:** ${opportunity?.category}\n**Potential Savings:** $${opportunity?.potentialSavings?.toLocaleString()}\n**Workers to Convert:** ${selectedWorkers.length}\n\n**Urgency:** ${urgency}\n\n**Additional Notes:** ${notes}\n\n---\n**Action Required:**\n1. Verify vendor credentials\n2. Review insurance & compliance docs\n3. Evaluate rate alignment\n4. Approve/Reject for Preferred Network`,
        status: "pending",
        priority: urgency === "urgent" ? "high" : "normal",
        due_date: new Date(Date.now() + (urgency === "urgent" ? 3 : 7) * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      };

      // Also create vendor invite record
      const vendorInvite = {
        vendor_name: newVendor.legal_name,
        contact_name: newVendor.contact_name,
        email: newVendor.email,
        phone: newVendor.phone,
        status: "pending_review",
        referral_reason: newVendor.reason,
        services_requested: newVendor.services,
        region: newVendor.region,
        notes: `Referred via Conversion Engine. Category: ${opportunity?.category}. Potential Savings: $${opportunity?.potentialSavings?.toLocaleString()}`,
      };

      await Promise.all([
        createTaskMutation.mutateAsync(referralTask),
        createVendorInviteMutation.mutateAsync(vendorInvite),
      ]);

      toast({
        title: "Vendor Referral Submitted",
        description: `${newVendor.legal_name} has been sent to Procurement for review and approval.`,
      });
    } else {
      // Existing vendor conversion
      const taskData = {
        task_name: isProcurement 
          ? `Vendor Consolidation: ${opportunity?.category}` 
          : `Rate Optimization: ${opportunity?.category}`,
        team_id: "procurement",
        description: isProcurement
          ? `**Vendor Consolidation Request**\n\n**Category:** ${opportunity?.category}\n**Target Tier 1 Vendor:** ${vendors.find(v => v.id === selectedVendor)?.legal_name || selectedVendor}\n**Vendors to Consolidate:** ${selectedWorkers.length}\n**Potential Savings:** $${opportunity?.potentialSavings?.toLocaleString()}\n\n**Urgency:** ${urgency}\n\n**Notes:** ${notes}\n\n---\n**Action Required:**\n1. Review vendor spend analysis\n2. Negotiate volume discounts\n3. Migrate contracts to preferred vendor\n4. Track consolidated savings`
          : `**Staff Rate Optimization**\n\n**Category:** ${opportunity?.category}\n**Target Vendor:** ${vendors.find(v => v.id === selectedVendor)?.legal_name || selectedVendor}\n**Positions Selected:** ${selectedWorkers.length}\n**Potential Savings:** $${opportunity?.potentialSavings?.toLocaleString()}\n\n**Urgency:** ${urgency}\n\n**Notes:** ${notes}\n\n---\n**Action Required:**\n1. Confirm rate book assignment\n2. Update position assignments\n3. Track savings in dashboard`,
        status: "pending",
        priority: urgency === "urgent" ? "high" : "normal",
        due_date: new Date(Date.now() + (urgency === "urgent" ? 3 : 7) * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      };

      await createTaskMutation.mutateAsync(taskData);

      toast({
        title: isProcurement ? "Vendor Consolidation Submitted" : "Optimization Request Submitted",
        description: isProcurement 
          ? `${selectedWorkers.length} vendors will be consolidated to ${vendors.find(v => v.id === selectedVendor)?.legal_name || "preferred vendor"}.`
          : `${selectedWorkers.length} positions will be optimized with ${vendors.find(v => v.id === selectedVendor)?.legal_name || "preferred vendor"}.`,
      });
    }

    handleClose();
  };

  const toggleItem = (itemId) => {
    setSelectedWorkers(prev =>
      prev.includes(itemId)
        ? prev.filter(id => id !== itemId)
        : [...prev, itemId]
    );
  };

  const selectAllItems = () => {
    const items = isProcurement ? affectedVendors : affectedWorkers;
    if (selectedWorkers.length === items.length) {
      setSelectedWorkers([]);
    } else {
      setSelectedWorkers(items.map(w => w.id));
    }
  };

  if (!opportunity) return null;

  const totalSteps = conversionType === "new" ? 4 : 3;

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Target className="w-5 h-5 text-[#0A39DF]" />
            {conversionType === "new" ? "New Vendor Referral" : "Start Conversion"}: {opportunity.category}
          </DialogTitle>
        </DialogHeader>

        {/* Progress Steps */}
        <div className="flex items-center gap-2 mb-6">
          {Array.from({ length: totalSteps }, (_, i) => i + 1).map((s) => (
            <React.Fragment key={s}>
              <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold ${
                step >= s ? 'bg-[#0A39DF] text-white' : 'bg-slate-200 text-slate-500'
              }`}>
                {step > s ? <CheckCircle className="w-4 h-4" /> : s}
              </div>
              {s < totalSteps && (
                <div className={`flex-1 h-1 rounded ${step > s ? 'bg-[#0A39DF]' : 'bg-slate-200'}`} />
              )}
            </React.Fragment>
          ))}
        </div>

        {/* Step 1: Choose Conversion Type */}
        {step === 1 && (
          <div className="space-y-4">
            <div className="bg-gradient-to-r from-blue-50 to-purple-50 p-4 rounded-xl border border-blue-100">
              <h4 className="font-semibold text-slate-900 mb-3">Conversion Opportunity Summary</h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-xs text-slate-500">Current Spend</p>
                  <p className="text-lg font-bold text-slate-900">
                    ${opportunity.currentSpend?.toLocaleString(undefined, { maximumFractionDigits: 0 })}
                  </p>
                </div>
                <div>
                  <p className="text-xs text-slate-500">Potential Savings</p>
                  <p className="text-lg font-bold text-green-600">
                    ${opportunity.potentialSavings?.toLocaleString(undefined, { maximumFractionDigits: 0 })}
                  </p>
                </div>
                <div>
                  <p className="text-xs text-slate-500">{isProcurement ? "Vendors Affected" : "Positions Affected"}</p>
                  <p className="text-lg font-bold text-slate-900">{opportunity.count} {opportunity.countLabel}</p>
                </div>
                <div>
                  <p className="text-xs text-slate-500">Savings Rate</p>
                  <p className="text-lg font-bold text-amber-600">{opportunity.savingsPercent}%</p>
                </div>
              </div>
            </div>

            <h4 className="font-semibold text-slate-900">How would you like to convert?</h4>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <Card 
                className={`cursor-pointer transition-all hover:shadow-md ${
                  conversionType === "existing" ? 'ring-2 ring-[#0A39DF] bg-blue-50' : 'hover:bg-slate-50'
                }`}
                onClick={() => setConversionType("existing")}
              >
                <CardContent className="p-4">
                  <div className="flex items-start gap-3">
                    <div className="w-10 h-10 bg-emerald-100 rounded-lg flex items-center justify-center">
                      <Shield className="w-5 h-5 text-emerald-600" />
                    </div>
                    <div>
                      <h5 className="font-semibold text-slate-900">Preferred Vendor Network</h5>
                      <p className="text-sm text-slate-500 mt-1">
                        Convert to an already approved vendor in your network
                      </p>
                      <Badge className="mt-2 bg-emerald-100 text-emerald-700">
                        <CheckCircle className="w-3 h-3 mr-1" />
                        Pre-Approved
                      </Badge>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card 
                className={`cursor-pointer transition-all hover:shadow-md ${
                  conversionType === "new" ? 'ring-2 ring-[#0A39DF] bg-blue-50' : 'hover:bg-slate-50'
                }`}
                onClick={() => setConversionType("new")}
              >
                <CardContent className="p-4">
                  <div className="flex items-start gap-3">
                    <div className="w-10 h-10 bg-amber-100 rounded-lg flex items-center justify-center">
                      <UserPlus className="w-5 h-5 text-amber-600" />
                    </div>
                    <div>
                      <h5 className="font-semibold text-slate-900">New Vendor Referral</h5>
                      <p className="text-sm text-slate-500 mt-1">
                        Refer a new vendor for procurement approval
                      </p>
                      <Badge className="mt-2 bg-amber-100 text-amber-700">
                        <AlertCircle className="w-3 h-3 mr-1" />
                        Requires Approval
                      </Badge>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>

            {conversionType === "new" && (
              <div className="bg-amber-50 p-4 rounded-xl border border-amber-200">
                <div className="flex items-start gap-3">
                  <AlertTriangle className="w-5 h-5 text-amber-600 mt-0.5" />
                  <div>
                    <p className="font-semibold text-amber-900">Vendor Referral Workflow</p>
                    <p className="text-sm text-amber-700 mt-1">
                      This vendor will be flagged as "Not Yet Approved" and sent to Procurement for review. 
                      They'll evaluate pricing, insurance, compliance, and SLA capability before approval.
                    </p>
                  </div>
                </div>
              </div>
            )}
          </div>
        )}

        {/* Step 2 for New Vendor: Vendor Details */}
        {step === 2 && conversionType === "new" && (
          <div className="space-y-4">
            <div className="bg-blue-50 p-3 rounded-lg border border-blue-200 flex items-center gap-2">
              <FileText className="w-5 h-5 text-blue-600" />
              <p className="text-sm text-blue-800">
                <strong>Vendor Referral Form</strong> — This will be sent to Procurement for review
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="text-sm font-medium text-slate-700 mb-1 block">Company Name *</label>
                <Input
                  value={newVendor.legal_name}
                  onChange={(e) => setNewVendor({ ...newVendor, legal_name: e.target.value })}
                  placeholder="e.g., Bay Area Staffing Co."
                />
              </div>
              <div>
                <label className="text-sm font-medium text-slate-700 mb-1 block">Contact Name *</label>
                <Input
                  value={newVendor.contact_name}
                  onChange={(e) => setNewVendor({ ...newVendor, contact_name: e.target.value })}
                  placeholder="e.g., John Smith"
                />
              </div>
              <div>
                <label className="text-sm font-medium text-slate-700 mb-1 block">Email *</label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <Input
                    value={newVendor.email}
                    onChange={(e) => setNewVendor({ ...newVendor, email: e.target.value })}
                    placeholder="vendor@company.com"
                    className="pl-10"
                  />
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-slate-700 mb-1 block">Phone</label>
                <div className="relative">
                  <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <Input
                    value={newVendor.phone}
                    onChange={(e) => setNewVendor({ ...newVendor, phone: e.target.value })}
                    placeholder="(555) 123-4567"
                    className="pl-10"
                  />
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-slate-700 mb-1 block">Region / Location</label>
                <div className="relative">
                  <MapPin className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <Input
                    value={newVendor.region}
                    onChange={(e) => setNewVendor({ ...newVendor, region: e.target.value })}
                    placeholder="e.g., Bay Area, Los Angeles"
                    className="pl-10"
                  />
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-slate-700 mb-1 block">Estimated Hourly Rate</label>
                <div className="relative">
                  <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <Input
                    value={newVendor.estimated_rate}
                    onChange={(e) => setNewVendor({ ...newVendor, estimated_rate: e.target.value })}
                    placeholder="e.g., $35-45/hr"
                    className="pl-10"
                  />
                </div>
              </div>
            </div>

            <div>
              <label className="text-sm font-medium text-slate-700 mb-1 block">Services Needed *</label>
              <Textarea
                value={newVendor.services}
                onChange={(e) => setNewVendor({ ...newVendor, services: e.target.value })}
                placeholder="e.g., Event catering staff, bartenders, servers for corporate events..."
                className="h-20"
              />
            </div>

            <div>
              <label className="text-sm font-medium text-slate-700 mb-1 block">Reason for Request *</label>
              <Textarea
                value={newVendor.reason}
                onChange={(e) => setNewVendor({ ...newVendor, reason: e.target.value })}
                placeholder="Why do you need this vendor? e.g., Local specialist, unique skills, better coverage in specific area..."
                className="h-20"
              />
            </div>
          </div>
        )}

        {/* Step 2 for Existing / Step 3 for New: Select Items */}
        {((step === 2 && conversionType === "existing") || (step === 3 && conversionType === "new")) && (
          <div className="space-y-4">
            {conversionType === "existing" && (
              <div>
                <label className="text-sm font-medium text-slate-700 mb-2 block">
                  {isProcurement ? "Select Target Preferred Vendor" : "Select Preferred Vendor"}
                </label>
                <Select value={selectedVendor} onValueChange={setSelectedVendor}>
                  <SelectTrigger>
                    <SelectValue placeholder="Choose from approved vendors" />
                  </SelectTrigger>
                  <SelectContent>
                    {vendors.length > 0 ? vendors.filter(v => v.approval_status === "approved" || v.is_active).map((vendor) => (
                      <SelectItem key={vendor.id} value={vendor.id}>
                        <div className="flex items-center gap-2">
                          <Shield className="w-4 h-4 text-emerald-500" />
                          {vendor.legal_name || vendor.doing_business_as}
                          <Badge className="ml-2 bg-emerald-100 text-emerald-700 text-[10px]">Tier 1</Badge>
                        </div>
                      </SelectItem>
                    )) : (
                      <>
                        <SelectItem value="vendor-1">
                          <div className="flex items-center gap-2">
                            <Shield className="w-4 h-4 text-emerald-500" />
                            Premier Staffing Co.
                            <Badge className="ml-2 bg-emerald-100 text-emerald-700 text-[10px]">Tier 1</Badge>
                          </div>
                        </SelectItem>
                        <SelectItem value="vendor-2">
                          <div className="flex items-center gap-2">
                            <Shield className="w-4 h-4 text-emerald-500" />
                            Elite Workforce Solutions
                            <Badge className="ml-2 bg-emerald-100 text-emerald-700 text-[10px]">Tier 1</Badge>
                          </div>
                        </SelectItem>
                        <SelectItem value="vendor-3">
                          <div className="flex items-center gap-2">
                            <Shield className="w-4 h-4 text-emerald-500" />
                            Compass Preferred Partners
                            <Badge className="ml-2 bg-emerald-100 text-emerald-700 text-[10px]">Tier 1</Badge>
                          </div>
                        </SelectItem>
                      </>
                    )}
                  </SelectContent>
                </Select>
              </div>
            )}

            {/* Procurement: Select Vendors to Consolidate */}
            {isProcurement ? (
              <div>
                <div className="flex items-center justify-between mb-2">
                  <label className="text-sm font-medium text-slate-700">
                    Select Vendors to Consolidate ({selectedWorkers.length}/{affectedVendors.length})
                  </label>
                  <Button variant="ghost" size="sm" onClick={selectAllItems}>
                    {selectedWorkers.length === affectedVendors.length ? "Deselect All" : "Select All"}
                  </Button>
                </div>
                <div className="border rounded-lg divide-y max-h-48 overflow-y-auto">
                  {affectedVendors.map((vendor) => (
                    <div
                      key={vendor.id}
                      className={`flex items-center gap-3 p-3 cursor-pointer hover:bg-slate-50 ${
                        selectedWorkers.includes(vendor.id) ? 'bg-blue-50' : ''
                      }`}
                      onClick={() => toggleItem(vendor.id)}
                    >
                      <Checkbox checked={selectedWorkers.includes(vendor.id)} />
                      <div className="flex-1">
                        <p className="font-medium text-sm">{vendor.name}</p>
                        <Badge className={`text-[10px] ${
                          vendor.tier === "Tier 1" ? "bg-emerald-100 text-emerald-700" :
                          vendor.tier === "Tier 2" ? "bg-amber-100 text-amber-700" :
                          "bg-red-100 text-red-700"
                        }`}>{vendor.tier}</Badge>
                      </div>
                      <div className="text-right">
                        <p className="text-sm font-medium">${vendor.currentSpend.toLocaleString(undefined, { maximumFractionDigits: 0 })}</p>
                        <p className="text-xs text-slate-500">${vendor.rate.toFixed(0)}/hr avg</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ) : (
              /* Client: Select Workers/Positions */
              <div>
                <div className="flex items-center justify-between mb-2">
                  <label className="text-sm font-medium text-slate-700">
                    Select Positions to Optimize ({selectedWorkers.length}/{affectedWorkers.length})
                  </label>
                  <Button variant="ghost" size="sm" onClick={selectAllItems}>
                    {selectedWorkers.length === affectedWorkers.length ? "Deselect All" : "Select All"}
                  </Button>
                </div>
                <div className="border rounded-lg divide-y max-h-48 overflow-y-auto">
                  {affectedWorkers.map((worker) => (
                    <div
                      key={worker.id}
                      className={`flex items-center gap-3 p-3 cursor-pointer hover:bg-slate-50 ${
                        selectedWorkers.includes(worker.id) ? 'bg-blue-50' : ''
                      }`}
                      onClick={() => toggleItem(worker.id)}
                    >
                      <Checkbox checked={selectedWorkers.includes(worker.id)} />
                      <div className="flex-1">
                        <p className="font-medium text-sm">{worker.name}</p>
                        <p className="text-xs text-slate-500">{worker.role}</p>
                      </div>
                      <div className="text-right">
                        <p className="text-sm font-medium">${worker.currentRate.toFixed(2)}/hr</p>
                        <p className="text-xs text-slate-500">{worker.assignments} shifts</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}

        {/* Final Step: Confirm & Submit */}
        {((step === 3 && conversionType === "existing") || (step === 4 && conversionType === "new")) && (
          <div className="space-y-4">
            <div className={`p-4 rounded-xl border ${
              conversionType === "new" 
                ? 'bg-amber-50 border-amber-200' 
                : 'bg-emerald-50 border-emerald-200'
            }`}>
              <h4 className={`font-semibold mb-2 flex items-center gap-2 ${
                conversionType === "new" ? 'text-amber-900' : 'text-emerald-900'
              }`}>
                {conversionType === "new" ? (
                  <>
                    <Send className="w-5 h-5" />
                    Vendor Referral Summary
                  </>
                ) : (
                  <>
                    <CheckCircle className="w-5 h-5" />
                    Conversion Request Summary
                  </>
                )}
              </h4>
              <div className="space-y-2 text-sm">
                <p><strong>Category:</strong> {opportunity.category}</p>
                <p><strong>{isProcurement ? "Vendors" : "Positions"} Selected:</strong> {selectedWorkers.length}</p>
                {conversionType === "new" ? (
                  <>
                    <p><strong>New Vendor:</strong> {newVendor.legal_name}</p>
                    <p><strong>Contact:</strong> {newVendor.contact_name} ({newVendor.email})</p>
                    <p><strong>Status:</strong> <Badge className="bg-amber-100 text-amber-700">Pending Procurement Review</Badge></p>
                  </>
                ) : (
                  <p><strong>Target Vendor:</strong> {vendors.find(v => v.id === selectedVendor)?.legal_name || selectedVendor}</p>
                )}
                <p><strong>Estimated Savings:</strong> <span className="text-green-600 font-bold">${Math.round((opportunity.potentialSavings || 0) * (selectedWorkers.length / Math.max(opportunity.count || 1, 1))).toLocaleString()} ({opportunity.savingsPercent || 0}%)</span></p>
              </div>
            </div>

            {conversionType === "new" && (
              <div className="bg-blue-50 p-4 rounded-xl border border-blue-200">
                <h5 className="font-semibold text-blue-900 mb-2 flex items-center gap-2">
                  <Briefcase className="w-4 h-4" />
                  What Happens Next?
                </h5>
                <ol className="text-sm text-blue-800 space-y-1 list-decimal list-inside">
                  <li>Vendor referral sent to Procurement team</li>
                  <li>Procurement evaluates pricing, insurance & compliance</li>
                  <li>Vendor approved → added to Preferred Network</li>
                  <li>Spot labor automatically converts to contracted savings</li>
                </ol>
              </div>
            )}

            <div>
              <label className="text-sm font-medium text-slate-700 mb-2 block">
                Urgency Level
              </label>
              <Select value={urgency} onValueChange={setUrgency}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="low">
                    <div className="flex items-center gap-2">
                      <Clock className="w-4 h-4 text-slate-400" />
                      Low — Within 2 weeks
                    </div>
                  </SelectItem>
                  <SelectItem value="normal">
                    <div className="flex items-center gap-2">
                      <Clock className="w-4 h-4 text-blue-500" />
                      Normal — Within 1 week
                    </div>
                  </SelectItem>
                  <SelectItem value="urgent">
                    <div className="flex items-center gap-2">
                      <AlertTriangle className="w-4 h-4 text-red-500" />
                      Urgent — Within 3 days
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <label className="text-sm font-medium text-slate-700 mb-2 block">
                Additional Notes (Optional)
              </label>
              <Textarea
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="Add any special requirements or instructions..."
                className="h-20"
              />
            </div>
          </div>
        )}

        <DialogFooter className="flex gap-2 mt-6">
          {step > 1 && (
            <Button variant="outline" onClick={() => setStep(step - 1)}>
              Back
            </Button>
          )}
          <Button variant="outline" onClick={handleClose}>
            Cancel
          </Button>
          {step === 1 ? (
            <Button
              onClick={() => setStep(2)}
              className="bg-[#0A39DF] hover:bg-[#0831b8]"
              disabled={!conversionType}
            >
              Continue
              <ArrowRight className="w-4 h-4 ml-2" />
            </Button>
          ) : step < totalSteps ? (
            <Button
              onClick={() => setStep(step + 1)}
              className="bg-[#0A39DF] hover:bg-[#0831b8]"
              disabled={
                (step === 2 && conversionType === "new" && (!newVendor.legal_name || !newVendor.email || !newVendor.services || !newVendor.reason)) ||
                ((step === 2 && conversionType === "existing") || (step === 3 && conversionType === "new")) && selectedWorkers.length === 0
              }
            >
              Continue
              <ArrowRight className="w-4 h-4 ml-2" />
            </Button>
          ) : (
            <Button
              onClick={handleSubmit}
              className={conversionType === "new" ? "bg-amber-600 hover:bg-amber-700" : "bg-emerald-600 hover:bg-emerald-700"}
              disabled={createTaskMutation.isPending || createVendorInviteMutation.isPending}
            >
              <Send className="w-4 h-4 mr-2" />
              {createTaskMutation.isPending || createVendorInviteMutation.isPending 
                ? "Submitting..." 
                : conversionType === "new" 
                  ? "Submit Vendor Referral" 
                  : "Submit Conversion Request"
              }
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}