import React from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { ArrowLeft, Save, Loader2, Users, MapPin, Star, Ban, Briefcase, Settings, Edit2, Trash2, UserMinus, UserPlus, Mail, Phone, Eye, DollarSign, Lock, Unlock, Grid3x3, List } from "lucide-react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import ERPSettingsTab from "../components/business/ERPSettingsTab";

const RATE_CARDS = {
  "Google": {
    "Banquet Captain": 34.02, "Barback": 31.79, "Barista": 32.53, "Busser": 27.62, "BW Bartender": 32.53,
    "Cashier/Standworker": 28.10, "Cook": 35.49, "Dinning Attendant": 28.83, "Dishwasher/ Steward": 28.10,
    "Executive Chef": 51.76, "FOH Cafe Attendant": 29.57, "Full Bartender": 36.97, "Grill Cook": 35.49,
    "Host/Hostess/Greeter": 29.57, "Internal Support": 36.57, "Lead Cook": 45.76, "Line Cook": 35.49,
    "Premium Server": 36.97, "Prep Cook": 29.57, "Receiver": 28.10, "Server": 30.22, "Sous Chef": 44.36,
    "Warehouse Worker": 28.10, "Baker": 35.59, "Janitor": 28.10, "Mixologist": 47.70, "Utilities": 28.10,
    "Scullery": 32.91, "Runner": 27.62, "Pantry Cook": 35.49, "Supervisor": 42.02, "Steward": 32.91, "Steward Supervisor": 34.10
  },
  "Bay Area Compass": {
    "Banquet Captain": 41.71, "Barback": 36.10, "Barista": 38.92, "Busser": 35.71, "BW Bartender": 38.92,
    "Cashier/Standworker": 36.10, "Cook": 42.13, "Dinning Attendant": 37.31, "Dishwasher/ Steward": 35.13,
    "Executive Chef": 72.19, "FOH Cafe Attendant": 37.31, "Full Bartender": 43.73, "Grill Cook": 42.13,
    "Host/Hostess/Greeter": 37.70, "Internal Support": 37.31, "Lead Cook": 46.57, "Line Cook": 42.13,
    "Premium Server": 44.12, "Prep Cook": 36.90, "Receiver": 35.71, "Server": 37.31, "Sous Chef": 56.15,
    "Warehouse Worker": 36.10, "Baker": 42.13, "Janitor": 35.13, "Mixologist": 56.15, "Utilities": 35.13,
    "Scullery": 36.10, "Runner": 35.71, "Pantry Cook": 42.13, "Supervisor": 46.84, "Steward": 36.10, "Steward Supervisor": 38.38
  },
  "LA Compass": {
    "Banquet Captain": 40.30, "Barback": 35.42, "Barista": 39.60, "Busser": 34.18, "BW Bartender": 35.65,
    "Cashier/Standworker": 34.26, "Cook": 37.20, "Dinning Attendant": 35.65, "Dishwasher/ Steward": 34.10,
    "Executive Chef": 60.53, "FOH Cafe Attendant": 35.65, "Full Bartender": 39.60, "Grill Cook": 37.20,
    "Host/Hostess/Greeter": 35.65, "Internal Support": 36.57, "Lead Cook": 39.60, "Line Cook": 37.20,
    "Premium Server": 40.30, "Prep Cook": 35.43, "Receiver": 34.65, "Server": 34.65, "Sous Chef": 52.78,
    "Warehouse Worker": 35.50, "Baker": 37.20, "Janitor": 34.10, "Mixologist": 62.00, "Utilities": 34.10,
    "Scullery": 34.10, "Runner": 34.18, "Pantry Cook": 37.20, "Supervisor": 39.60, "Steward": 34.10, "Steward Supervisor": 36.10
  },
  "FoodBuy": {
    "Banquet Captain": 47.76, "Barback": 36.13, "Barista": 43.11, "Busser": 39.23, "BW Bartender": 41.15,
    "Cashier/Standworker": 38.05, "Cook": 44.58, "Dinning Attendant": 41.56, "Dishwasher/ Steward": 38.38,
    "Executive Chef": 70.60, "FOH Cafe Attendant": 41.56, "Full Bartender": 47.76, "Grill Cook": 44.58,
    "Host/Hostess/Greeter": 41.56, "Internal Support": 41.56, "Lead Cook": 52.00, "Line Cook": 44.58,
    "Premium Server": 47.76, "Prep Cook": 37.98, "Receiver": 40.01, "Server": 41.56, "Sous Chef": 59.75,
    "Warehouse Worker": 41.15, "Baker": 44.58, "Janitor": 38.38, "Mixologist": 71.30, "Utilities": 38.38,
    "Scullery": 38.38, "Runner": 39.23, "Pantry Cook": 44.58, "Supervisor": 47.76, "Steward": 38.38, "Steward Supervisor": 41.15
  },
  "Aramark": {
    "Banquet Captain": 46.37, "Barback": 33.11, "Barista": 36.87, "Busser": 33.11, "BW Bartender": 36.12,
    "Cashier/Standworker": 33.11, "Cook": 36.12, "Dinning Attendant": 34.62, "Dishwasher/ Steward": 33.11,
    "Executive Chef": 76.76, "FOH Cafe Attendant": 34.62, "Full Bartender": 45.15, "Grill Cook": 36.12,
    "Host/Hostess/Greeter": 34.62, "Internal Support": 37.63, "Lead Cook": 52.68, "Line Cook": 36.12,
    "Premium Server": 40.64, "Prep Cook": 34.62, "Receiver": 34.62, "Server": 34.62, "Sous Chef": 60.20,
    "Warehouse Worker": 34.62, "Baker": 45.15, "Janitor": 34.62, "Mixologist": 60.20, "Utilities": 33.11,
    "Scullery": 33.11, "Runner": 33.11, "Pantry Cook": 36.12, "Supervisor": 45.15, "Steward": 33.11, "Steward Supervisor": 34.10
  },
  "Promotion": {
    "Banquet Captain": 40.00, "Barback": 34.00, "Barista": 36.00, "Busser": 34.00, "BW Bartender": 36.00,
    "Cashier/Standworker": 34.00, "Cook": 36.00, "Dinning Attendant": 36.00, "Dishwasher/ Steward": 30.00,
    "Executive Chef": 51.00, "FOH Cafe Attendant": 36.00, "Full Bartender": 40.00, "Grill Cook": 36.00,
    "Host/Hostess/Greeter": 34.00, "Internal Support": 36.00, "Lead Cook": 45.00, "Line Cook": 36.00,
    "Premium Server": 38.00, "Prep Cook": 32.00, "Receiver": 34.00, "Server": 34.00, "Sous Chef": 44.00,
    "Warehouse Worker": 34.00, "Baker": 36.00, "Janitor": 32.00, "Mixologist": 51.00, "Utilities": 30.00,
    "Scullery": 34.00, "Runner": 34.00, "Pantry Cook": 36.00, "Supervisor": 40.00, "Steward": 34.00, "Steward Supervisor": 36.10
  },
  "Convention Center": {
    "Banquet Captain": 40.00, "Barback": 34.00, "Barista": 36.00, "Busser": 34.00, "BW Bartender": 36.00,
    "Cashier/Standworker": 34.00, "Cook": 36.00, "Dinning Attendant": 36.00, "Dishwasher/ Steward": 30.00,
    "Executive Chef": 51.00, "FOH Cafe Attendant": 36.00, "Full Bartender": 38.00, "Grill Cook": 36.00,
    "Host/Hostess/Greeter": 34.00, "Internal Support": 36.00, "Lead Cook": 45.00, "Line Cook": 36.00,
    "Premium Server": 38.00, "Prep Cook": 34.00, "Receiver": 34.00, "Server": 34.00, "Sous Chef": 44.00,
    "Warehouse Worker": 34.00, "Baker": 36.00, "Janitor": 32.00, "Mixologist": 51.00, "Utilities": 30.00,
    "Scullery": 34.00, "Runner": 34.00, "Pantry Cook": 36.00, "Supervisor": 40.00, "Steward": 34.00, "Steward Supervisor": 38.38
  }
};

