import React, { useState, useEffect } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Calendar, Zap, RefreshCw, Users, Building2,
  Plus, Minus, Trash2, Search, Save, MapPin, Edit2, UserPlus, X
} from "lucide-react";
import { format } from "date-fns";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Checkbox } from "@/components/ui/checkbox";
import { Textarea } from "@/components/ui/textarea";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem } from "@/components/ui/command";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import GoogleAddressInput from "../common/GoogleAddressInput";
import RapidOrderInterface from "../orders/RapidOrderInterface";
import { createPageUrl } from "@/utils";

export default function EventFormWizard({ event, onSubmit, onRapidSubmit, isSubmitting, currentUser, onCancel }) {
  const [showRapidInterface, setShowRapidInterface] = useState(false);
  const [formData, setFormData] = useState(event || {
    event_name: "",
    order_type: "one_time",
    business_id: "",
    business_name: "",
    hub: "",
    department: "",
    po_reference: "",
    status: "Draft",
    date: "",
    include_backup: false,
    backup_staff_count: 0,
    vendor_id: "",
    vendor_name: "",
    recurring_start_date: "",
    recurring_end_date: "",
    recurring_days: [],
    recurring_time: "09:00",
    permanent_start_date: "",
    permanent_days: [],
    permanent_time: "09:00",
    shifts: [{
      shift_name: "Shift 1",
      location_address: "",
      same_as_billing: true,
      roles: [{
        role: "",
        department: "",
        count: 1,
        start_time: "09:00",
        end_time: "17:00",
        hours: 8,
        uniform: "Type 1",
        break_minutes: 30,
        rate_per_hour: 0,
        total_value: 0
      }]
    }],
    notes: "",
    total: 0
  });

  const [roleSearchOpen, setRoleSearchOpen] = useState({});
  const [showShiftContactDialog, setShowShiftContactDialog] = useState(false);
  const [selectedShiftIndex, setSelectedShiftIndex] = useState(null);

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

  const currentUserData = currentUser || user;
  const userRole = currentUserData?.user_role || currentUserData?.role || "admin";
  const isVendor = userRole === "vendor";
  const isClient = userRole === "client";

  // Fetch client user's team member data to auto-populate hub, department, and address
  const { data: teamMember } = useQuery({
    queryKey: ['client-team-member', currentUserData?.id],
    queryFn: async () => {
      if (!currentUserData?.id || !isClient) return null;
      const allMembers = await base44.entities.TeamMember.list();
      return allMembers.find(m => m.email === currentUserData.email);
    },
    enabled: !!currentUserData?.id && isClient,
  });

  const { data: teamHub } = useQuery({
    queryKey: ['client-team-hub', teamMember?.hub, teamMember?.team_id],
    queryFn: async () => {
      if (!teamMember?.hub || !teamMember?.team_id) return null;
      const allHubs = await base44.entities.TeamHub.list();
      return allHubs.find(h => h.hub_name === teamMember.hub && h.team_id === teamMember.team_id);
    },
    enabled: !!teamMember?.hub && !!teamMember?.team_id,
  });

  const { data: teamHubs = [] } = useQuery({
    queryKey: ['team-hubs-for-order', teamMember?.team_id],
    queryFn: async () => {
      if (!teamMember?.team_id) return [];
      const allHubs = await base44.entities.TeamHub.list();
      return allHubs.filter(h => h.team_id === teamMember.team_id && h.is_active);
    },
    enabled: !!teamMember?.team_id && isClient,
    initialData: [],
  });

  const { data: teamMembers = [] } = useQuery({
    queryKey: ['team-members-for-contact', teamMember?.team_id],
    queryFn: async () => {
      if (!teamMember?.team_id) return [];
      const allMembers = await base44.entities.TeamMember.list();
      return allMembers.filter(m => m.team_id === teamMember.team_id && m.is_active);
    },
    enabled: !!teamMember?.team_id && isClient,
    initialData: [],
  });

  const { data: businesses = [] } = useQuery({
    queryKey: ['businesses'],
    queryFn: () => base44.entities.Business.list(),
    initialData: [],
  });

  const { data: vendors = [] } = useQuery({
    queryKey: ['vendors-for-order'],
    queryFn: () => base44.entities.Vendor.list(),
    initialData: [],
  });

  const { data: allRates = [] } = useQuery({
    queryKey: ['vendor-rates-all'],
    queryFn: () => base44.entities.VendorRate.list(),
    initialData: [],
  });

  // Get available roles - filter by selected vendor for clients, or by client for vendors
  const availableRoles = React.useMemo(() => {
    // For CLIENT users: filter roles by selected vendor
    if (isClient && formData.vendor_id) {
      const selectedVendor = vendors.find(v => v.id === formData.vendor_id);
      const vendorName = selectedVendor?.legal_name || selectedVendor?.doing_business_as;
      
      // Get roles from this vendor's rates
      const vendorRoles = allRates.filter(rate => 
        (rate.vendor_id === formData.vendor_id || rate.vendor_name === vendorName) &&
        rate.is_active !== false
      ).map(r => r.role_name);
      
      // Deduplicate and sort
      const uniqueRoles = [...new Set(vendorRoles)].filter(Boolean);
      
      if (uniqueRoles.length > 0) {
        return uniqueRoles.sort();
      }
    }
    
    // For VENDOR users: filter roles by selected client
    if (isVendor && formData.business_id && formData.business_name) {
      const extractCompanyName = (name) => {
        if (!name) return '';
        return name.split(/\s*[-–]\s*/)[0].trim();
      };
      
      const mainCompanyName = extractCompanyName(formData.business_name);
      const selectedBusiness = businesses.find(b => b.id === formData.business_id);
      
      // Get roles that have client-specific rates for this client
      const clientSpecificRoles = allRates.filter(rate => 
        rate.rate_book_type === 'client_specific' &&
        (rate.client_name === formData.business_name || 
         rate.client_name === mainCompanyName ||
         extractCompanyName(rate.client_name) === mainCompanyName)
      ).map(r => r.role_name);
      
      // Also get roles from client's rate_card if set
      let rateCardRoles = [];
      if (selectedBusiness?.rate_card) {
        rateCardRoles = allRates.filter(rate => 
          rate.rate_book_name === selectedBusiness.rate_card
        ).map(r => r.role_name);
      }
      
      // Combine and deduplicate
      const combinedRoles = [...new Set([...clientSpecificRoles, ...rateCardRoles])].filter(Boolean);
      
      if (combinedRoles.length > 0) {
        return combinedRoles.sort();
      }
    }
    
    // Default: show all roles
    return [...new Set(allRates.map(r => r.role_name))].filter(Boolean).sort();
  }, [allRates, isVendor, isClient, formData.vendor_id, formData.business_id, formData.business_name, businesses, vendors]);

  useEffect(() => {
    if (isClient && currentUserData && !formData.vendor_id) {
      const preferredVendorId = currentUserData.preferred_vendor_id;
      const preferredVendorName = currentUserData.preferred_vendor_name;

      if (preferredVendorId) {
        setFormData(prev => ({
          ...prev,
          vendor_id: preferredVendorId,
          vendor_name: preferredVendorName || ""
        }));
      }
    }
  }, [isClient, currentUserData, formData.vendor_id]);

  // Auto-populate hub, department, and address from team member data for client users
  useEffect(() => {
    if (isClient && teamMember && !event) {
      setFormData(prev => ({
        ...prev,
        hub: prev.hub || teamMember.hub || "",
        department: prev.department || teamMember.department || "",
        shifts: prev.shifts.map((shift, idx) => ({
          ...shift,
          location_address: idx === 0 && !shift.location_address 
            ? (teamHub?.address || teamMember.hub || "") 
            : shift.location_address
        }))
      }));
    }
  }, [isClient, teamMember, teamHub, event]);

  // Auto-fill fields when order type changes to RAPID
  useEffect(() => {
    if (formData.order_type === 'rapid' && formData.shifts?.length > 0 && formData.shifts[0].roles?.length > 0) {
      const firstRole = formData.shifts[0].roles[0];
      
      // Only auto-fill if fields are empty
      if (!firstRole.start_time || !firstRole.count || firstRole.count === 0) {
        const updatedShifts = [...formData.shifts];
        const updatedRole = {
          ...firstRole,
          start_time: firstRole.start_time || "09:00",
          end_time: firstRole.end_time || "17:00",
          count: firstRole.count || 1,
          break_minutes: firstRole.break_minutes ?? 30,
          hours: firstRole.hours || 8,
        };
        
        // If role is selected, fetch rate
        if (updatedRole.role && formData.vendor_id) {
          const rate = getRateForRole(updatedRole.role, formData.vendor_id);
          updatedRole.rate_per_hour = rate;
          updatedRole.total_value = rate * updatedRole.hours * updatedRole.count;
        }
        
        updatedShifts[0].roles[0] = updatedRole;
        
        setFormData(prev => ({
          ...prev,
          shifts: updatedShifts
        }));
        updateGrandTotal();
      }
    }
  }, [formData.order_type]);

  useEffect(() => {
    if (event) {
      // Determine order type from event data
      let orderType = 'one_time';
      if (event.is_rapid) {
        orderType = 'rapid';
      } else if (event.is_recurring || event.order_type === 'recurring') {
        orderType = 'recurring';
      } else if (event.order_type === 'permanent') {
        orderType = 'permanent';
      } else if (event.order_type) {
        orderType = event.order_type;
      }
      
      // Ensure all fields are properly loaded
      const loadedData = {
        ...event,
        order_type: orderType,
        vendor_id: event.vendor_id || "",
        vendor_name: event.vendor_name || "",
        hub: event.hub || "",
        date: event.date || "",
        event_name: event.event_name || "",
        total: event.total || 0,
        shifts: event.shifts && event.shifts.length > 0 ? event.shifts : [{
          shift_name: "Shift 1",
          location_address: "",
          same_as_billing: true,
          roles: [{
            role: "",
            department: "",
            count: 1,
            start_time: "09:00",
            end_time: "17:00",
            hours: 8,
            uniform: "Type 1",
            break_minutes: 30,
            rate_per_hour: 0,
            total_value: 0
          }]
        }]
      };
      
      setFormData(loadedData);
    }
  }, [event]);

  // Auto-fill fields when order type changes to RAPID
  useEffect(() => {
    if (formData.order_type === 'rapid' && formData.shifts?.length > 0 && formData.shifts[0].roles?.length > 0) {
      const firstRole = formData.shifts[0].roles[0];
      
      // Only auto-fill if fields are empty
      if (!firstRole.start_time || !firstRole.count || firstRole.count === 0) {
        const updatedShifts = [...formData.shifts];
        const updatedRole = {
          ...firstRole,
          start_time: firstRole.start_time || "09:00",
          end_time: firstRole.end_time || "17:00",
          count: firstRole.count || 1,
          break_minutes: firstRole.break_minutes ?? 30,
          hours: firstRole.hours || 8,
        };
        
        // If role is selected, fetch rate
        if (updatedRole.role && formData.vendor_id) {
          const rate = getRateForRole(updatedRole.role, formData.vendor_id);
          updatedRole.rate_per_hour = rate;
          updatedRole.total_value = rate * updatedRole.hours * updatedRole.count;
        }
        
        updatedShifts[0].roles[0] = updatedRole;
        
        setFormData(prev => ({
          ...prev,
          shifts: updatedShifts
        }));
        updateGrandTotal();
      }
    }
  }, [formData.order_type]);

  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleBusinessChange = (businessId) => {
    const selectedBusiness = businesses.find(b => b.id === businessId);
    if (selectedBusiness) {
      // Update form with business info and recalculate rates for all roles
      setFormData(prev => {
        const updatedShifts = prev.shifts.map(shift => ({
          ...shift,
          location_address: selectedBusiness.address || shift.location_address,
          roles: shift.roles.map(role => {
            if (role.role) {
              const rate = getRateForRoleAndClient(role.role, businessId, selectedBusiness.business_name);
              return {
                ...role,
                rate_per_hour: rate,
                total_value: rate * (role.hours || 0) * (parseInt(role.count) || 1)
              };
            }
            return role;
          })
        }));

        return {
          ...prev,
          business_id: businessId,
          business_name: selectedBusiness.business_name || "",
          hub: selectedBusiness.hub_building || prev.hub,
          shifts: updatedShifts
        };
      });
      setTimeout(() => updateGrandTotal(), 10);
    }
  };

  // Get rate for role based on selected client
  const getRateForRoleAndClient = (roleName, businessId, businessName) => {
    if (!businessId || !businessName) return 0;
    
    // Extract main company name (e.g., "Chime" from "Chime - HQ")
    const extractCompanyName = (name) => {
      if (!name) return '';
      return name.split(/\s*[-–]\s*/)[0].trim();
    };
    
    const mainCompanyName = extractCompanyName(businessName);
    const selectedBusiness = businesses.find(b => b.id === businessId);
    
    // Priority 1: Client-specific rate matching this client
    const clientSpecificRate = allRates.find(rate => 
      rate.role_name?.toLowerCase() === roleName.toLowerCase() &&
      rate.rate_book_type === 'client_specific' &&
      (rate.client_name === businessName || 
       rate.client_name === mainCompanyName ||
       extractCompanyName(rate.client_name) === mainCompanyName)
    );
    
    if (clientSpecificRate) {
      return clientSpecificRate.client_rate || 0;
    }
    
    // Priority 2: Match client's rate_card
    if (selectedBusiness?.rate_card) {
      const rateCardMatch = allRates.find(rate => 
        rate.role_name?.toLowerCase() === roleName.toLowerCase() &&
        rate.rate_book_name === selectedBusiness.rate_card
      );
      if (rateCardMatch) {
        return rateCardMatch.client_rate || 0;
      }
    }
    
    // Priority 3: Default rate
    const defaultRate = allRates.find(rate => 
      rate.role_name?.toLowerCase() === roleName.toLowerCase() &&
      rate.rate_book_type === 'default'
    );
    
    return defaultRate?.client_rate || 0;
  };

  // Auto-populate shift addresses when hub changes
  useEffect(() => {
    if (formData.hub && formData.shifts.length > 0) {
      setFormData(prev => ({
        ...prev,
        shifts: prev.shifts.map((shift, idx) => ({
          ...shift,
          location_address: shift.location_address || formData.hub
        }))
      }));
    }
  }, [formData.hub]);

  const handleVendorChange = (vendorId) => {
    const selectedVendor = vendors.find(v => v.id === vendorId);
    if (selectedVendor) {
      setFormData(prev => {
        const updatedShifts = prev.shifts.map(shift => ({
          ...shift,
          roles: shift.roles.map(role => {
            if (role.role) {
              const rate = getRateForRole(role.role, vendorId);
              return {
                ...role,
                rate_per_hour: rate,
                total_value: rate * (role.hours || 0) * (parseInt(role.count) || 1),
                vendor_id: vendorId,
                vendor_name: selectedVendor.legal_name || selectedVendor.doing_business_as
              };
            }
            return {
              ...role,
              vendor_id: vendorId,
              vendor_name: selectedVendor.legal_name || selectedVendor.doing_business_as
            };
          })
        }));

        return {
          ...prev,
          vendor_id: vendorId,
          vendor_name: selectedVendor.legal_name || selectedVendor.doing_business_as || "",
          shifts: updatedShifts
        };
      });
      setTimeout(() => updateGrandTotal(), 10);
    }
  };

  const calculateHours = (startTime, endTime, breakMinutes = 0) => {
    if (!startTime || !endTime) return 0;
    const [startHour, startMin] = startTime.split(':').map(Number);
    const [endHour, endMin] = endTime.split(':').map(Number);
    const startMinutes = startHour * 60 + startMin;
    const endMinutes = endHour * 60 + endMin;
    let totalMinutes = endMinutes - startMinutes;
    if (totalMinutes < 0) totalMinutes += 24 * 60;
    totalMinutes -= (breakMinutes || 0);
    return Math.max(0, Math.round((totalMinutes / 60) * 100) / 100);
  };

  const getRateForRole = (roleName, vendorId = null) => {
    const targetVendorId = vendorId || formData.vendor_id;

    if (targetVendorId) {
      // Priority 1: Find rate matching vendor_id and role_name exactly
      const vendorRate = allRates.find(r =>
        r.role_name?.toLowerCase() === roleName?.toLowerCase() &&
        r.vendor_id === targetVendorId &&
        r.is_active !== false
      );
      if (vendorRate) {
        return parseFloat(vendorRate.client_rate || 0);
      }

      // Priority 2: Find rate matching vendor_name (some rates may not have vendor_id set)
      const selectedVendor = vendors.find(v => v.id === targetVendorId);
      if (selectedVendor) {
        const vendorName = selectedVendor.legal_name || selectedVendor.doing_business_as;
        const vendorNameRate = allRates.find(r =>
          r.role_name?.toLowerCase() === roleName?.toLowerCase() &&
          r.vendor_name === vendorName &&
          r.is_active !== false
        );
        if (vendorNameRate) {
          return parseFloat(vendorNameRate.client_rate || 0);
        }
      }
    }

    // Fallback: Find any rate for this role (default rates)
    const defaultRate = allRates.find(r => 
      r.role_name?.toLowerCase() === roleName?.toLowerCase() && 
      r.rate_book_type === 'default' &&
      r.is_active !== false
    );
    if (defaultRate) {
      return parseFloat(defaultRate.client_rate || 0);
    }

    // Last fallback: any rate for this role
    const anyRate = allRates.find(r => r.role_name?.toLowerCase() === roleName?.toLowerCase() && r.is_active !== false);
    return anyRate ? parseFloat(anyRate.client_rate || 0) : 0;
  };

  const handleRoleChange = (shiftIndex, roleIndex, field, value) => {
    setFormData(prev => {
      const newShifts = [...prev.shifts];
      const role = newShifts[shiftIndex].roles[roleIndex];
      role[field] = value;

      if (field === 'role') {
        // For vendors, use client-based rates; for clients, use vendor-based rates
        let rate = 0;
        if (isVendor && prev.business_id) {
          rate = getRateForRoleAndClient(value, prev.business_id, prev.business_name);
        } else {
          rate = getRateForRole(value, prev.vendor_id);
        }
        console.log('Setting rate for role', value, ':', rate);
        role.rate_per_hour = rate;
        role.vendor_id = prev.vendor_id;
        role.vendor_name = prev.vendor_name;
      }

      if (field === 'start_time' || field === 'end_time' || field === 'break_minutes') {
        role.hours = calculateHours(role.start_time, role.end_time, role.break_minutes);
      }

      if (field === 'count') {
        role.count = parseInt(value) || 1;
      }

      role.total_value = (role.rate_per_hour || 0) * (role.hours || 0) * (role.count || 1);
      console.log('Role total:', role.total_value, '= rate:', role.rate_per_hour, '* hours:', role.hours, '* count:', role.count);

      return { ...prev, shifts: newShifts };
    });
    setTimeout(() => updateGrandTotal(), 0);
  };

  const updateGrandTotal = () => {
    setTimeout(() => {
      setFormData(prev => {
        const total = prev.shifts.reduce((sum, shift) => {
          const shiftTotal = shift.roles.reduce((roleSum, role) => roleSum + (role.total_value || 0), 0);
          return sum + shiftTotal;
        }, 0);
        return { ...prev, total };
      });
    }, 0);
  };

  const handleAddShift = () => {
    setFormData(prev => {
      const newShift = {
        shift_name: `Shift ${prev.shifts.length + 1}`,
        location_address: prev.hub || "",
        same_as_billing: false,
        roles: [{
          role: "",
          department: "",
          count: 1,
          start_time: "09:00",
          end_time: "17:00",
          hours: 8,
          uniform: "Type 1",
          break_minutes: 30,
          rate_per_hour: 0,
          total_value: 0,
          vendor_id: prev.vendor_id,
          vendor_name: prev.vendor_name
        }]
      };
      return { ...prev, shifts: [...prev.shifts, newShift] };
    });
  };

  const handleRemoveShift = (shiftIndex) => {
    if (formData.shifts.length === 1) return;
    setFormData(prev => {
      const newShifts = prev.shifts.filter((_, idx) => idx !== shiftIndex);
      return { ...prev, shifts: newShifts };
    });
    updateGrandTotal();
  };

  const handleShiftChange = (shiftIndex, field, value) => {
    setFormData(prev => {
      const newShifts = [...prev.shifts];
      newShifts[shiftIndex][field] = value;
      return { ...prev, shifts: newShifts };
    });
  };

  const handleSelectShiftContact = (member) => {
    if (selectedShiftIndex !== null) {
      handleShiftChange(selectedShiftIndex, 'shift_contact', member.member_name);
      handleShiftChange(selectedShiftIndex, 'shift_contact_phone', member.phone);
      handleShiftChange(selectedShiftIndex, 'shift_contact_email', member.email);
    }
    setShowShiftContactDialog(false);
    setSelectedShiftIndex(null);
  };

  const handleAddRole = (shiftIndex) => {
    setFormData(prev => {
      const newShifts = [...prev.shifts];
      newShifts[shiftIndex].roles.push({
        role: "",
        department: "",
        count: 1,
        start_time: "09:00",
        end_time: "17:00",
        hours: 8,
        uniform: "Type 1",
        break_minutes: 30,
        rate_per_hour: 0,
        total_value: 0,
        vendor_id: prev.vendor_id,
        vendor_name: prev.vendor_name
      });
      return { ...prev, shifts: newShifts };
    });
  };

  const handleRemoveRole = (shiftIndex, roleIndex) => {
    setFormData(prev => {
      const newShifts = [...prev.shifts];
      newShifts[shiftIndex].roles.splice(roleIndex, 1);
      return { ...prev, shifts: newShifts };
    });
    updateGrandTotal();
  };

  const handleOrderTypeChange = (type) => {
    setFormData(prev => ({
      ...prev,
      order_type: type
    }));
  };

  const handleRapidInterfaceSubmit = (rapidData) => {
    // Parse the rapid message and populate form
    // For now, just add the message to notes and switch to standard view
    setFormData(prev => ({
      ...prev,
      notes: rapidData.rawMessage,
      event_name: "RAPID Order",
      date: new Date().toISOString().split('T')[0]
    }));

    // Switch back to standard form view
    setFormData(prev => ({
      ...prev,
      order_type: 'one_time'
    }));
  };

  const handleSubmit = (isDraft = false) => {
    const status = isDraft ? "Draft" :
      formData.order_type === "rapid" ? "Active" : "Pending";
    
    const totalRequested = formData.shifts.reduce((sum, shift) => {
      return sum + shift.roles.reduce((roleSum, role) => roleSum + (parseInt(role.count) || 0), 0);
    }, 0);
    
    onSubmit({ 
      ...formData, 
      status,
      requested: totalRequested
    });
  };



  return (
    <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
      {/* Left Column */}
      <div className="lg:col-span-4 space-y-4">
        <div>
          <Label className="text-sm font-semibold mb-3 block">Order Type</Label>
          <div className="grid grid-cols-2 gap-3">
            <button
              type="button"
              onClick={() => handleOrderTypeChange('rapid')}
              className={`p-4 rounded-lg border-2 transition-all flex flex-col items-center gap-2 ${
                formData.order_type === 'rapid'
                  ? 'border-red-500 bg-red-50'
                  : 'border-slate-200 hover:border-slate-300'
              }`}
            >
              <Zap className={`w-8 h-8 ${formData.order_type === 'rapid' ? 'text-red-600' : 'text-slate-400'}`} />
              <p className={`text-sm font-bold ${formData.order_type === 'rapid' ? 'text-red-600' : 'text-slate-600'}`}>RAPID</p>
              <p className={`text-xs ${formData.order_type === 'rapid' ? 'text-red-500' : 'text-slate-500'}`}>URGENT same-day Coverage</p>
            </button>

            <button
              type="button"
              onClick={() => handleOrderTypeChange('one_time')}
              className={`p-4 rounded-lg border-2 transition-all flex flex-col items-center gap-2 ${
                formData.order_type === 'one_time'
                  ? 'border-[#0A39DF] bg-blue-50'
                  : 'border-slate-200 hover:border-slate-300'
              }`}
            >
              <Calendar className={`w-8 h-8 ${formData.order_type === 'one_time' ? 'text-[#0A39DF]' : 'text-slate-400'}`} />
              <p className={`text-sm font-bold ${formData.order_type === 'one_time' ? 'text-[#0A39DF]' : 'text-slate-600'}`}>One-Time</p>
              <p className={`text-xs ${formData.order_type === 'one_time' ? 'text-blue-500' : 'text-slate-500'}`}>Single Event or Shift Request</p>
            </button>

            <button
              type="button"
              onClick={() => handleOrderTypeChange('recurring')}
              className={`p-4 rounded-lg border-2 transition-all flex flex-col items-center gap-2 ${
                formData.order_type === 'recurring'
                  ? 'border-purple-500 bg-purple-50'
                  : 'border-slate-200 hover:border-slate-300'
              }`}
            >
              <RefreshCw className={`w-8 h-8 ${formData.order_type === 'recurring' ? 'text-purple-600' : 'text-slate-400'}`} />
              <p className={`text-sm font-bold ${formData.order_type === 'recurring' ? 'text-purple-600' : 'text-slate-600'}`}>Recurring</p>
              <p className={`text-xs ${formData.order_type === 'recurring' ? 'text-purple-500' : 'text-slate-500'}`}>Ongoing Weekly / Monthly Coverage</p>
            </button>

            <button
              type="button"
              onClick={() => handleOrderTypeChange('permanent')}
              className={`p-4 rounded-lg border-2 transition-all flex flex-col items-center gap-2 ${
                formData.order_type === 'permanent'
                  ? 'border-green-500 bg-green-50'
                  : 'border-slate-200 hover:border-slate-300'
              }`}
            >
              <Users className={`w-8 h-8 ${formData.order_type === 'permanent' ? 'text-green-600' : 'text-slate-400'}`} />
              <p className={`text-sm font-bold ${formData.order_type === 'permanent' ? 'text-green-600' : 'text-slate-600'}`}>Permanent</p>
              <p className={`text-xs ${formData.order_type === 'permanent' ? 'text-green-500' : 'text-slate-500'}`}>Long-Term Staffing Placement</p>
            </button>
          </div>
        </div>

        <Card className="border-slate-200">
          <CardContent className="p-4 space-y-4">
            <Label className="text-sm font-semibold">Event Details</Label>

            {isVendor && (
              <div className="p-3 bg-amber-50 rounded-lg border border-amber-200">
                <Label className="text-xs font-semibold mb-2 flex items-center gap-2">
                  <Building2 className="w-4 h-4 text-amber-600" />
                  Select Client *
                </Label>
                <Select value={formData.business_id || ""} onValueChange={handleBusinessChange}>
                  <SelectTrigger className="h-10 bg-white">
                    <SelectValue placeholder="Choose client for this order" />
                  </SelectTrigger>
                  <SelectContent>
                    {businesses.map((business) => (
                      <SelectItem key={business.id} value={business.id}>
                        {business.business_name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {formData.business_id && (
                  <p className="text-xs text-amber-600 mt-2">
                    ✓ Client selected: {formData.business_name}
                  </p>
                )}
              </div>
            )}

            {isClient && (
              <div className="p-3 bg-blue-50 rounded-lg border border-blue-200">
                <Label className="text-xs font-semibold mb-2 flex items-center gap-2">
                  <Building2 className="w-4 h-4 text-blue-600" />
                  Select Vendor *
                  {currentUserData?.preferred_vendor_id === formData.vendor_id && (
                    <Badge className="bg-gradient-to-r from-blue-500 to-blue-600 text-white text-xs font-bold">
                      ⭐ Preferred
                    </Badge>
                  )}
                </Label>
                <Select value={formData.vendor_id || ""} onValueChange={handleVendorChange}>
                  <SelectTrigger className="h-10 bg-white">
                    <SelectValue placeholder="Choose vendor for this order" />
                  </SelectTrigger>
                  <SelectContent>
                    {vendors.filter(v => v.approval_status === 'approved').map((vendor) => (
                      <SelectItem key={vendor.id} value={vendor.id}>
                        {vendor.legal_name || vendor.doing_business_as}
                        {currentUserData?.preferred_vendor_id === vendor.id && (
                          <Badge className="ml-2 bg-gradient-to-r from-blue-500 to-blue-600 text-white text-xs font-bold">⭐ Preferred</Badge>
                        )}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {formData.vendor_id && (
                  <p className="text-xs text-blue-600 mt-2">
                    ✓ Rates will be automatically applied from {formData.vendor_name}
                    {currentUserData?.preferred_vendor_id === formData.vendor_id && " (Your preferred vendor)"}
                  </p>
                )}
              </div>
            )}

            <div>
              <Label className="text-sm mb-1.5 block">Hub *</Label>
              {isClient && teamHubs.length > 0 ? (
                <Select value={formData.hub || ""} onValueChange={(value) => handleChange('hub', value)}>
                  <SelectTrigger className="h-10">
                    <SelectValue placeholder="Hub location" />
                  </SelectTrigger>
                  <SelectContent>
                    {teamHubs.map((hub) => (
                      <SelectItem key={hub.id} value={hub.hub_name}>
                        {hub.hub_name}
                        {hub.departments && hub.departments.length > 0 && (
                          <span className="text-xs text-slate-500 ml-2">
                            ({hub.departments.map(d => d.cost_center).filter(Boolean).join(', ')})
                          </span>
                        )}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              ) : (
                <Input
                  value={formData.hub || ""}
                  onChange={(e) => handleChange('hub', e.target.value)}
                  placeholder="Hub location"
                  className="h-10"
                  required
                />
              )}
            </div>

            <div>
              <Label className="text-sm mb-1.5 block">Department</Label>
              <Input
                value={formData.department || ""}
                onChange={(e) => handleChange('department', e.target.value)}
                placeholder="Department name"
                className="h-10"
              />
            </div>

            {formData.order_type === 'recurring' ? (
              <>
                <div>
                  <Label className="text-sm mb-1.5 block">Start Date *</Label>
                  <Input
                    type="date"
                    value={formData.recurring_start_date || ""}
                    onChange={(e) => {
                      const dateValue = e.target.value;
                      handleChange('recurring_start_date', dateValue);
                    }}
                    className="h-10"
                    required
                  />
                </div>
                <div>
                  <Label className="text-sm mb-1.5 block">End Date *</Label>
                  <Input
                    type="date"
                    value={formData.recurring_end_date || ""}
                    onChange={(e) => {
                      const dateValue = e.target.value;
                      handleChange('recurring_end_date', dateValue);
                    }}
                    className="h-10"
                    required
                  />
                </div>
                <div>
                  <Label className="text-sm mb-2 block">Recurring Days *</Label>
                  <div className="flex gap-2">
                    {['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((day, idx) => {
                      const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
                      const isSelected = formData.recurring_days?.includes(dayNames[idx]);
                      return (
                        <button
                          key={idx}
                          type="button"
                          onClick={() => {
                            const current = formData.recurring_days || [];
                            const updated = isSelected 
                              ? current.filter(d => d !== dayNames[idx])
                              : [...current, dayNames[idx]];
                            handleChange('recurring_days', updated);
                          }}
                          className={`w-10 h-10 rounded-full font-bold transition-all ${
                            isSelected 
                              ? 'bg-purple-600 text-white shadow-lg' 
                              : 'bg-white border-2 border-slate-300 text-slate-600 hover:border-purple-400'
                          }`}
                        >
                          {day}
                        </button>
                      );
                    })}
                  </div>
                  {formData.recurring_days?.length > 0 && (
                    <p className="text-xs text-slate-600 mt-2">
                      Every {formData.recurring_days.join(', ')}
                    </p>
                  )}
                </div>
              </>
            ) : formData.order_type === 'permanent' ? (
              <>
                <div>
                  <Label className="text-sm mb-1.5 block">Start Date *</Label>
                  <Input
                    type="date"
                    value={formData.permanent_start_date || ""}
                    onChange={(e) => {
                      const dateValue = e.target.value;
                      handleChange('permanent_start_date', dateValue);
                    }}
                    className="h-10"
                    required
                  />
                </div>
                <div>
                  <Label className="text-sm mb-2 block">Working Days *</Label>
                  <div className="flex gap-2">
                    {['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((day, idx) => {
                      const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
                      const isSelected = formData.permanent_days?.includes(dayNames[idx]);
                      return (
                        <button
                          key={idx}
                          type="button"
                          onClick={() => {
                            const current = formData.permanent_days || [];
                            const updated = isSelected 
                              ? current.filter(d => d !== dayNames[idx])
                              : [...current, dayNames[idx]];
                            handleChange('permanent_days', updated);
                          }}
                          className={`w-10 h-10 rounded-full font-bold transition-all ${
                            isSelected 
                              ? 'bg-green-600 text-white shadow-lg' 
                              : 'bg-white border-2 border-slate-300 text-slate-600 hover:border-green-400'
                          }`}
                        >
                          {day}
                        </button>
                      );
                    })}
                  </div>
                  {formData.permanent_days?.length > 0 && (
                    <p className="text-xs text-slate-600 mt-2">
                      Every {formData.permanent_days.join(', ')}
                    </p>
                  )}
                </div>
              </>
            ) : (
              <div>
                <Label className="text-sm mb-1.5 block">Date *</Label>
                <Input
                  type="date"
                  value={formData.date || ""}
                  onChange={(e) => {
                    const dateValue = e.target.value;
                    // Store date as-is without timezone conversion
                    handleChange('date', dateValue);
                  }}
                  className="h-10"
                  required
                />
              </div>
            )}

            <div>
              <Label className="text-sm mb-1.5 block">Event Name</Label>
              <Input
                value={formData.event_name || ""}
                onChange={(e) => handleChange('event_name', e.target.value)}
                placeholder="Event name (optional)"
                className="h-10"
              />
            </div>

            <div>
              <Label className="text-sm mb-1.5 block">PO Reference</Label>
              <Input
                value={formData.po_reference || ""}
                onChange={(e) => handleChange('po_reference', e.target.value)}
                placeholder="Purchase order number (optional)"
                className="h-10"
              />
            </div>



            <div className="flex items-center gap-2 p-2.5 bg-green-50 rounded-lg">
              <Checkbox
                id="backup"
                checked={formData.include_backup}
                onCheckedChange={(checked) => handleChange('include_backup', checked)}
              />
              <Label htmlFor="backup" className="text-sm cursor-pointer">Backup Staff</Label>
            </div>
          </CardContent>
        </Card>

        <Card className="border-2 border-[#0A39DF] bg-gradient-to-br from-blue-50 to-white">
          <CardContent className="p-6">
            <div className="text-center">
              <p className="text-sm text-slate-600 mb-1">Total</p>
              <p className="text-4xl font-bold text-[#0A39DF]">${(formData.total || 0).toFixed(2)}</p>
            </div>
          </CardContent>
        </Card>

        <div className="space-y-3">
          <Button
            onClick={() => handleSubmit(false)}
            disabled={isSubmitting}
            className="w-full bg-blue-600 hover:bg-blue-700 text-white h-11 text-base font-semibold"
          >
            <Save className="w-5 h-5 mr-2" />
            Submit Order
          </Button>
          <Button
            variant="outline"
            onClick={() => handleSubmit(true)}
            disabled={isSubmitting}
            className="w-full h-10"
          >
            Save as Draft
          </Button>
          <Button
            variant="ghost"
            onClick={onCancel}
            className="w-full h-10"
          >
            Cancel
          </Button>
        </div>
      </div>

      {/* Right Column */}
      <div className="lg:col-span-8 space-y-4">
        {/* RAPID Interface - Shows when RAPID is selected */}
        {formData.order_type === 'rapid' && (
          <div className="mb-4">
            <RapidOrderInterface
              onBack={() => handleOrderTypeChange('one_time')}
              onSubmit={handleRapidInterfaceSubmit}
            />
          </div>
        )}

        {/* Show standard form sections only when NOT RAPID */}
        {formData.order_type !== 'rapid' && (
          <>
        <Card className="border-slate-200">
          <CardHeader className="pb-3">
            <CardTitle className="text-lg">Shifts & Roles</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {formData.shifts.map((shift, shiftIdx) => (
              <div key={shiftIdx} className="space-y-4">
                <div className="flex items-start justify-between pb-4 border-b border-slate-200">
                  <div className="flex items-start gap-3 flex-1">
                    <MapPin className="w-5 h-5 text-blue-600 mt-1" />
                    <div className="flex-1">
                      <h4 className="font-bold text-lg text-slate-900 mb-1">{shift.shift_name}</h4>
                      <div className="text-sm text-slate-600">
                        <GoogleAddressInput
                          value={shift.location_address || formData.hub || ""}
                          onChange={(value) => handleShiftChange(shiftIdx, 'location_address', value)}
                          placeholder="Enter location address..."
                        />
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    {shift.shift_contact ? (
                      <div className="flex items-center gap-2 bg-blue-50 px-3 py-1.5 rounded-lg border border-blue-200">
                        <div>
                          <p className="text-sm font-semibold text-blue-900">{shift.shift_contact}</p>
                          <p className="text-xs text-blue-600">{shift.shift_contact_phone || shift.shift_contact_email}</p>
                        </div>
                        <Button
                          type="button"
                          size="icon"
                          variant="ghost"
                          className="h-6 w-6 text-blue-600 hover:bg-blue-100"
                          onClick={() => {
                            handleShiftChange(shiftIdx, 'shift_contact', '');
                            handleShiftChange(shiftIdx, 'shift_contact_phone', '');
                            handleShiftChange(shiftIdx, 'shift_contact_email', '');
                          }}
                        >
                          <X className="w-4 h-4" />
                        </Button>
                      </div>
                    ) : (
                      <Button
                        type="button"
                        size="sm"
                        className="h-9 bg-blue-100 hover:bg-blue-200 text-blue-700 border-0"
                        onClick={() => {
                          setSelectedShiftIndex(shiftIdx);
                          setShowShiftContactDialog(true);
                        }}
                      >
                        <UserPlus className="w-4 h-4 mr-2" />
                        Add shift contact
                      </Button>
                    )}
                    {formData.shifts.length > 1 && (
                      <Button
                        type="button"
                        size="sm"
                        variant="ghost"
                        onClick={() => handleRemoveShift(shiftIdx)}
                        className="text-red-600 hover:bg-red-50 h-9"
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    )}
                  </div>
                </div>

                {shift.roles.map((role, roleIdx) => (
                  <div key={roleIdx} className="p-4 bg-slate-50 rounded-lg space-y-3 border border-slate-200">
                    <div className="grid grid-cols-12 gap-3">
                      <div className="col-span-3">
                        <Label className="text-sm mb-1.5 block">Role</Label>
                        <Popover open={roleSearchOpen[`${shiftIdx}-${roleIdx}`]} onOpenChange={(open) => setRoleSearchOpen(prev => ({ ...prev, [`${shiftIdx}-${roleIdx}`]: open }))}>
                          <PopoverTrigger asChild>
                            <Button className="w-full h-10 justify-between bg-blue-50 hover:bg-blue-100 text-blue-900 border-blue-200">
                              {role.role || "Select..."}
                              <Search className="w-4 h-4 ml-2" />
                            </Button>
                          </PopoverTrigger>
                          <PopoverContent className="w-[300px] p-0">
                            <Command>
                              <CommandInput placeholder="Search roles..." className="h-9" />
                              <CommandEmpty>No role found.</CommandEmpty>
                              <CommandGroup className="max-h-60 overflow-auto">
                                {availableRoles.map((roleName) => (
                                  <CommandItem
                                    key={roleName}
                                    onSelect={() => {
                                      handleRoleChange(shiftIdx, roleIdx, 'role', roleName);
                                      setRoleSearchOpen(prev => ({ ...prev, [`${shiftIdx}-${roleIdx}`]: false }));
                                    }}
                                    className="aria-selected:bg-blue-100 aria-selected:text-blue-900"
                                  >
                                    {roleName}
                                  </CommandItem>
                                ))}
                              </CommandGroup>
                            </Command>
                          </PopoverContent>
                        </Popover>
                      </div>

                      <div className="col-span-3">
                        <Label className="text-sm mb-1.5 block">Count</Label>
                        <div className="flex items-center gap-1">
                          <Button
                            type="button"
                            size="icon"
                            variant="outline"
                            className="h-10 w-10 shrink-0"
                            onClick={() => handleRoleChange(shiftIdx, roleIdx, 'count', Math.max(1, role.count - 1))}
                          >
                            <Minus className="w-4 h-4" />
                          </Button>
                          <Input
                            type="number"
                            min="1"
                            value={role.count || 1}
                            onChange={(e) => handleRoleChange(shiftIdx, roleIdx, 'count', Math.max(1, parseInt(e.target.value) || 1))}
                            className="h-10 flex-1 text-center font-bold text-blue-600 text-xl border border-slate-300 bg-white"
                          />
                          <Button
                            type="button"
                            size="icon"
                            variant="outline"
                            className="h-10 w-10 shrink-0"
                            onClick={() => handleRoleChange(shiftIdx, roleIdx, 'count', role.count + 1)}
                          >
                            <Plus className="w-4 h-4" />
                          </Button>
                        </div>
                      </div>

                      <div className="col-span-2">
                        <Label className="text-sm mb-1.5 block">Start</Label>
                        <Input
                          type="time"
                          value={role.start_time}
                          onChange={(e) => handleRoleChange(shiftIdx, roleIdx, 'start_time', e.target.value)}
                          className="h-10"
                        />
                      </div>

                      <div className="col-span-2">
                        <Label className="text-sm mb-1.5 block">End</Label>
                        <Input
                          type="time"
                          value={role.end_time}
                          onChange={(e) => handleRoleChange(shiftIdx, roleIdx, 'end_time', e.target.value)}
                          className="h-10"
                        />
                      </div>

                      <div className="col-span-2">
                        <Label className="text-sm mb-1.5 block">Hours</Label>
                        <div className="h-10 bg-blue-600 text-white rounded-md flex items-center justify-center font-bold text-lg">
                          {role.hours % 1 === 0 ? role.hours : (role.hours || 0).toFixed(2)}h
                        </div>
                      </div>
                    </div>

                    <div>
                      <Label className="text-sm mb-2 block">Break:</Label>
                      <div className="flex gap-2">
                        <button
                          type="button"
                          onClick={() => handleRoleChange(shiftIdx, roleIdx, 'break_minutes', 15)}
                          className={`px-4 py-2 rounded-md text-sm font-medium transition-all ${
                            role.break_minutes === 15
                              ? 'bg-green-500 text-white shadow-md'
                              : 'bg-white border border-slate-300 text-slate-700 hover:border-green-400'
                          }`}
                        >
                          15 Min Payable
                        </button>
                        <button
                          type="button"
                          onClick={() => handleRoleChange(shiftIdx, roleIdx, 'break_minutes', 30)}
                          className={`px-4 py-2 rounded-md text-sm font-medium transition-all ${
                            role.break_minutes === 30
                              ? 'bg-amber-500 text-white shadow-md'
                              : 'bg-white border border-slate-300 text-slate-700 hover:border-amber-400'
                          }`}
                        >
                          30 Min Non-Payable
                        </button>
                        <button
                          type="button"
                          onClick={() => handleRoleChange(shiftIdx, roleIdx, 'break_minutes', 0)}
                          className={`px-4 py-2 rounded-md text-sm font-medium transition-all ${
                            role.break_minutes === 0 || !role.break_minutes
                              ? 'bg-slate-500 text-white shadow-md'
                              : 'bg-white border border-slate-300 text-slate-700 hover:border-slate-400'
                          }`}
                        >
                          No Break
                        </button>
                      </div>
                    </div>

                    <div className="flex items-center justify-between pt-2 border-t border-slate-200">
                      <span className="text-sm text-slate-600">Rate: ${(role.rate_per_hour || 0).toFixed(2)}/hr</span>
                      <div className="flex items-center gap-3">
                        <span className="font-bold text-[#0A39DF] text-base">Total: ${(role.total_value || 0).toFixed(2)}</span>
                        {shift.roles.length > 1 && (
                          <Button
                            size="icon"
                            variant="ghost"
                            onClick={() => handleRemoveRole(shiftIdx, roleIdx)}
                            className="h-8 w-8 text-red-600 hover:bg-red-50"
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        )}
                      </div>
                    </div>
                  </div>
                ))}

                <button
                  type="button"
                  onClick={() => handleAddRole(shiftIdx)}
                  className="flex items-center gap-2 text-blue-600 hover:text-blue-700 font-medium text-sm transition-colors"
                >
                  <Plus className="w-4 h-4" />
                  Add role
                </button>
              </div>
            ))}

            <Button
              type="button"
              variant="outline"
              onClick={handleAddShift}
              className="w-full h-12 border-2 border-slate-300 hover:border-slate-400 hover:bg-slate-50 rounded-full text-slate-700 font-medium"
            >
              <Plus className="w-5 h-5 mr-2" />
              Add location
            </Button>
          </CardContent>
        </Card>

        <Card className="border-slate-200">
          <CardHeader className="pb-3">
            <CardTitle className="text-base">Additional Notes</CardTitle>
          </CardHeader>
          <CardContent>
            <Textarea
              value={formData.notes || ""}
              onChange={(e) => handleChange('notes', e.target.value)}
              placeholder="Special instructions..."
              rows={4}
              className="resize-none"
            />
          </CardContent>
        </Card>
        </>
        )}
      </div>

      {/* Shift Contact Dialog */}
      <Dialog open={showShiftContactDialog} onOpenChange={setShowShiftContactDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Select Shift Contact</DialogTitle>
          </DialogHeader>
          <div className="max-h-96 overflow-y-auto space-y-2">
            {teamMembers.length > 0 ? (
              teamMembers.map((member) => (
                <Card 
                  key={member.id} 
                  className="cursor-pointer hover:bg-blue-50 transition-colors border-slate-200"
                  onClick={() => handleSelectShiftContact(member)}
                >
                  <CardContent className="p-4">
                    <div className="flex items-center gap-3">
                      <Avatar className="w-12 h-12">
                        <AvatarImage src={member.avatar_url} />
                        <AvatarFallback className="bg-[#0A39DF] text-white font-bold">
                          {member.member_name?.charAt(0)}
                        </AvatarFallback>
                      </Avatar>
                      <div className="flex-1">
                        <p className="font-semibold text-slate-900">{member.member_name}</p>
                        <p className="text-sm text-slate-600">{member.title || member.role}</p>
                        <div className="flex gap-2 mt-1">
                          {member.phone && (
                            <p className="text-xs text-slate-500">{member.phone}</p>
                          )}
                          {member.email && (
                            <p className="text-xs text-slate-500">{member.email}</p>
                          )}
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))
            ) : (
              <div className="text-center py-8 text-slate-500">
                <p>No team members available</p>
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}