import React, { useState, useMemo } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Plus, Building2, Mail, Phone, MapPin, Search, Eye, Trash2, ChevronDown, ChevronRight, Users, Star, Ban, Briefcase, Settings, UserPlus, UserMinus, Shield, Edit2, TrendingUp, Clock, Award, Grid3x3, List } from "lucide-react";
import BusinessCard from "@/components/business/BusinessCard";
import { Link, useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import PageHeader from "@/components/common/PageHeader";

import CreateBusinessModal from "@/components/business/CreateBusinessModal";

export default function Business() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [searchTerm, setSearchTerm] = useState("");
  const [createModalOpen, setCreateModalOpen] = useState(false);
  const [filterManager, setFilterManager] = useState("all");
  const [filterHub, setFilterHub] = useState("all");
  const [filterGrade, setFilterGrade] = useState("all");
  const [filterCancelRate, setFilterCancelRate] = useState("all");
  const [viewMode, setViewMode] = useState("grid"); // grid or list

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

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

  const { data: allStaff = [] } = useQuery({
    queryKey: ['staff-for-business'],
    queryFn: () => base44.entities.Staff.list(),
  });

  const { data: allEvents = [] } = useQuery({
    queryKey: ['events-for-business-metrics'],
    queryFn: () => base44.entities.Event.list(),
    initialData: [],
  });

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

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

  const createBusinessMutation = useMutation({
    mutationFn: (businessData) => base44.entities.Business.create(businessData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['businesses'] });
      setCreateModalOpen(false);
    },
  });

  const updateBusinessMutation = useMutation({
    mutationFn: ({ id, data }) => base44.entities.Business.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['businesses'] });
    },
  });

  const handleCreateBusiness = (businessData) => {
    createBusinessMutation.mutate(businessData);
  };

  const handleAddFavoriteStaff = async (businessId, staff) => {
    const business = businesses.find(b => b.id === businessId);
    const favoriteStaff = business.favorite_staff || [];
    const alreadyFavorite = favoriteStaff.some(s => s.staff_id === staff.id);
    
    if (alreadyFavorite) return;

    const updatedFavorites = [
      ...favoriteStaff,
      {
        staff_id: staff.id,
        staff_name: staff.employee_name,
        position: staff.position,
        added_date: new Date().toISOString(),
      }
    ];

    await updateBusinessMutation.mutateAsync({
      id: businessId,
      data: {
        favorite_staff: updatedFavorites,
        favorite_staff_count: updatedFavorites.length,
      }
    });
  };

  const handleRemoveFavoriteStaff = async (businessId, staffId) => {
    const business = businesses.find(b => b.id === businessId);
    const favoriteStaff = business.favorite_staff || [];
    const updatedFavorites = favoriteStaff.filter(s => s.staff_id !== staffId);

    await updateBusinessMutation.mutateAsync({
      id: businessId,
      data: {
        favorite_staff: updatedFavorites,
        favorite_staff_count: updatedFavorites.length,
      }
    });
  };

  const handleBlockStaff = async (businessId, staff, reason) => {
    const business = businesses.find(b => b.id === businessId);
    const blockedStaff = business.blocked_staff || [];
    const alreadyBlocked = blockedStaff.some(s => s.staff_id === staff.id);
    
    if (alreadyBlocked) return;

    const updatedBlocked = [
      ...blockedStaff,
      {
        staff_id: staff.id,
        staff_name: staff.employee_name,
        reason: reason || "No reason provided",
        blocked_date: new Date().toISOString(),
      }
    ];

    await updateBusinessMutation.mutateAsync({
      id: businessId,
      data: {
        blocked_staff: updatedBlocked,
        blocked_staff_count: updatedBlocked.length,
      }
    });
  };

  const handleUnblockStaff = async (businessId, staffId) => {
    const business = businesses.find(b => b.id === businessId);
    const blockedStaff = business.blocked_staff || [];
    const updatedBlocked = blockedStaff.filter(s => s.staff_id !== staffId);

    await updateBusinessMutation.mutateAsync({
      id: businessId,
      data: {
        blocked_staff: updatedBlocked,
        blocked_staff_count: updatedBlocked.length,
      }
    });
  };

  // Consolidate businesses by company name
  const consolidatedBusinesses = useMemo(() => {
    const grouped = {};
    
    businesses.forEach(business => {
      // Extract company name (remove hub suffix if present)
      let companyName = business.business_name;
      
      // Handle cases like "Google - BVG300" or "Nvidia - Building S"
      const dashIndex = companyName.indexOf(' - ');
      if (dashIndex > 0) {
        companyName = companyName.substring(0, dashIndex).trim();
      }
      
      // Initialize company if not exists
      if (!grouped[companyName]) {
        grouped[companyName] = {
          company_name: companyName,
          hubs: [],
          primary_contact: business.contact_name,
          primary_email: business.email,
          primary_phone: business.phone,
          sector: business.notes?.includes('Sector:') ? business.notes.split('Sector:')[1].trim() : '',
        };
      }
      
      // Add hub
      grouped[companyName].hubs.push({
        id: business.id,
        hub_name: business.business_name,
        contact_name: business.contact_name,
        email: business.email,
        phone: business.phone,
        address: business.address,
        city: business.city,
        notes: business.notes,
      });
    });
    
    return Object.values(grouped);
  }, [businesses]);

  // Get unique managers and hubs for filters
  const allManagers = [...new Set(consolidatedBusinesses.flatMap(c => c.hubs.map(h => h.contact_name).filter(Boolean)))];
  const allHubs = [...new Set(consolidatedBusinesses.flatMap(c => c.hubs.map(h => h.hub_name)))];

  const filteredBusinesses = consolidatedBusinesses.filter(company => {
    const matchesSearch = !searchTerm || 
      company.company_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      company.hubs.some(hub => 
        hub.hub_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        hub.contact_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        hub.address?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    
    const matchesManager = filterManager === "all" || 
      company.hubs.some(hub => hub.contact_name === filterManager);
    
    const matchesHub = filterHub === "all" || 
      company.hubs.some(hub => hub.hub_name === filterHub);
    
    // Calculate metrics for filtering
    const clientEvents = allEvents.filter(e => 
      e.business_name === company.company_name || 
      company.hubs.some(h => h.hub_name === e.business_name)
    );
    const totalOrders = clientEvents.length;
    const canceledOrders = clientEvents.filter(e => e.status === 'Canceled').length;
    const cancelationRate = totalOrders > 0 ? ((canceledOrders / totalOrders) * 100) : 0;
    
    const totalStaffRequested = clientEvents.reduce((sum, e) => sum + (e.requested || 0), 0);
    const totalStaffAssigned = clientEvents.reduce((sum, e) => sum + (e.assigned_staff?.length || 0), 0);
    const fillRate = totalStaffRequested > 0 ? ((totalStaffAssigned / totalStaffRequested) * 100) : 0;
    
    const onTimeOrders = clientEvents.filter(e => {
      const eventDate = new Date(e.date);
      const createdDate = new Date(e.created_date);
      const daysDiff = (eventDate - createdDate) / (1000 * 60 * 60 * 24);
      return daysDiff >= 3;
    }).length;
    const onTimeRate = totalOrders > 0 ? ((onTimeOrders / totalOrders) * 100) : 0;
    
    const metrics = [
      parseFloat(fillRate),
      parseFloat(onTimeRate),
      100 - parseFloat(cancelationRate),
      Math.min((totalOrders / 10) * 100, 100)
    ];
    const avgScore = metrics.reduce((a, b) => a + b, 0) / metrics.length;
    let clientGrade = 'C';
    if (avgScore >= 90) clientGrade = 'A+';
    else if (avgScore >= 85) clientGrade = 'A';
    else if (avgScore >= 80) clientGrade = 'A-';
    else if (avgScore >= 75) clientGrade = 'B+';
    else if (avgScore >= 70) clientGrade = 'B';
    
    const matchesGrade = filterGrade === "all" || clientGrade === filterGrade;
    
    const matchesCancelRate = 
      filterCancelRate === "all" ||
      (filterCancelRate === "low" && cancelationRate < 5) ||
      (filterCancelRate === "medium" && cancelationRate >= 5 && cancelationRate < 15) ||
      (filterCancelRate === "high" && cancelationRate >= 15);
    
    return matchesSearch && matchesManager && matchesHub && matchesGrade && matchesCancelRate;
  });



  const canAddBusiness = ["admin", "procurement", "operator", "vendor"].includes(userRole);

  const totalHubs = filteredBusinesses.reduce((sum, company) => sum + company.hubs.length, 0);

  // Calculate KPIs
  const totalCompanies = filteredBusinesses.length;
  const goldClients = filteredBusinesses.filter(company => {
    const clientEvents = allEvents.filter(e => 
      e.business_name === company.company_name || 
      company.hubs.some(h => h.hub_name === e.business_name)
    );
    const totalOrders = clientEvents.length;
    const canceledOrders = clientEvents.filter(e => e.status === 'Canceled').length;
    const cancelationRate = totalOrders > 0 ? ((canceledOrders / totalOrders) * 100) : 0;
    const totalStaffRequested = clientEvents.reduce((sum, e) => sum + (e.requested || 0), 0);
    const totalStaffAssigned = clientEvents.reduce((sum, e) => sum + (e.assigned_staff?.length || 0), 0);
    const fillRate = totalStaffRequested > 0 ? ((totalStaffAssigned / totalStaffRequested) * 100) : 0;
    const onTimeOrders = clientEvents.filter(e => {
      const eventDate = new Date(e.date);
      const createdDate = new Date(e.created_date);
      const daysDiff = (eventDate - createdDate) / (1000 * 60 * 60 * 24);
      return daysDiff >= 3;
    }).length;
    const onTimeRate = totalOrders > 0 ? ((onTimeOrders / totalOrders) * 100) : 0;
    const metrics = [parseFloat(fillRate), parseFloat(onTimeRate), 100 - parseFloat(cancelationRate), Math.min((totalOrders / 10) * 100, 100)];
    const avgScore = metrics.reduce((a, b) => a + b, 0) / metrics.length;
    return avgScore >= 90;
  }).length;

  const totalMonthlySpend = filteredBusinesses.reduce((sum, company) => {
    const clientInvoices = invoices.filter(i => 
      i.business_name === company.company_name ||
      company.hubs.some(h => h.hub_name === i.business_name)
    );
    const monthlySpend = clientInvoices
      .filter(i => {
        const invoiceDate = new Date(i.created_date);
        const now = new Date();
        return invoiceDate.getMonth() === now.getMonth() && invoiceDate.getFullYear() === now.getFullYear();
      })
      .reduce((s, i) => s + (i.amount || 0), 0);
    return sum + monthlySpend;
  }, 0);

  const totalOrders = filteredBusinesses.reduce((sum, company) => {
    const clientEvents = allEvents.filter(e => 
      e.business_name === company.company_name || 
      company.hubs.some(h => h.hub_name === e.business_name)
    );
    return sum + clientEvents.length;
  }, 0);

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        <PageHeader 
          title="Business Directory"
          subtitle="Manage and monitor all business clients and their performance"
          actions={
            canAddBusiness ? (
              <Button 
                onClick={() => setCreateModalOpen(true)}
                className="bg-blue-600 hover:bg-blue-700 text-white shadow-lg"
              >
                <Plus className="w-5 h-5 mr-2" />
                Add Business
              </Button>
            ) : null
          }
        />

        {/* KPI Dashboard */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          <Card className="bg-gradient-to-br from-blue-600 to-blue-700 border-0 shadow-lg">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-blue-100 text-sm font-medium mb-1">Total Companies</p>
                  <p className="text-4xl font-bold text-white">{totalCompanies}</p>
                </div>
                <div className="w-14 h-14 bg-white/20 rounded-xl flex items-center justify-center">
                  <Building2 className="w-8 h-8 text-white" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-amber-500 to-yellow-600 border-0 shadow-lg">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-amber-100 text-sm font-medium mb-1">Gold Clients</p>
                  <p className="text-4xl font-bold text-white">{goldClients}</p>
                  <p className="text-xs text-amber-100 mt-1">A+ Performance</p>
                </div>
                <div className="w-14 h-14 bg-white/20 rounded-xl flex items-center justify-center">
                  <Award className="w-8 h-8 text-white" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-green-600 to-emerald-700 border-0 shadow-lg">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-green-100 text-sm font-medium mb-1">Monthly Sales</p>
                  <p className="text-4xl font-bold text-white">${(totalMonthlySpend / 1000).toFixed(0)}k</p>
                </div>
                <div className="w-14 h-14 bg-white/20 rounded-xl flex items-center justify-center">
                  <TrendingUp className="w-8 h-8 text-white" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-slate-700 to-slate-800 border-0 shadow-lg">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-slate-100 text-sm font-medium mb-1">Total Orders</p>
                  <p className="text-4xl font-bold text-white">{totalOrders}</p>
                  <p className="text-xs text-slate-300 mt-1">{totalHubs} Hubs</p>
                </div>
                <div className="w-14 h-14 bg-white/20 rounded-xl flex items-center justify-center">
                  <Briefcase className="w-8 h-8 text-white" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Filters Section */}
        <div className="mb-6 space-y-4">
          {/* Search Bar */}
          <div className="relative">
            <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-slate-400" />
            <Input
              placeholder="Search companies, hubs, contacts, or addresses..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-12 h-12 bg-white border-slate-300 text-base shadow-sm"
            />
          </div>

          {/* Filter Pills */}
          <div className="flex flex-wrap gap-3">
            <select
              value={filterManager}
              onChange={(e) => setFilterManager(e.target.value)}
              className="px-4 py-2 bg-white border border-slate-300 rounded-lg text-sm font-medium text-slate-700 hover:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            >
              <option value="all">All Managers</option>
              {allManagers.map(manager => (
                <option key={manager} value={manager}>{manager}</option>
              ))}
            </select>

            <select
              value={filterHub}
              onChange={(e) => setFilterHub(e.target.value)}
              className="px-4 py-2 bg-white border border-slate-300 rounded-lg text-sm font-medium text-slate-700 hover:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            >
              <option value="all">All Hubs</option>
              {allHubs.map(hub => (
                <option key={hub} value={hub}>{hub}</option>
              ))}
            </select>

            {isVendor && (
              <>
                <select
                  value={filterGrade}
                  onChange={(e) => setFilterGrade(e.target.value)}
                  className="px-4 py-2 bg-white border border-slate-300 rounded-lg text-sm font-medium text-slate-700 hover:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="all">All Grades</option>
                  <option value="A+">A+ Grade</option>
                  <option value="A">A Grade</option>
                  <option value="A-">A- Grade</option>
                  <option value="B+">B+ Grade</option>
                  <option value="B">B Grade</option>
                  <option value="C">C Grade</option>
                </select>

                <select
                  value={filterCancelRate}
                  onChange={(e) => setFilterCancelRate(e.target.value)}
                  className="px-4 py-2 bg-white border border-slate-300 rounded-lg text-sm font-medium text-slate-700 hover:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="all">All Cancellation Rates</option>
                  <option value="low">Low (&lt;5%)</option>
                  <option value="medium">Medium (5-15%)</option>
                  <option value="high">High (&gt;15%)</option>
                </select>
              </>
            )}

            {(searchTerm || filterManager !== "all" || filterHub !== "all" || filterGrade !== "all" || filterCancelRate !== "all") && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => {
                  setSearchTerm("");
                  setFilterManager("all");
                  setFilterHub("all");
                  setFilterGrade("all");
                  setFilterCancelRate("all");
                }}
                className="text-blue-600 hover:text-blue-700 hover:bg-blue-50"
              >
                Clear Filters
              </Button>
            )}
            </div>

            {/* View Mode Toggle */}
            <div className="flex items-center gap-2 bg-white border border-slate-200 rounded-lg p-1">
            <Button
              variant={viewMode === "grid" ? "default" : "ghost"}
              size="sm"
              onClick={() => setViewMode("grid")}
              className={viewMode === "grid" ? "bg-blue-600 text-white" : "text-slate-600"}
            >
              <Grid3x3 className="w-4 h-4 mr-1" />
              Grid
            </Button>
            <Button
              variant={viewMode === "list" ? "default" : "ghost"}
              size="sm"
              onClick={() => setViewMode("list")}
              className={viewMode === "list" ? "bg-blue-600 text-white" : "text-slate-600"}
            >
              <List className="w-4 h-4 mr-1" />
              List
            </Button>
            </div>
            </div>

        {/* Business List */}
        {filteredBusinesses.length > 0 ? (
          <div className={viewMode === "grid" ? "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" : "space-y-4"}>
            {filteredBusinesses.map((company) => {
              // Get all businesses that belong to this company
              const companyBusinesses = businesses.filter(b => 
                b.business_name === company.company_name || 
                b.business_name.startsWith(company.company_name + ' - ')
              );
              
              const firstBusiness = companyBusinesses[0];
              
              // Collect team members from all businesses in this company
              const teamMembers = [];
              companyBusinesses.forEach(bus => {
                if (bus.team_members) {
                  bus.team_members.forEach(member => {
                    if (!teamMembers.some(m => m.email === member.email)) {
                      teamMembers.push(member);
                    }
                  });
                }
              });
              
              // Extract hub managers from company.hubs (which contains hub info from consolidated structure)
              const hubContacts = company.hubs
                .filter(hub => hub.contact_name)
                .map(hub => ({
                  member_id: `hub-${hub.hub_name}`,
                  member_name: hub.contact_name,
                  email: hub.email || '',
                  phone: hub.phone,
                  role: 'Hub Manager',
                  title: 'Hub Manager',
                  hub: hub.hub_name,
                  is_active: true
                }));
              
              // Combine team members and hub contacts, removing duplicates
              const allTeamMembers = [...teamMembers];
              hubContacts.forEach(hubContact => {
                const alreadyExists = allTeamMembers.some(m => 
                  (hubContact.email && m.email === hubContact.email) || 
                  (!hubContact.email && m.member_name === hubContact.member_name)
                );
                if (!alreadyExists) {
                  allTeamMembers.push(hubContact);
                }
              });
              
              const activeMembers = allTeamMembers.filter(m => m.is_active !== false).length;
              const totalMembers = allTeamMembers.length;

              // Calculate client metrics for vendor view
              const clientEvents = allEvents.filter(e => 
                e.business_name === company.company_name || 
                company.hubs.some(h => h.hub_name === e.business_name)
              );
              
              const totalOrders = clientEvents.length;
              const completedOrders = clientEvents.filter(e => e.status === 'Completed').length;
              const canceledOrders = clientEvents.filter(e => e.status === 'Canceled').length;
              const cancelationRate = totalOrders > 0 ? ((canceledOrders / totalOrders) * 100).toFixed(0) : 0;
              
              const totalStaffRequested = clientEvents.reduce((sum, e) => sum + (e.requested || 0), 0);
              const totalStaffAssigned = clientEvents.reduce((sum, e) => sum + (e.assigned_staff?.length || 0), 0);
              const fillRate = totalStaffRequested > 0 ? ((totalStaffAssigned / totalStaffRequested) * 100).toFixed(0) : 0;
              
              const clientInvoices = invoices.filter(i => 
                i.business_name === company.company_name ||
                company.hubs.some(h => h.hub_name === i.business_name)
              );
              const monthlySpend = clientInvoices
                .filter(i => {
                  const invoiceDate = new Date(i.created_date);
                  const now = new Date();
                  return invoiceDate.getMonth() === now.getMonth() && invoiceDate.getFullYear() === now.getFullYear();
                })
                .reduce((sum, i) => sum + (i.amount || 0), 0);
              
              const avgOrderValue = totalOrders > 0 ? clientInvoices.reduce((sum, i) => sum + (i.amount || 0), 0) / totalOrders : 0;
              
              const onTimeOrders = clientEvents.filter(e => {
                const eventDate = new Date(e.date);
                const createdDate = new Date(e.created_date);
                const daysDiff = (eventDate - createdDate) / (1000 * 60 * 60 * 24);
                return daysDiff >= 3;
              }).length;
              const onTimeRate = totalOrders > 0 ? ((onTimeOrders / totalOrders) * 100).toFixed(0) : 0;
              
              // Calculate grade based on metrics
              const getClientGrade = () => {
                const metrics = [
                  parseFloat(fillRate),
                  parseFloat(onTimeRate),
                  100 - parseFloat(cancelationRate),
                  Math.min((totalOrders / 10) * 100, 100)
                ];
                const avgScore = metrics.reduce((a, b) => a + b, 0) / metrics.length;
                if (avgScore >= 90) return 'A+';
                if (avgScore >= 85) return 'A';
                if (avgScore >= 80) return 'A-';
                if (avgScore >= 75) return 'B+';
                if (avgScore >= 70) return 'B';
                return 'C';
              };
              
              const clientGrade = getClientGrade();
              const gradeColor = clientGrade.startsWith('A') ? 'bg-green-500' : clientGrade.startsWith('B') ? 'bg-blue-500' : 'bg-orange-500';

              // Calculate rapid orders (less than 3 days notice)
              const rapidOrders = clientEvents.filter(e => {
                const eventDate = new Date(e.date);
                const createdDate = new Date(e.created_date);
                const daysDiff = (eventDate - createdDate) / (1000 * 60 * 60 * 24);
                return daysDiff < 3;
              }).length;

              // Get most requested position
              const roleCount = {};
              clientEvents.forEach(e => {
                if (e.shifts) {
                  e.shifts.forEach(shift => {
                    if (shift.roles) {
                      shift.roles.forEach(role => {
                        const roleName = role.role || 'Staff';
                        roleCount[roleName] = (roleCount[roleName] || 0) + (role.count || 1);
                      });
                    }
                  });
                }
              });
              const mainPosition = Object.keys(roleCount).length > 0 
                ? Object.keys(roleCount).reduce((a, b) => roleCount[a] > roleCount[b] ? a : b)
                : 'Line Cook';

              // Check if business is using KROW (based on having platform integration or active usage)
              const isUsingKROW = firstBusiness?.notes?.toLowerCase().includes('krow') || 
                                 totalOrders > 5 || 
                                 Math.random() > 0.5; // Randomize for demo - replace with actual logic

              // Calculate last order date
              const lastOrderDate = clientEvents.length > 0 
                ? clientEvents.reduce((latest, event) => {
                    const eventDate = new Date(event.date || event.created_date);
                    return eventDate > latest ? eventDate : latest;
                  }, new Date(0)).toISOString()
                : null;

              const cardData = {
                companyName: company.company_name,
                logo: firstBusiness?.company_logo,
                sector: company.sector,
                monthlySpend: monthlySpend,
                totalStaff: totalStaffRequested,
                location: firstBusiness?.city || 'Bay Area',
                serviceType: firstBusiness?.service_specialty || 'Full Service Events',
                phone: company.primary_phone || '(555) 123-4567',
                email: company.primary_email || 'contact@company.com',
                technology: { isUsingKROW },
                performance: {
                  fillRate: fillRate,
                  onTimeRate: onTimeRate,
                  cancelRate: cancelationRate,
                  rapidOrders: rapidOrders,
                  mainPosition: mainPosition
                },
                gradeColor: gradeColor,
                clientGrade: clientGrade,
                isActive: firstBusiness?.is_active,
                lastOrderDate: lastOrderDate,
                rateCard: firstBusiness?.rate_card,
                businessId: company.hubs[0]?.id
              };

              return (
                <BusinessCard
                  key={company.company_name}
                  company={cardData}
                  metrics={{ totalOrders, hubs: company.hubs.length, activeMembers }}
                  isListView={viewMode === "list"}
                  onView={() => navigate(createPageUrl(`EditBusiness?id=${company.hubs[0]?.id}`))}
                  onEdit={() => navigate(createPageUrl(`EditBusiness?id=${company.hubs[0]?.id}`))}
                />
              );
            })}
          </div>
        ) : (
          <div className="text-center py-16 bg-white rounded-xl border border-slate-200">
            <Building2 className="w-16 h-16 mx-auto text-slate-300 mb-4" />
            <h3 className="text-xl font-semibold text-slate-900 mb-2">
              {searchTerm ? "No businesses found" : "No business clients yet"}
            </h3>
            <p className="text-slate-600 mb-6">
              {searchTerm ? "Try adjusting your search" : "Get started by adding your first business"}
            </p>
            {canAddBusiness && !searchTerm && (
              <Button 
                onClick={() => setCreateModalOpen(true)}
                className="bg-gradient-to-r from-[#0A39DF] to-[#1C323E] hover:from-[#0A39DF]/90 hover:to-[#1C323E]/90 text-white"
              >
                <Plus className="w-4 h-4 mr-2" />
                Add First Business
              </Button>
            )}
          </div>
        )}
      </div>
      {/* Create Business Modal */}
      <CreateBusinessModal
        open={createModalOpen}
        onOpenChange={setCreateModalOpen}
        onSubmit={handleCreateBusiness}
        isSubmitting={createBusinessMutation.isPending}
      />
    </div>
  );
}