function RateBreakdownTable({ rateCard }) {
  const rates = RATE_CARDS[rateCard] || {};
  const positions = Object.entries(rates).sort((a, b) => a[0].localeCompare(b[0]));

  if (!rateCard || positions.length === 0) {
    return (
      <div className="p-12 text-center">
        <Briefcase className="w-16 h-16 mx-auto mb-4 text-slate-300" />
        <h3 className="text-lg font-bold text-slate-900 mb-2">No Rate Card Assigned</h3>
        <p className="text-slate-600">Contact admin to assign a rate card</p>
      </div>
    );
  }

  return (
    <table className="w-full">
      <thead className="bg-slate-50 border-b border-slate-200">
        <tr>
          <th className="text-left py-3 px-6 font-semibold text-xs text-slate-600 uppercase">Position</th>
          <th className="text-right py-3 px-6 font-semibold text-xs text-slate-600 uppercase">Hourly Rate</th>
        </tr>
      </thead>
      <tbody>
        {positions.map(([position, rate], idx) => (
          <tr key={position} className={`border-b border-slate-100 ${idx % 2 === 0 ? 'bg-white' : 'bg-slate-50/30'}`}>
            <td className="py-3 px-6">
              <span className="font-medium text-slate-900">{position}</span>
            </td>
            <td className="py-3 px-6 text-right">
              <span className="font-bold text-blue-600">${rate.toFixed(2)}</span>
              <span className="text-xs text-slate-500 ml-1">/hr</span>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function TeamTabContent({ allTeamMembers }) {
  const [viewMode, setViewMode] = React.useState("grid");

  return (
    <div className="space-y-4">
      {/* View Toggle */}
      <div className="flex items-center justify-between">
        <p className="text-sm text-slate-600">{allTeamMembers.length} team member{allTeamMembers.length !== 1 ? 's' : ''}</p>
        <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>

      {allTeamMembers.length > 0 ? (
        viewMode === "grid" ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {allTeamMembers.map((member) => (
              <Card key={member.member_id} className={`${member.is_active ? 'border-2 border-blue-200' : 'border border-slate-200 opacity-70'}`}>
                <CardContent className="p-6">
                  <div className="flex items-start gap-3 mb-4">
                    <div className={`w-16 h-16 ${member.is_active ? 'bg-blue-600' : 'bg-slate-400'} rounded-2xl flex items-center justify-center text-white font-bold text-xl shadow-md flex-shrink-0`}>
                      {member.member_name?.split(' ').map(n => n[0]).join('').toUpperCase() || 'U'}
                    </div>
                    <div className="flex-1 min-w-0">
                      <h4 className="font-bold text-slate-900 text-base mb-0.5">{member.member_name}</h4>
                      <p className="text-sm text-slate-600 mb-1">{member.role || 'Member'}</p>
                      <p className="text-xs text-slate-500">{member.title || 'Team Member'}</p>
                    </div>
                  </div>

                  <div className="space-y-2 mb-4">
                    {member.email && (
                      <div className="flex items-center gap-2 text-sm text-slate-700">
                        <Mail className="w-4 h-4 text-slate-400 flex-shrink-0" />
                        <span className="truncate">{member.email}</span>
                      </div>
                    )}
                    {member.phone && (
                      <div className="flex items-center gap-2 text-sm text-slate-700">
                        <Phone className="w-4 h-4 text-slate-400 flex-shrink-0" />
                        <span className="truncate">{member.phone}</span>
                      </div>
                    )}
                  </div>

                  <div className="flex flex-wrap gap-2">
                    {member.department && (
                      <Badge className="bg-blue-100 text-blue-700 text-xs border-0">
                        {member.department}
                      </Badge>
                    )}
                    {member.hub && (
                      <Badge className="bg-purple-100 text-purple-700 text-xs border-0">
                        <MapPin className="w-3 h-3 mr-1" />
                        {member.hub}
                      </Badge>
                    )}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        ) : (
          <Card className="border-slate-200">
            <CardContent className="p-0">
              <table className="w-full">
                <thead className="bg-slate-50 border-b border-slate-200">
                  <tr>
                    <th className="text-left py-3 px-6 font-semibold text-xs text-slate-600 uppercase">Name</th>
                    <th className="text-left py-3 px-6 font-semibold text-xs text-slate-600 uppercase">Role</th>
                    <th className="text-left py-3 px-6 font-semibold text-xs text-slate-600 uppercase">Contact</th>
                    <th className="text-left py-3 px-6 font-semibold text-xs text-slate-600 uppercase">Hub</th>
                    <th className="text-center py-3 px-6 font-semibold text-xs text-slate-600 uppercase">Status</th>
                  </tr>
                </thead>
                <tbody>
                  {allTeamMembers.map((member, idx) => (
                    <tr key={member.member_id} className={`border-b border-slate-100 hover:bg-slate-50 transition-colors ${idx % 2 === 0 ? 'bg-white' : 'bg-slate-50/30'}`}>
                      <td className="py-4 px-6">
                        <div className="flex items-center gap-3">
                          <div className={`w-10 h-10 ${member.is_active ? 'bg-blue-600' : 'bg-slate-400'} rounded-full flex items-center justify-center text-white font-bold text-sm`}>
                            {member.member_name?.split(' ').map(n => n[0]).join('').toUpperCase() || 'U'}
                          </div>
                          <span className="font-medium text-slate-900">{member.member_name}</span>
                        </div>
                      </td>
                      <td className="py-4 px-6">
                        <div>
                          <p className="font-medium text-slate-900 text-sm">{member.role || 'Member'}</p>
                          <p className="text-xs text-slate-500">{member.title || 'Team Member'}</p>
                        </div>
                      </td>
                      <td className="py-4 px-6">
                        <div className="text-sm">
                          {member.email && <p className="text-slate-700 flex items-center gap-1"><Mail className="w-3 h-3 text-slate-400" />{member.email}</p>}
                          {member.phone && <p className="text-slate-500 flex items-center gap-1 mt-0.5"><Phone className="w-3 h-3 text-slate-400" />{member.phone}</p>}
                        </div>
                      </td>
                      <td className="py-4 px-6">
                        {member.hub ? (
                          <Badge className="bg-purple-100 text-purple-700 text-xs border-0">
                            <MapPin className="w-3 h-3 mr-1" />
                            {member.hub}
                          </Badge>
                        ) : (
                          <span className="text-slate-400 text-sm">—</span>
                        )}
                      </td>
                      <td className="py-4 px-6 text-center">
                        <Badge className={member.is_active !== false ? "bg-green-100 text-green-700" : "bg-slate-200 text-slate-600"}>
                          {member.is_active !== false ? 'Active' : 'Inactive'}
                        </Badge>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </CardContent>
          </Card>
        )
      ) : (
        <Card>
          <CardContent className="p-12 text-center">
            <Users className="w-16 h-16 mx-auto mb-4 text-slate-300" />
            <h3 className="text-lg font-bold text-slate-900 mb-2">No Team Members</h3>
            <p className="text-slate-600">This business doesn't have any team members yet</p>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

function ServicesTab({ business, businessId, updateBusinessMutation }) {
  const [isUnlocked, setIsUnlocked] = React.useState(false);
  const [selectedCard, setSelectedCard] = React.useState(business?.rate_card || '');

  React.useEffect(() => {
    setSelectedCard(business?.rate_card || '');
  }, [business?.rate_card]);

  const handleSaveRateCard = () => {
    updateBusinessMutation.mutate({
      id: businessId,
      data: { rate_card: selectedCard }
    });
    setIsUnlocked(false);
  };

  const rateCardOptions = Object.keys(RATE_CARDS);

  return (
    <div className="space-y-6">
      {/* Rate Card Header */}
      <Card className="border-slate-200 shadow-lg">
        <CardContent className="p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-4">
              <div className={`w-14 h-14 ${isUnlocked ? 'bg-amber-500' : 'bg-blue-600'} rounded-2xl flex items-center justify-center shadow-lg transition-colors`}>
                <DollarSign className="w-7 h-7 text-white" />
              </div>
              <div>
                <p className="text-sm font-semibold text-slate-500 mb-1">Assigned Rate Card</p>
                {isUnlocked ? (
                  <Select value={selectedCard} onValueChange={setSelectedCard}>
                    <SelectTrigger className="w-[240px] border-amber-300 bg-amber-50">
                      <SelectValue placeholder="Select rate card" />
                    </SelectTrigger>
                    <SelectContent>
                      {rateCardOptions.map(card => (
                        <SelectItem key={card} value={card}>{card}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                ) : (
                  <p className="text-2xl font-bold text-slate-900">{business?.rate_card || 'Not Assigned'}</p>
                )}
              </div>
            </div>
            <div className="flex items-center gap-2">
              {isUnlocked ? (
                <>
                  <Button 
                    variant="outline" 
                    size="sm"
                    onClick={() => { setIsUnlocked(false); setSelectedCard(business?.rate_card || ''); }}
                    className="border-slate-300"
                  >
                    Cancel
                  </Button>
                  <Button 
                    size="sm"
                    onClick={handleSaveRateCard}
                    disabled={updateBusinessMutation.isPending || selectedCard === business?.rate_card}
                    className="bg-green-600 hover:bg-green-700 text-white"
                  >
                    {updateBusinessMutation.isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4 mr-1" />}
                    Save
                  </Button>
                </>
              ) : (
                <Button 
                  variant="outline" 
                  size="sm"
                  onClick={() => setIsUnlocked(true)}
                  className="border-amber-300 text-amber-700 hover:bg-amber-50"
                >
                  <Unlock className="w-4 h-4 mr-1" />
                  Unlock to Change
                </Button>
              )}
              <Badge className={`${isUnlocked ? 'bg-amber-100 text-amber-700 border-amber-200' : 'bg-green-100 text-green-700 border-green-200'} px-3 py-1`}>
                {isUnlocked ? <><Unlock className="w-3 h-3 mr-1 inline" />Unlocked</> : <><Lock className="w-3 h-3 mr-1 inline" />Locked</>}
              </Badge>
            </div>
          </div>
          {isUnlocked && (
            <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 text-sm text-amber-800">
              Select a new rate card and click Save to update pricing for this business.
            </div>
          )}
        </CardContent>
      </Card>

      {/* Rate Breakdown Table */}
      <Card className="border-slate-200 shadow-lg">
        <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b border-slate-100">
          <CardTitle className="text-slate-900 flex items-center justify-between">
            <span>Rate Breakdown</span>
            <span className="text-sm font-normal text-slate-500">
              {isUnlocked && selectedCard !== business?.rate_card ? `Preview: ${selectedCard}` : business?.rate_card}
            </span>
          </CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <RateBreakdownTable rateCard={isUnlocked ? selectedCard : business?.rate_card} />
        </CardContent>
      </Card>
    </div>
  );
}

export default function EditBusiness() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const urlParams = new URLSearchParams(window.location.search);
  const businessId = urlParams.get('id');
  const defaultTab = urlParams.get('tab') || 'overview';

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

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

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

  const business = allBusinesses.find(b => b.id === businessId);

  // Get company name without hub suffix
  let companyName = business?.business_name || '';
  const dashIndex = companyName.indexOf(' - ');
  if (dashIndex > 0) {
    companyName = companyName.substring(0, dashIndex).trim();
  }

  // Find all businesses for this company
  const companyBusinesses = allBusinesses.filter(b => 
    b.business_name === companyName || 
    b.business_name.startsWith(companyName + ' - ')
  );

  // Extract hubs first
      const hubs = companyBusinesses.map(bus => ({
        id: bus.id,
        hub_name: bus.business_name,
        contact_name: bus.contact_name,
        email: bus.email,
        phone: bus.phone,
        address: bus.address,
        city: bus.city,
        notes: bus.notes
      }));

      // Collect all team members
      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);
            }
          });
        }
      });

      // Add hub contacts as team members
      hubs.forEach(hub => {
        if (hub.contact_name) {
          // Check if this contact is already in team members (by name if no email, or by email)
          const alreadyExists = teamMembers.some(m => 
            (hub.email && m.email === hub.email) || 
            (!hub.email && m.member_name === hub.contact_name)
          );
          
          if (!alreadyExists) {
            teamMembers.push({
              member_id: `hub-${hub.id}`,
              member_name: hub.contact_name,
              email: hub.email || '',
              phone: hub.phone,
              role: 'Hub Manager',
              title: 'Hub Manager',
              hub: hub.hub_name,
              is_active: true
            });
          }
        }
      });

  // teamMembers already includes hub contacts from above
      const allTeamMembers = teamMembers;

  // Calculate metrics
  const clientEvents = allEvents.filter(e => 
    e.business_name === companyName || 
    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 === companyName ||
    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 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;

  const [formData, setFormData] = React.useState({
    business_name: "",
    company_logo: "",
    contact_name: "",
    email: "",
    phone: "",
    address: "",
    notes: ""
  });

  React.useEffect(() => {
    if (business) {
      setFormData({
        business_name: business.business_name || "",
        company_logo: business.company_logo || "",
        contact_name: business.contact_name || "",
        email: business.email || "",
        phone: business.phone || "",
        address: business.address || "",
        notes: business.notes || ""
      });
    }
  }, [business]);

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

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

  const handleSubmit = (e) => {
    e.preventDefault();
    updateBusinessMutation.mutate({ id: businessId, data: formData });
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  if (!business) {
    return (
      <div className="p-8 text-center">
        <h2 className="text-2xl font-bold text-slate-900 mb-4">Business Not Found</h2>
        <Button onClick={() => navigate(createPageUrl("Business"))}>
          Back to Businesses
        </Button>
      </div>
    );
  }

  return (
    <div className="p-4 md:p-8">
      <div className="max-w-7xl mx-auto">
        <div className="mb-8">
          <Button
            variant="ghost"
            onClick={() => navigate(createPageUrl("Business"))}
            className="mb-4 hover:bg-slate-100"
          >
            <ArrowLeft className="w-4 h-4 mr-2" />
            Back to Businesses
          </Button>
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl md:text-4xl font-bold text-slate-900 mb-2">{companyName}</h1>
              <p className="text-slate-600">{hubs.length} hub locations • {allTeamMembers.length} team members</p>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3">
              <div className="bg-blue-50 rounded-xl p-4 text-center">
                <p className="text-xs text-blue-700 font-semibold mb-1">Monthly Sales</p>
                <p className="text-2xl font-bold text-blue-900">${(monthlySpend / 1000).toFixed(0)}k</p>
              </div>
              <div className="bg-slate-50 rounded-xl p-4 text-center">
                <p className="text-xs text-slate-700 font-semibold mb-1">Total Orders</p>
                <p className="text-2xl font-bold text-slate-900">{totalOrders}</p>
              </div>
              <div className="bg-green-50 rounded-xl p-4 text-center">
                <p className="text-xs text-green-700 font-semibold mb-1">On-Time Rate</p>
                <p className="text-2xl font-bold text-green-900">{onTimeRate}%</p>
              </div>
              <div className="bg-orange-50 rounded-xl p-4 text-center">
                <p className="text-xs text-orange-700 font-semibold mb-1">Cancellations</p>
                <p className="text-2xl font-bold text-orange-900">{cancelationRate}%</p>
              </div>
              <div className="bg-purple-50 rounded-xl p-4 text-center">
                <p className="text-xs text-purple-700 font-semibold mb-1">Completed</p>
                <p className="text-2xl font-bold text-purple-900">{completedOrders}</p>
              </div>
            </div>
          </div>
        </div>

        <Tabs defaultValue={defaultTab} className="space-y-8">
          <div className="bg-white rounded-2xl shadow-lg border border-slate-200 p-2">
            <TabsList className="bg-transparent w-full grid grid-cols-7 gap-2">
              <TabsTrigger 
                value="overview" 
                className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl font-semibold text-sm text-slate-600 hover:bg-slate-50 transition-all data-[state=active]:bg-gradient-to-br data-[state=active]:from-blue-600 data-[state=active]:to-blue-700 data-[state=active]:text-white data-[state=active]:shadow-lg data-[state=active]:shadow-blue-200"
              >
                <Briefcase className="w-4 h-4" />
                <span className="hidden lg:inline">Overview</span>
              </TabsTrigger>

              <TabsTrigger 
                value="team" 
                className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl font-semibold text-sm text-slate-600 hover:bg-slate-50 transition-all data-[state=active]:bg-gradient-to-br data-[state=active]:from-blue-600 data-[state=active]:to-blue-700 data-[state=active]:text-white data-[state=active]:shadow-lg data-[state=active]:shadow-blue-200"
              >
                <Users className="w-4 h-4" />
                <span className="hidden lg:inline">Team</span>
                <span className="inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 text-xs font-bold rounded-full bg-slate-200 text-slate-700 data-[state=active]:bg-white/20 data-[state=active]:text-white">
                  {allTeamMembers.length}
                </span>
              </TabsTrigger>

              <TabsTrigger 
                value="hubs" 
                className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl font-semibold text-sm text-slate-600 hover:bg-slate-50 transition-all data-[state=active]:bg-gradient-to-br data-[state=active]:from-blue-600 data-[state=active]:to-blue-700 data-[state=active]:text-white data-[state=active]:shadow-lg data-[state=active]:shadow-blue-200"
              >
                <MapPin className="w-4 h-4" />
                <span className="hidden lg:inline">Hubs</span>
                <span className="inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 text-xs font-bold rounded-full bg-slate-200 text-slate-700 data-[state=active]:bg-white/20 data-[state=active]:text-white">
                  {hubs.length}
                </span>
              </TabsTrigger>

              <TabsTrigger 
                value="services" 
                className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl font-semibold text-sm text-slate-600 hover:bg-slate-50 transition-all data-[state=active]:bg-gradient-to-br data-[state=active]:from-blue-600 data-[state=active]:to-blue-700 data-[state=active]:text-white data-[state=active]:shadow-lg data-[state=active]:shadow-blue-200"
              >
                <Briefcase className="w-4 h-4" />
                <span className="hidden lg:inline">Services</span>
              </TabsTrigger>

              <TabsTrigger 
                value="favorites" 
                className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl font-semibold text-sm text-slate-600 hover:bg-slate-50 transition-all data-[state=active]:bg-gradient-to-br data-[state=active]:from-yellow-500 data-[state=active]:to-amber-600 data-[state=active]:text-white data-[state=active]:shadow-lg data-[state=active]:shadow-yellow-200"
              >
                <Star className="w-4 h-4" />
                <span className="hidden lg:inline">Favorites</span>
                <span className="inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 text-xs font-bold rounded-full bg-slate-200 text-slate-700 data-[state=active]:bg-white/20 data-[state=active]:text-white">
                  {business?.favorite_staff?.length || 0}
                </span>
              </TabsTrigger>

              <TabsTrigger 
                value="blocked" 
                className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl font-semibold text-sm text-slate-600 hover:bg-slate-50 transition-all data-[state=active]:bg-gradient-to-br data-[state=active]:from-red-500 data-[state=active]:to-red-600 data-[state=active]:text-white data-[state=active]:shadow-lg data-[state=active]:shadow-red-200"
              >
                <Ban className="w-4 h-4" />
                <span className="hidden lg:inline">Blocked</span>
                <span className="inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 text-xs font-bold rounded-full bg-slate-200 text-slate-700 data-[state=active]:bg-white/20 data-[state=active]:text-white">
                  {business?.blocked_staff?.length || 0}
                </span>
              </TabsTrigger>

              <TabsTrigger 
                value="erp" 
                className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl font-semibold text-sm text-slate-600 hover:bg-slate-50 transition-all data-[state=active]:bg-gradient-to-br data-[state=active]:from-purple-600 data-[state=active]:to-purple-700 data-[state=active]:text-white data-[state=active]:shadow-lg data-[state=active]:shadow-purple-200"
              >
                <Briefcase className="w-4 h-4" />
                <span className="hidden lg:inline">ERP/EDI</span>
              </TabsTrigger>

              <TabsTrigger 
                value="settings" 
                className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl font-semibold text-sm text-slate-600 hover:bg-slate-50 transition-all data-[state=active]:bg-gradient-to-br data-[state=active]:from-slate-700 data-[state=active]:to-slate-800 data-[state=active]:text-white data-[state=active]:shadow-lg data-[state=active]:shadow-slate-300"
              >
                <Settings className="w-4 h-4" />
                <span className="hidden lg:inline">Settings</span>
              </TabsTrigger>
            </TabsList>
          </div>

          {/* Overview Tab */}
          <TabsContent value="overview">
            <form onSubmit={handleSubmit}>
              <Card className="border-slate-200 shadow-lg">
                <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b border-slate-100">
                  <CardTitle className="text-slate-900">Business Information</CardTitle>
                </CardHeader>
                <CardContent className="p-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2 md:col-span-2">
                  <Label htmlFor="business_name" className="text-slate-700 font-medium">Business Name *</Label>
                  <Input
                    id="business_name"
                    value={formData.business_name}
                    onChange={(e) => handleChange('business_name', e.target.value)}
                    required
                    className="border-slate-200"
                    placeholder="Enter business name"
                  />
                </div>

                <div className="space-y-2 md:col-span-2">
                  <Label htmlFor="company_logo" className="text-slate-700 font-medium">Company Logo URL</Label>
                  <Input
                    id="company_logo"
                    value={formData.company_logo}
                    onChange={(e) => handleChange('company_logo', e.target.value)}
                    className="border-slate-200"
                    placeholder="https://example.com/logo.png"
                  />
                  <p className="text-xs text-slate-500">Optional: URL to company logo image</p>
                  {formData.company_logo && (
                    <div className="mt-2 p-3 bg-slate-50 rounded-lg border border-slate-200">
                      <p className="text-xs text-slate-600 mb-2">Preview:</p>
                      <img 
                        src={formData.company_logo} 
                        alt="Company logo preview" 
                        className="w-16 h-16 object-contain"
                        onError={(e) => {
                          e.target.style.display = 'none';
                          e.target.parentElement.innerHTML = '<p class="text-xs text-red-500">Failed to load image</p>';
                        }}
                      />
                    </div>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="contact_name" className="text-slate-700 font-medium">Contact Person</Label>
                  <Input
                    id="contact_name"
                    value={formData.contact_name}
                    onChange={(e) => handleChange('contact_name', e.target.value)}
                    className="border-slate-200"
                    placeholder="Primary contact name"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="phone" className="text-slate-700 font-medium">Phone Number</Label>
                  <Input
                    id="phone"
                    type="tel"
                    value={formData.phone}
                    onChange={(e) => handleChange('phone', e.target.value)}
                    className="border-slate-200"
                    placeholder="(555) 123-4567"
                  />
                </div>

                <div className="space-y-2 md:col-span-2">
                  <Label htmlFor="email" className="text-slate-700 font-medium">Email</Label>
                  <Input
                    id="email"
                    type="email"
                    value={formData.email}
                    onChange={(e) => handleChange('email', e.target.value)}
                    className="border-slate-200"
                    placeholder="business@example.com"
                  />
                </div>

                <div className="space-y-2 md:col-span-2">
                  <Label htmlFor="address" className="text-slate-700 font-medium">Address</Label>
                  <Textarea
                    id="address"
                    value={formData.address}
                    onChange={(e) => handleChange('address', e.target.value)}
                    rows={3}
                    className="border-slate-200"
                    placeholder="Full address including street, city, state, and zip"
                  />
                </div>

                <div className="space-y-2 md:col-span-2">
                  <Label htmlFor="notes" className="text-slate-700 font-medium">Notes</Label>
                  <Textarea
                    id="notes"
                    value={formData.notes}
                    onChange={(e) => handleChange('notes', e.target.value)}
                    rows={4}
                    className="border-slate-200"
                    placeholder="Additional notes about this business..."
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          <div className="flex justify-end gap-3 mt-6">
            <Button
              type="button"
              variant="outline"
              onClick={() => navigate(createPageUrl("Business"))}
              className="border-slate-300"
            >
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={updateBusinessMutation.isPending}
              className="bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white shadow-lg"
            >
              {updateBusinessMutation.isPending ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Updating...
                </>
              ) : (
                <>
                  <Save className="w-4 h-4 mr-2" />
                  Update Business
                </>
              )}
            </Button>
          </div>
        </form>
      </TabsContent>

      {/* Team Tab */}
      <TabsContent value="team">
        <TeamTabContent allTeamMembers={allTeamMembers} />
      </TabsContent>

      {/* Hubs Tab */}
      <TabsContent value="hubs">
        <Card>
          <CardContent className="p-0">
            <table className="w-full">
              <thead className="bg-slate-50 border-b border-slate-200">
                <tr>
                  <th className="text-left py-3 px-6 font-semibold text-xs text-slate-600">Hub Name</th>
                  <th className="text-left py-3 px-6 font-semibold text-xs text-slate-600">Contact</th>
                  <th className="text-left py-3 px-6 font-semibold text-xs text-slate-600">Address</th>
                  <th className="text-left py-3 px-6 font-semibold text-xs text-slate-600">City</th>
                  <th className="text-center py-3 px-6 font-semibold text-xs text-slate-600">Actions</th>
                </tr>
              </thead>
              <tbody>
                {hubs.map((hub, idx) => (
                  <tr key={hub.id} className={`border-b border-slate-100 hover:bg-slate-50 transition-colors ${idx % 2 === 0 ? 'bg-white' : 'bg-slate-50/30'}`}>
                    <td className="py-4 px-6">
                      <div className="flex items-center gap-2">
                        <MapPin className="w-4 h-4 text-blue-500" />
                        <span className="font-medium text-sm text-slate-900">{hub.hub_name}</span>
                      </div>
                    </td>
                    <td className="py-4 px-6">
                      <div className="text-sm">
                        <p className="font-medium text-slate-900">{hub.contact_name || '—'}</p>
                        {hub.email && <p className="text-xs text-slate-500 flex items-center gap-1 mt-0.5"><Mail className="w-3 h-3" />{hub.email}</p>}
                        {hub.phone && <p className="text-xs text-slate-500 flex items-center gap-1 mt-0.5"><Phone className="w-3 h-3" />{hub.phone}</p>}
                      </div>
                    </td>
                    <td className="py-4 px-6">
                      <p className="text-sm text-slate-600">{hub.address || '—'}</p>
                    </td>
                    <td className="py-4 px-6">
                      <p className="text-sm text-slate-600">{hub.city || '—'}</p>
                    </td>
                    <td className="py-4 px-6">
                      <div className="flex items-center justify-center gap-2">
                        <Button variant="ghost" size="icon" className="text-slate-400 hover:text-blue-600 hover:bg-blue-50 h-8 w-8">
                          <Eye className="w-4 h-4" />
                        </Button>
                        <Button variant="ghost" size="icon" className="text-slate-400 hover:text-red-600 hover:bg-red-50 h-8 w-8">
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </CardContent>
        </Card>
      </TabsContent>

      {/* Services Tab */}
      <TabsContent value="services">
        <ServicesTab 
          business={business} 
          businessId={businessId} 
          updateBusinessMutation={updateBusinessMutation} 
        />
      </TabsContent>

      {/* Favorites Tab */}
      <TabsContent value="favorites">
        <div className="space-y-4">
          {business?.favorite_staff?.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {business.favorite_staff.map((fav) => (
                <Card key={fav.staff_id} className="border border-yellow-200">
                  <CardContent className="p-4">
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center gap-3">
                        <div className="w-12 h-12 bg-yellow-100 rounded-full flex items-center justify-center">
                          <Star className="w-6 h-6 text-yellow-600 fill-yellow-500" />
                        </div>
                        <div>
                          <p className="font-bold text-slate-900">{fav.staff_name}</p>
                          <p className="text-xs text-slate-500">{fav.position || 'Staff'}</p>
                        </div>
                      </div>
                      <Button variant="ghost" size="icon" className="text-slate-400 hover:text-red-600">
                        <UserMinus className="w-4 h-4" />
                      </Button>
                    </div>
                    <p className="text-xs text-slate-500">Added: {new Date(fav.added_date).toLocaleDateString()}</p>
                  </CardContent>
                </Card>
              ))}
            </div>
          ) : (
            <Card>
              <CardContent className="p-12 text-center">
                <Star className="w-16 h-16 mx-auto mb-4 text-slate-300" />
                <h3 className="text-lg font-bold text-slate-900 mb-2">No Favorite Staff</h3>
                <p className="text-slate-600 mb-4">Mark staff as favorites for quick access</p>
                <Button size="sm" className="bg-yellow-100 hover:bg-yellow-200 text-slate-800 border border-yellow-200">
                  <UserPlus className="w-4 h-4 mr-2" />Add Favorite
                </Button>
              </CardContent>
            </Card>
          )}
        </div>
      </TabsContent>

      {/* Blocked Tab */}
      <TabsContent value="blocked">
        <div className="space-y-4">
          {business?.blocked_staff?.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {business.blocked_staff.map((blocked) => (
                <Card key={blocked.staff_id} className="border border-red-200">
                  <CardContent className="p-4">
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center gap-3">
                        <div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center">
                          <Ban className="w-6 h-6 text-red-600" />
                        </div>
                        <div>
                          <p className="font-bold text-slate-900">{blocked.staff_name}</p>
                          <Badge className="bg-red-100 text-red-800 text-xs mt-1">Blocked</Badge>
                        </div>
                      </div>
                      <Button variant="ghost" size="icon" className="text-slate-400 hover:text-green-600">
                        <UserPlus className="w-4 h-4" />
                      </Button>
                    </div>
                    <p className="text-xs text-slate-600 mb-1"><strong>Reason:</strong> {blocked.reason}</p>
                    <p className="text-xs text-slate-500">Blocked: {new Date(blocked.blocked_date).toLocaleDateString()}</p>
                  </CardContent>
                </Card>
              ))}
            </div>
          ) : (
            <Card>
              <CardContent className="p-12 text-center">
                <Ban className="w-16 h-16 mx-auto mb-4 text-slate-300" />
                <h3 className="text-lg font-bold text-slate-900 mb-2">No Blocked Staff</h3>
                <p className="text-slate-600">Staff blocking helps maintain quality standards</p>
              </CardContent>
            </Card>
          )}
        </div>
      </TabsContent>

      {/* ERP/EDI Tab */}
      <TabsContent value="erp">
        <ERPSettingsTab 
          business={business} 
          onSave={(erpSettings) => {
            updateBusinessMutation.mutate({
              id: businessId,
              data: erpSettings
            });
          }}
          isSaving={updateBusinessMutation.isPending}
        />
      </TabsContent>

      {/* Settings Tab */}
      <TabsContent value="settings">
        <Card>
          <CardContent className="p-6">
            <h3 className="font-bold text-lg text-slate-900 mb-4">Business Settings</h3>
            <div className="space-y-6">
              <div>
                <h4 className="font-semibold text-slate-900 mb-3">General Settings</h4>
                <div className="space-y-4">
                  <div className="flex items-center justify-between p-4 bg-slate-50 rounded-lg">
                    <div>
                      <p className="font-medium text-slate-900">Client Active Status</p>
                      <p className="text-sm text-slate-500">Activate or deactivate this client</p>
                    </div>
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        checked={business?.is_active !== false}
                        onChange={(e) => {
                          updateBusinessMutation.mutate({
                            id: businessId,
                            data: { is_active: e.target.checked }
                          });
                        }}
                        className="sr-only peer"
                      />
                      <div className="w-14 h-7 bg-slate-300 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-0.5 after:left-[4px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-6 after:w-6 after:transition-all peer-checked:bg-blue-600"></div>
                    </label>
                  </div>
                  <div className="flex items-center justify-between p-4 bg-slate-50 rounded-lg">
                    <div>
                      <p className="font-medium text-slate-900">Status</p>
                      <p className="text-sm text-slate-500">Current business status</p>
                    </div>
                    <Badge className={business?.is_active !== false ? "bg-green-100 text-green-700" : "bg-slate-300 text-slate-700"}>
                      {business?.is_active !== false ? 'Active' : 'Inactive'}
                    </Badge>
                  </div>
                  <div className="flex items-center justify-between p-4 bg-slate-50 rounded-lg">
                    <div>
                      <p className="font-medium text-slate-900">Last Order Date</p>
                      <p className="text-sm text-slate-500">Most recent order placed</p>
                    </div>
                    <span className="font-semibold text-slate-900">
                      {business?.last_order_date 
                        ? new Date(business.last_order_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
                        : 'No orders yet'}
                    </span>
                  </div>
                  <div className="flex items-center justify-between p-4 bg-slate-50 rounded-lg">
                    <div>
                      <p className="font-medium text-slate-900">Rate Group</p>
                      <p className="text-sm text-slate-500">Pricing tier</p>
                    </div>
                    <span className="font-semibold text-slate-900">{business?.rate_group || 'Standard'}</span>
                  </div>
                </div>
              </div>

              <div className="pt-6 border-t border-slate-200">
                <h4 className="font-semibold text-slate-900 mb-3">Danger Zone</h4>
                <div className="flex gap-3">
                  <Button variant="outline" className="border-red-300 text-red-600 hover:bg-red-50">
                    <Trash2 className="w-4 h-4 mr-2" />Delete Business
                  </Button>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </TabsContent>
    </Tabs>
      </div>
    </div>
  );
}