import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useMutation, useQueryClient, useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { 
  ArrowLeft, 
  ArrowRight, 
  Check, 
  FileText, 
  Building2, 
  DollarSign, 
  Shield, 
  MapPin,
  Sparkles,
  FileCheck,
  TrendingUp
} from "lucide-react";
import PageHeader from "@/components/common/PageHeader";
import { useToast } from "@/components/ui/use-toast";

const ONBOARDING_STEPS = [
  { id: 1, title: "Vendor Onboard", icon: Building2, description: "Basic vendor information" },
  { id: 2, title: "NDA", icon: Shield, description: "Sign and Accept Non-Disclosure Agreement" },
  { id: 3, title: "Contract", icon: FileText, description: "Master service agreement" },
  { id: 4, title: "Performance & VA Structure", icon: TrendingUp, description: "Performance metrics and VA structure" },
  { id: 5, title: "Documents & Validation", icon: FileCheck, description: "Upload compliance documents" },
  { id: 6, title: "Service & Coverage", icon: MapPin, description: "Service areas and coverage" },
  { id: 7, title: "Rate Proposal", icon: DollarSign, description: "Submit your rate proposal" },
  { id: 8, title: "AI Intelligence", icon: Sparkles, description: "AI-powered optimization" }
];

export default function VendorOnboarding() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { toast } = useToast();
  const [currentStep, setCurrentStep] = useState(1);

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

  const userRole = user?.user_role || user?.role;
  const isBuyer = userRole === "procurement" || userRole === "admin";

  const [vendorData, setVendorData] = useState({
    // Step 1: Vendor Onboard
    legal_name: "",
    doing_business_as: "",
    tax_id: "",
    business_type: "LLC",
    primary_contact_name: "",
    primary_contact_email: "",
    primary_contact_phone: "",
    billing_address: "",
    
    // Step 2: NDA
    nda_acknowledged: false,
    nda_signed_by: "",
    nda_signature_date: "",
    nda_signature_time: "",
    
    // Step 3: Contract
    contract_acknowledged: false,
    contract_signed_date: "",
    
    // Step 4: Performance & VA Structure
    performance_metrics_agreed: false,
    va_structure_type: "",
    
    // Step 5: Documents & Validation
    w9_document: "",
    coi_document: "",
    insurance_expiry: "",
    
    // Step 6: Service & Coverage
    coverage_regions: [],
    eligible_roles: [],
    
    // Step 7: Rate Proposal
    rate_proposal_submitted: false,
    
    // Step 8: AI Intelligence
    ai_optimization_enabled: false,
    
    // Status
    approval_status: "pending",
  });

  const generateVendorNumber = () => {
    const randomNum = Math.floor(1000 + Math.random() * 9000);
    return `VN-${randomNum}`;
  };

  const createVendorMutation = useMutation({
    mutationFn: (data) => base44.entities.Vendor.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vendors'] });
      toast({
        title: "✅ Vendor Onboarding Complete",
        description: "Vendor submitted for approval",
      });
      navigate(createPageUrl("VendorManagement"));
    },
  });

  const handleNext = () => {
    // Validation for Step 2 (NDA)
    if (currentStep === 2 && !vendorData.nda_acknowledged) {
      toast({
        title: "⚠️ NDA Required",
        description: "You must sign and accept the NDA before proceeding",
        variant: "destructive",
      });
      return;
    }
    
    if (currentStep < 8) {
      setCurrentStep(currentStep + 1);
    }
  };

  const handleBack = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const handleSubmit = () => {
    const vendorNumber = generateVendorNumber();
    createVendorMutation.mutate({
      ...vendorData,
      vendor_number: vendorNumber,
      is_active: false,
    });
  };

  const handleFileUpload = async (file, field) => {
    try {
      const { file_url } = await base44.integrations.Core.UploadFile({ file });
      setVendorData({ ...vendorData, [field]: file_url });
      toast({
        title: "✅ File Uploaded",
        description: "Document uploaded successfully",
      });
    } catch (error) {
      toast({
        title: "❌ Upload Failed",
        description: "Failed to upload document",
        variant: "destructive",
      });
    }
  };

  const handleSignNDA = () => {
    const now = new Date();
    setVendorData({
      ...vendorData,
      nda_acknowledged: true,
      nda_signed_by: user?.full_name || user?.email,
      nda_signature_date: now.toLocaleDateString(),
      nda_signature_time: now.toLocaleTimeString()
    });
    toast({
      title: "✅ NDA Signed",
      description: `Signed by ${user?.full_name || user?.email} on ${now.toLocaleString()}`,
    });
  };

  if (!isBuyer) {
    return (
      <div className="p-8">
        <Card className="max-w-2xl mx-auto border-red-200 bg-red-50">
          <CardContent className="p-8 text-center">
            <Shield className="w-16 h-16 mx-auto text-red-600 mb-4" />
            <h2 className="text-xl font-bold text-red-900 mb-2">Access Denied</h2>
            <p className="text-red-700">Only Procurement and Admin users can onboard vendors.</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-6xl mx-auto">
        <PageHeader
          title="🚀 Vendor Onboarding Process"
          subtitle="Complete all 8 steps to join our vendor network"
          backTo={createPageUrl("VendorManagement")}
          backButtonLabel="Back to Vendors"
        />

        {/* Progress Stepper */}
        <Card className="mb-8 border-slate-200 shadow-xl">
          <CardContent className="p-6">
            <div className="grid grid-cols-8 gap-2">
              {ONBOARDING_STEPS.map((step, index) => {
                const isActive = currentStep === step.id;
                const isCompleted = currentStep > step.id;
                const Icon = step.icon;

                return (
                  <div key={step.id} className="flex flex-col items-center">
                    <div
                      className={`w-16 h-16 rounded-full flex items-center justify-center mb-2 transition-all ${
                        isCompleted
                          ? "bg-green-500 text-white shadow-lg"
                          : isActive
                          ? "bg-[#0A39DF] text-white shadow-lg scale-110"
                          : "bg-slate-200 text-slate-500"
                      }`}
                    >
                      {isCompleted ? <Check className="w-8 h-8" /> : <Icon className="w-8 h-8" />}
                    </div>
                    <span
                      className={`text-xs font-medium text-center ${
                        isActive ? "text-[#0A39DF]" : isCompleted ? "text-green-600" : "text-slate-500"
                      }`}
                    >
                      Step {step.id}
                    </span>
                    <span
                      className={`text-xs text-center font-bold ${
                        isActive ? "text-[#0A39DF]" : isCompleted ? "text-green-600" : "text-slate-400"
                      }`}
                    >
                      {step.title}
                    </span>
                  </div>
                );
              })}
            </div>
          </CardContent>
        </Card>

        {/* Step Content */}
        <Card className="mb-8 border-slate-200 shadow-xl">
          <CardHeader className="bg-gradient-to-r from-[#0A39DF] to-[#1C323E] text-white">
            <div className="flex items-center gap-4">
              {React.createElement(ONBOARDING_STEPS[currentStep - 1].icon, { className: "w-8 h-8" })}
              <div>
                <CardTitle className="text-2xl">
                  Step {currentStep}: {ONBOARDING_STEPS[currentStep - 1].title}
                </CardTitle>
                <p className="text-blue-100 text-sm mt-1">
                  {ONBOARDING_STEPS[currentStep - 1].description}
                </p>
              </div>
            </div>
          </CardHeader>
          <CardContent className="p-8">
            {/* STEP 1: Vendor Onboard */}
            {currentStep === 1 && (
              <div className="space-y-6">
                <h3 className="text-xl font-bold text-[#1C323E] mb-4">📝 Basic Vendor Information</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <Label className="text-slate-700 font-semibold">Legal Business Name *</Label>
                    <Input
                      value={vendorData.legal_name}
                      onChange={(e) => setVendorData({ ...vendorData, legal_name: e.target.value })}
                      placeholder="ABC Staffing LLC"
                      className="mt-2"
                    />
                  </div>
                  <div>
                    <Label className="text-slate-700 font-semibold">Doing Business As (DBA)</Label>
                    <Input
                      value={vendorData.doing_business_as}
                      onChange={(e) => setVendorData({ ...vendorData, doing_business_as: e.target.value })}
                      placeholder="ABC Staff"
                      className="mt-2"
                    />
                  </div>
                  <div>
                    <Label className="text-slate-700 font-semibold">Federal Tax ID / EIN *</Label>
                    <Input
                      value={vendorData.tax_id}
                      onChange={(e) => setVendorData({ ...vendorData, tax_id: e.target.value })}
                      placeholder="12-3456789"
                      className="mt-2"
                    />
                  </div>
                  <div>
                    <Label className="text-slate-700 font-semibold">Business Type *</Label>
                    <Select
                      value={vendorData.business_type}
                      onValueChange={(value) => setVendorData({ ...vendorData, business_type: value })}
                    >
                      <SelectTrigger className="mt-2">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Corporation">Corporation</SelectItem>
                        <SelectItem value="LLC">LLC</SelectItem>
                        <SelectItem value="Partnership">Partnership</SelectItem>
                        <SelectItem value="Sole Proprietorship">Sole Proprietorship</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label className="text-slate-700 font-semibold">Primary Contact Name *</Label>
                    <Input
                      value={vendorData.primary_contact_name}
                      onChange={(e) => setVendorData({ ...vendorData, primary_contact_name: e.target.value })}
                      placeholder="John Doe"
                      className="mt-2"
                    />
                  </div>
                  <div>
                    <Label className="text-slate-700 font-semibold">Primary Contact Email *</Label>
                    <Input
                      type="email"
                      value={vendorData.primary_contact_email}
                      onChange={(e) => setVendorData({ ...vendorData, primary_contact_email: e.target.value })}
                      placeholder="john@abcstaff.com"
                      className="mt-2"
                    />
                  </div>
                  <div>
                    <Label className="text-slate-700 font-semibold">Primary Contact Phone *</Label>
                    <Input
                      value={vendorData.primary_contact_phone}
                      onChange={(e) => setVendorData({ ...vendorData, primary_contact_phone: e.target.value })}
                      placeholder="(555) 123-4567"
                      className="mt-2"
                    />
                  </div>
                </div>
                <div>
                  <Label className="text-slate-700 font-semibold">Billing Address *</Label>
                  <Textarea
                    value={vendorData.billing_address}
                    onChange={(e) => setVendorData({ ...vendorData, billing_address: e.target.value })}
                    placeholder="123 Main St, San Francisco, CA 94102"
                    rows={3}
                    className="mt-2"
                  />
                </div>
              </div>
            )}

            {/* STEP 2: NDA - Sign and Accept */}
            {currentStep === 2 && (
              <div className="space-y-6">
                <div className="p-6 bg-purple-50 border-2 border-purple-300 rounded-xl">
                  <div className="flex items-start gap-4">
                    <Shield className="w-8 h-8 text-purple-600 flex-shrink-0 mt-1" />
                    <div>
                      <h3 className="text-xl font-bold text-purple-900 mb-2">
                        🔒 Non-Disclosure Agreement (NDA)
                      </h3>
                      <p className="text-purple-700">
                        Review and sign the NDA between your company and Foodbuy, LLC. This is a legally binding document.
                      </p>
                    </div>
                  </div>
                </div>

                {/* NDA Document Viewer */}
                <div className="border-2 border-slate-300 rounded-xl overflow-hidden shadow-lg">
                  <div className="bg-gradient-to-r from-purple-600 to-purple-800 px-6 py-4 flex items-center justify-between">
                    <h4 className="font-bold text-white text-lg">📄 NDA Document</h4>
                    <a
                      href="https://qtrypzzcjebvfcihiynt.supabase.co/storage/v1/object/public/base44-prod/public/68fc6cf01386035c266e7a5d/1d8cf6dbf_LegendaryEventStaffingFOODBUYVendorNDA.pdf"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="px-4 py-2 bg-white text-purple-700 rounded-lg hover:bg-purple-50 font-semibold text-sm flex items-center gap-2"
                    >
                      <FileText className="w-4 h-4" />
                      Open in New Tab
                    </a>
                  </div>
                  <div className="h-[600px] bg-white">
                    <iframe
                      src="https://qtrypzzcjebvfcihiynt.supabase.co/storage/v1/object/public/base44-prod/public/68fc6cf01386035c266e7a5d/1d8cf6dbf_LegendaryEventStaffingFOODBUYVendorNDA.pdf"
                      className="w-full h-full"
                      title="NDA Document"
                    />
                  </div>
                </div>

                {/* NDA Key Terms */}
                <div className="p-6 bg-slate-50 border border-slate-200 rounded-xl">
                  <h4 className="font-bold text-slate-900 mb-4 text-lg">📋 Key Terms Summary:</h4>
                  <ul className="space-y-3">
                    <li className="flex items-start gap-3">
                      <span className="w-2 h-2 bg-purple-600 rounded-full mt-2"></span>
                      <span className="text-slate-700">
                        <strong>Confidentiality:</strong> All proprietary information, pricing, and client data must remain confidential
                      </span>
                    </li>
                    <li className="flex items-start gap-3">
                      <span className="w-2 h-2 bg-purple-600 rounded-full mt-2"></span>
                      <span className="text-slate-700">
                        <strong>Duration:</strong> Obligations continue for 2 years after relationship termination
                      </span>
                    </li>
                    <li className="flex items-start gap-3">
                      <span className="w-2 h-2 bg-purple-600 rounded-full mt-2"></span>
                      <span className="text-slate-700">
                        <strong>Governing Law:</strong> North Carolina law applies
                      </span>
                    </li>
                    <li className="flex items-start gap-3">
                      <span className="w-2 h-2 bg-purple-600 rounded-full mt-2"></span>
                      <span className="text-slate-700">
                        <strong>Use Restrictions:</strong> Information only for business relationship purposes
                      </span>
                    </li>
                  </ul>
                </div>

                {/* Sign and Accept Section */}
                <div className={`p-8 border-4 rounded-xl transition-all ${
                  vendorData.nda_acknowledged 
                    ? 'bg-green-50 border-green-400' 
                    : 'bg-white border-purple-300'
                }`}>
                  {!vendorData.nda_acknowledged ? (
                    <div>
                      <h4 className="text-xl font-bold text-slate-900 mb-4">✍️ Sign and Accept NDA</h4>
                      <p className="text-slate-700 mb-6 leading-relaxed">
                        By clicking the button below, I acknowledge that I have read, understood, and agree to be bound by 
                        the terms of the Confidentiality/Non-Disclosure Agreement between my company and Foodbuy, LLC.
                      </p>
                      <Button
                        onClick={handleSignNDA}
                        className="w-full bg-gradient-to-r from-purple-600 to-purple-800 hover:from-purple-700 hover:to-purple-900 text-white text-lg py-6 font-bold shadow-xl"
                      >
                        <Check className="w-6 h-6 mr-3" />
                        I SIGN AND ACCEPT THE NDA
                      </Button>
                    </div>
                  ) : (
                    <div className="text-center">
                      <div className="w-20 h-20 bg-green-500 rounded-full flex items-center justify-center mx-auto mb-4">
                        <Check className="w-12 h-12 text-white" />
                      </div>
                      <h4 className="text-2xl font-bold text-green-900 mb-4">✅ NDA Signed Successfully</h4>
                      <div className="bg-white p-6 rounded-lg border-2 border-green-300 max-w-md mx-auto">
                        <div className="space-y-2 text-left">
                          <div className="flex justify-between">
                            <span className="font-semibold text-slate-700">Signed by:</span>
                            <span className="text-slate-900">{vendorData.nda_signed_by}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="font-semibold text-slate-700">Date:</span>
                            <span className="text-slate-900">{vendorData.nda_signature_date}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="font-semibold text-slate-700">Time:</span>
                            <span className="text-slate-900">{vendorData.nda_signature_time}</span>
                          </div>
                        </div>
                      </div>
                      <p className="text-green-700 mt-4 font-semibold">
                        ✓ You may now proceed to the next step
                      </p>
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* STEP 3: Contract */}
            {currentStep === 3 && (
              <div className="space-y-6">
                <h3 className="text-xl font-bold text-[#1C323E]">📋 Master Service Agreement</h3>
                <div className="p-6 bg-blue-50 border border-blue-200 rounded-lg">
                  <p className="text-blue-900">
                    Review and sign the Master Service Agreement. This document outlines the terms of our business relationship.
                  </p>
                </div>
                <div className="h-96 bg-slate-100 rounded-lg flex items-center justify-center border-2 border-dashed border-slate-300">
                  <p className="text-slate-500">Contract document viewer will appear here</p>
                </div>
              </div>
            )}

            {/* STEP 4: Performance & VA Structure */}
            {currentStep === 4 && (
              <div className="space-y-6">
                <h3 className="text-xl font-bold text-[#1C323E]">📊 Performance Metrics & VA Structure</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="p-6 bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl border border-blue-200">
                    <h4 className="font-bold text-blue-900 mb-3">Performance Metrics</h4>
                    <ul className="space-y-2 text-sm text-blue-800">
                      <li>• Fill Rate Target: 95%+</li>
                      <li>• On-Time Arrival: 98%+</li>
                      <li>• Quality Rating: 4.5/5+</li>
                      <li>• Cancellation Rate: &lt;5%</li>
                    </ul>
                  </div>
                  <div className="p-6 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                    <h4 className="font-bold text-purple-900 mb-3">VA Structure</h4>
                    <Label className="text-purple-800 font-semibold">Select Structure Type</Label>
                    <Select
                      value={vendorData.va_structure_type}
                      onValueChange={(value) => setVendorData({ ...vendorData, va_structure_type: value })}
                    >
                      <SelectTrigger className="mt-2">
                        <SelectValue placeholder="Choose VA structure" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="standard">Standard VA</SelectItem>
                        <SelectItem value="premium">Premium VA</SelectItem>
                        <SelectItem value="enterprise">Enterprise VA</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </div>
            )}

            {/* STEP 5: Documents & Validation */}
            {currentStep === 5 && (
              <div className="space-y-6">
                <h3 className="text-xl font-bold text-[#1C323E]">📂 Upload Compliance Documents</h3>
                <div className="space-y-4">
                  <div className="p-6 bg-white border-2 border-slate-200 rounded-xl">
                    <Label className="text-slate-700 font-semibold text-lg">W-9 Form *</Label>
                    <input
                      type="file"
                      accept=".pdf,.doc,.docx"
                      onChange={(e) => e.target.files[0] && handleFileUpload(e.target.files[0], 'w9_document')}
                      className="block w-full mt-3 text-sm text-slate-500 file:mr-4 file:py-3 file:px-6 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-[#0A39DF] file:text-white hover:file:bg-[#0A39DF]/90"
                    />
                    {vendorData.w9_document && (
                      <Badge className="mt-3 bg-green-500 text-white px-4 py-2">
                        <Check className="w-4 h-4 mr-2" />
                        Uploaded Successfully
                      </Badge>
                    )}
                  </div>

                  <div className="p-6 bg-white border-2 border-slate-200 rounded-xl">
                    <Label className="text-slate-700 font-semibold text-lg">Certificate of Insurance (COI) *</Label>
                    <input
                      type="file"
                      accept=".pdf,.doc,.docx"
                      onChange={(e) => e.target.files[0] && handleFileUpload(e.target.files[0], 'coi_document')}
                      className="block w-full mt-3 text-sm text-slate-500 file:mr-4 file:py-3 file:px-6 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-[#0A39DF] file:text-white hover:file:bg-[#0A39DF]/90"
                    />
                    {vendorData.coi_document && (
                      <Badge className="mt-3 bg-green-500 text-white px-4 py-2">
                        <Check className="w-4 h-4 mr-2" />
                        Uploaded Successfully
                      </Badge>
                    )}
                  </div>

                  <div className="p-6 bg-white border-2 border-slate-200 rounded-xl">
                    <Label className="text-slate-700 font-semibold text-lg">Insurance Expiry Date *</Label>
                    <Input
                      type="date"
                      value={vendorData.insurance_expiry}
                      onChange={(e) => setVendorData({ ...vendorData, insurance_expiry: e.target.value })}
                      className="mt-3"
                    />
                  </div>
                </div>
              </div>
            )}

            {/* STEP 6: Service & Coverage */}
            {currentStep === 6 && (
              <div className="space-y-6">
                <h3 className="text-xl font-bold text-[#1C323E]">🗺️ Service Areas & Coverage</h3>
                <div>
                  <Label className="mb-3 block text-lg font-bold text-slate-700">Coverage Regions *</Label>
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                    {["San Francisco Bay Area", "Los Angeles", "Sacramento", "San Diego", "Silicon Valley", "East Bay"].map((region) => (
                      <label key={region} className="flex items-center gap-3 p-4 border-2 border-slate-200 rounded-xl hover:bg-slate-50 cursor-pointer transition-all hover:border-[#0A39DF]">
                        <input
                          type="checkbox"
                          checked={vendorData.coverage_regions.includes(region)}
                          onChange={(e) => {
                            const regions = e.target.checked
                              ? [...vendorData.coverage_regions, region]
                              : vendorData.coverage_regions.filter((r) => r !== region);
                            setVendorData({ ...vendorData, coverage_regions: regions });
                          }}
                          className="w-5 h-5"
                        />
                        <span className="font-medium">{region}</span>
                      </label>
                    ))}
                  </div>
                </div>

                <div>
                  <Label className="mb-3 block text-lg font-bold text-slate-700">Eligible Roles *</Label>
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                    {["Bartender", "Server", "Cook", "Dishwasher", "Barista", "Cashier", "Security", "Event Staff", "Manager"].map((role) => (
                      <label key={role} className="flex items-center gap-3 p-4 border-2 border-slate-200 rounded-xl hover:bg-slate-50 cursor-pointer transition-all hover:border-[#0A39DF]">
                        <input
                          type="checkbox"
                          checked={vendorData.eligible_roles.includes(role)}
                          onChange={(e) => {
                            const roles = e.target.checked
                              ? [...vendorData.eligible_roles, role]
                              : vendorData.eligible_roles.filter((r) => r !== role);
                            setVendorData({ ...vendorData, eligible_roles: roles });
                          }}
                          className="w-5 h-5"
                        />
                        <span className="font-medium">{role}</span>
                      </label>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {/* STEP 7: Rate Proposal */}
            {currentStep === 7 && (
              <div className="space-y-6">
                <h3 className="text-xl font-bold text-[#1C323E]">💰 Rate Proposal</h3>
                <div className="p-6 bg-amber-50 border border-amber-200 rounded-lg">
                  <p className="text-amber-900 font-semibold">
                    Submit your proposed rate structure. Our procurement team will review and may negotiate.
                  </p>
                </div>
                <p className="text-slate-600">
                  You can add detailed rate proposals after initial approval. For now, we'll create a default rate card for review.
                </p>
              </div>
            )}

            {/* STEP 8: AI Intelligence */}
            {currentStep === 8 && (
              <div className="space-y-6">
                <h3 className="text-xl font-bold text-[#1C323E]">🤖 AI-Powered Optimization</h3>
                <div className="p-8 bg-gradient-to-r from-purple-50 to-blue-50 border-2 border-purple-200 rounded-xl">
                  <div className="flex items-start gap-4 mb-6">
                    <Sparkles className="w-12 h-12 text-purple-600" />
                    <div>
                      <h4 className="text-2xl font-bold text-purple-900 mb-2">AI Intelligence Features</h4>
                      <p className="text-purple-700">
                        Enable AI-powered features to optimize your vendor performance, automate workflows, and gain insights.
                      </p>
                    </div>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                    <div className="p-4 bg-white rounded-lg border border-purple-200">
                      <h5 className="font-bold text-slate-900 mb-2">✨ Smart Matching</h5>
                      <p className="text-sm text-slate-600">AI matches your workforce to the best opportunities</p>
                    </div>
                    <div className="p-4 bg-white rounded-lg border border-purple-200">
                      <h5 className="font-bold text-slate-900 mb-2">📈 Predictive Analytics</h5>
                      <p className="text-sm text-slate-600">Forecast demand and optimize staffing</p>
                    </div>
                    <div className="p-4 bg-white rounded-lg border border-purple-200">
                      <h5 className="font-bold text-slate-900 mb-2">🎯 Performance Insights</h5>
                      <p className="text-sm text-slate-600">Real-time performance tracking and recommendations</p>
                    </div>
                    <div className="p-4 bg-white rounded-lg border border-purple-200">
                      <h5 className="font-bold text-slate-900 mb-2">⚡ Automated Workflows</h5>
                      <p className="text-sm text-slate-600">Streamline operations with AI automation</p>
                    </div>
                  </div>
                  <label className="flex items-center gap-4 p-6 bg-white rounded-xl border-2 border-purple-300 cursor-pointer hover:bg-purple-50">
                    <input
                      type="checkbox"
                      checked={vendorData.ai_optimization_enabled}
                      onChange={(e) => setVendorData({ ...vendorData, ai_optimization_enabled: e.target.checked })}
                      className="w-6 h-6"
                    />
                    <div>
                      <p className="font-bold text-slate-900">Enable AI Intelligence</p>
                      <p className="text-sm text-slate-600">Activate AI-powered features for your vendor account</p>
                    </div>
                  </label>
                </div>

                {/* Final Review */}
                <div className="p-8 bg-green-50 border-2 border-green-300 rounded-xl">
                  <h4 className="text-2xl font-bold text-green-900 mb-4">✅ Ready to Submit!</h4>
                  <p className="text-green-800 mb-6">
                    You've completed all onboarding steps. Review your information and submit for approval.
                  </p>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div className="flex items-center gap-2">
                      <Check className="w-5 h-5 text-green-600" />
                      <span>Basic Information Complete</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <Check className="w-5 h-5 text-green-600" />
                      <span>NDA Signed: {vendorData.nda_signature_date}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <Check className="w-5 h-5 text-green-600" />
                      <span>{vendorData.coverage_regions.length} Regions Selected</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <Check className="w-5 h-5 text-green-600" />
                      <span>{vendorData.eligible_roles.length} Roles Selected</span>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Navigation Buttons */}
        <div className="flex items-center justify-between">
          <Button
            variant="outline"
            onClick={handleBack}
            disabled={currentStep === 1}
            className="px-8 py-6 text-lg"
          >
            <ArrowLeft className="w-5 h-5 mr-2" />
            Back
          </Button>

          <div className="flex items-center gap-3">
            {currentStep < 8 ? (
              <Button
                onClick={handleNext}
                className="bg-gradient-to-r from-[#0A39DF] to-[#1C323E] hover:from-[#0A39DF]/90 hover:to-[#1C323E]/90 text-white px-8 py-6 text-lg font-bold shadow-xl"
              >
                Next Step
                <ArrowRight className="w-5 h-5 ml-2" />
              </Button>
            ) : (
              <Button
                onClick={handleSubmit}
                disabled={createVendorMutation.isPending}
                className="bg-gradient-to-r from-green-600 to-green-800 hover:from-green-700 hover:to-green-900 text-white px-8 py-6 text-lg font-bold shadow-xl"
              >
                <Check className="w-5 h-5 mr-2" />
                Submit for Approval
              </Button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}