import React, { useState } 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, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ArrowLeft, Edit, UserPlus, MapPin, Star, UserX, Search, Mail, Loader2 } from "lucide-react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/components/ui/use-toast";

export default function TeamDetails() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { toast } = useToast();
  const urlParams = new URLSearchParams(window.location.search);
  const teamId = urlParams.get('id');
  
  const [activeTab, setActiveTab] = useState("details");
  const [memberTab, setMemberTab] = useState("active");
  const [searchTerm, setSearchTerm] = useState("");
  const [showInviteMemberDialog, setShowInviteMemberDialog] = useState(false);
  const [showEditMemberDialog, setShowEditMemberDialog] = useState(false);
  const [showAddHubDialog, setShowAddHubDialog] = useState(false);
  const [editingMember, setEditingMember] = useState(null);
  
  const [inviteData, setInviteData] = useState({
    email: "",
    full_name: "",
    role: "member",
    title: "",
    department: "",
    hub: ""
  });
  
  const [newHub, setNewHub] = useState({
    hub_name: "",
    address: "",
    city: "",
    state: "",
    zip_code: "",
    manager_name: "",
    manager_email: "",
    departments: []
  });
  
  const [showAddDepartmentDialog, setShowAddDepartmentDialog] = useState(false);
  const [selectedHub, setSelectedHub] = useState(null);
  const [newDepartment, setNewDepartment] = useState({
    department_name: "",
    cost_center: "",
    manager_name: ""
  });
  
  const [favoriteSearch, setFavoriteSearch] = useState("");
  const [blockedSearch, setBlockedSearch] = useState("");
  const [showAddFavoriteDialog, setShowAddFavoriteDialog] = useState(false);
  const [showAddBlockedDialog, setShowAddBlockedDialog] = useState(false);
  const [blockReason, setBlockReason] = useState("");

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

  const { data: team, isLoading } = useQuery({
    queryKey: ['team', teamId],
    queryFn: async () => {
      const allTeams = await base44.entities.Team.list();
      return allTeams.find(t => t.id === teamId);
    },
    enabled: !!teamId,
  });

  const { data: members = [] } = useQuery({
    queryKey: ['team-members', teamId],
    queryFn: async () => {
      const allMembers = await base44.entities.TeamMember.list('-created_date');
      return allMembers.filter(m => m.team_id === teamId);
    },
    enabled: !!teamId,
    initialData: [],
  });

  const { data: hubs = [] } = useQuery({
    queryKey: ['team-hubs', teamId],
    queryFn: async () => {
      const allHubs = await base44.entities.TeamHub.list('-created_date');
      return allHubs.filter(h => h.team_id === teamId);
    },
    enabled: !!teamId,
    initialData: [],
  });
  
  const { data: allStaff = [] } = useQuery({
    queryKey: ['staff-for-favorites'],
    queryFn: () => base44.entities.Staff.list(),
    enabled: !!teamId,
    initialData: [],
  });

  const updateMemberMutation = useMutation({
    mutationFn: ({ id, data }) => base44.entities.TeamMember.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['team-members', teamId] });
      setShowEditMemberDialog(false);
      setEditingMember(null);
      toast({
        title: "Member Updated",
        description: "Team member updated successfully",
      });
    },
  });

  const inviteMemberMutation = useMutation({
    mutationFn: async (data) => {
      // Generate unique invite code
      const inviteCode = `TEAM-${Math.floor(10000 + Math.random() * 90000)}`;
      
      // Create invite record
      const invite = await base44.entities.TeamMemberInvite.create({
        team_id: teamId,
        team_name: team?.team_name,
        invite_code: inviteCode,
        email: data.email,
        full_name: data.full_name,
        role: data.role,
        invited_by: user?.email || user?.full_name,
        invite_status: "pending",
        invited_date: new Date().toISOString(),
        expires_at: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString() // 7 days
      });

      // Send email invitation
      const acceptUrl = `${window.location.origin}${createPageUrl('TeamDetails')}?id=${teamId}&invite=${inviteCode}`;
      
      await base44.integrations.Core.SendEmail({
        from_name: team?.team_name || "Team",
        to: data.email,
        subject: `You're invited to join ${team?.team_name}!`,
        body: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; background: linear-gradient(to bottom, #f8fafc, #e0f2fe); border-radius: 12px;">
            <div style="text-align: center; padding: 20px; background: linear-gradient(to right, #0A39DF, #1C323E); border-radius: 12px 12px 0 0;">
              <h1 style="color: white; margin: 0;">Team Invitation</h1>
              <p style="color: #e0f2fe; margin-top: 8px;">Join ${team?.team_name}</p>
            </div>
            
            <div style="padding: 30px; background: white; border-radius: 0 0 12px 12px;">
              <p style="color: #1C323E; font-size: 16px; line-height: 1.6;">
                Hi ${data.full_name || 'there'},
              </p>
              
              <p style="color: #475569; font-size: 14px; line-height: 1.6; margin-top: 16px;">
                <strong>${user?.full_name || user?.email}</strong> has invited you to join <strong>${team?.team_name}</strong> as a <strong>${data.role}</strong>.
              </p>

              ${data.title ? `<p style="color: #475569; font-size: 14px;"><strong>Position:</strong> ${data.title}</p>` : ''}
              ${data.department ? `<p style="color: #475569; font-size: 14px;"><strong>Department:</strong> ${data.department}</p>` : ''}
              ${data.hub ? `<p style="color: #475569; font-size: 14px;"><strong>Hub:</strong> ${data.hub}</p>` : ''}

              <div style="text-align: center; margin: 32px 0;">
                <a href="${acceptUrl}" 
                   style="display: inline-block; padding: 16px 32px; background: linear-gradient(to right, #0A39DF, #1C323E); 
                          color: white; text-decoration: none; border-radius: 8px; font-weight: bold; font-size: 16px;
                          box-shadow: 0 4px 6px rgba(10, 57, 223, 0.3);">
                  Accept Invitation
                </a>
              </div>

              <div style="background: #fef3c7; padding: 16px; border-radius: 8px; margin-top: 24px; border: 1px solid #fbbf24;">
                <p style="color: #92400e; font-size: 13px; margin: 0;">
                  <strong>📋 Note:</strong> This invitation will expire in 7 days.
                </p>
              </div>

              <p style="color: #64748b; font-size: 13px; margin-top: 32px; padding-top: 20px; border-top: 1px solid #e2e8f0;">
                Your invite code: <strong>${inviteCode}</strong><br>
                Questions? Contact ${user?.email || 'the team admin'}
              </p>
            </div>
          </div>
        `
      });

      return invite;
    },
    onSuccess: () => {
      setShowInviteMemberDialog(false);
      setInviteData({
        email: "",
        full_name: "",
        role: "member",
        title: "",
        department: "",
        hub: ""
      });
      toast({
        title: "Invitation Sent",
        description: `Invitation sent to ${inviteData.email}`,
      });
    },
  });

  const addHubMutation = useMutation({
    mutationFn: (hubData) => base44.entities.TeamHub.create(hubData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['team-hubs', teamId] });
      queryClient.invalidateQueries({ queryKey: ['team', teamId] });
      setShowAddHubDialog(false);
      setNewHub({
        hub_name: "",
        address: "",
        city: "",
        state: "",
        zip_code: "",
        manager_name: "",
        manager_email: "",
        departments: []
      });
      toast({
        title: "Hub Created",
        description: "Hub created successfully",
      });
    },
  });
  
  const updateTeamMutation = useMutation({
    mutationFn: ({ id, data }) => base44.entities.Team.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['team', teamId] });
      toast({
        title: "Updated",
        description: "Team updated successfully",
      });
    },
  });
  
  const addToFavorites = (staff) => {
    const favoriteStaff = team.favorite_staff || [];
    const newFavorite = {
      staff_id: staff.id,
      staff_name: staff.employee_name,
      position: staff.position,
      added_date: new Date().toISOString()
    };
    
    updateTeamMutation.mutate({
      id: teamId,
      data: {
        favorite_staff: [...favoriteStaff, newFavorite],
        favorite_staff_count: favoriteStaff.length + 1
      }
    });
    setShowAddFavoriteDialog(false);
  };
  
  const removeFromFavorites = (staffId) => {
    const favoriteStaff = (team.favorite_staff || []).filter(f => f.staff_id !== staffId);
    updateTeamMutation.mutate({
      id: teamId,
      data: {
        favorite_staff: favoriteStaff,
        favorite_staff_count: favoriteStaff.length
      }
    });
  };
  
  const addToBlocked = (staff) => {
    const blockedStaff = team.blocked_staff || [];
    const newBlocked = {
      staff_id: staff.id,
      staff_name: staff.employee_name,
      reason: blockReason,
      blocked_date: new Date().toISOString()
    };
    
    updateTeamMutation.mutate({
      id: teamId,
      data: {
        blocked_staff: [...blockedStaff, newBlocked],
        blocked_staff_count: blockedStaff.length + 1
      }
    });
    setShowAddBlockedDialog(false);
    setBlockReason("");
  };
  
  const removeFromBlocked = (staffId) => {
    const blockedStaff = (team.blocked_staff || []).filter(b => b.staff_id !== staffId);
    updateTeamMutation.mutate({
      id: teamId,
      data: {
        blocked_staff: blockedStaff,
        blocked_staff_count: blockedStaff.length
      }
    });
  };

  const handleEditMember = (member) => {
    setEditingMember(member);
    setShowEditMemberDialog(true);
  };

  const handleUpdateMember = () => {
    updateMemberMutation.mutate({
      id: editingMember.id,
      data: editingMember
    });
  };

  const handleInviteMember = () => {
    inviteMemberMutation.mutate(inviteData);
  };

  const handleAddHub = () => {
    addHubMutation.mutate({
      ...newHub,
      team_id: teamId,
      is_active: true
    });
  };

  const activeMembers = members.filter(m => m.is_active);
  const deactivatedMembers = members.filter(m => !m.is_active);

  const filteredMembers = (memberTab === "active" ? activeMembers : deactivatedMembers).filter(m =>
    !searchTerm ||
    m.member_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    m.email?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    m.title?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="w-16 h-16 border-4 border-[#0A39DF] border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-slate-600">Loading team details...</p>
        </div>
      </div>
    );
  }

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

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        <Button
          variant="ghost"
          onClick={() => navigate(createPageUrl("Teams"))}
          className="mb-4 hover:bg-slate-100"
        >
          <ArrowLeft className="w-4 h-4 mr-2" />
          Back to Teams
        </Button>

        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-4">
            <Avatar className="w-16 h-16 border-2 border-slate-200">
              <AvatarImage src={team.company_logo} />
              <AvatarFallback className="bg-gradient-to-br from-[#0A39DF] to-[#1C323E] text-white text-2xl font-bold">
                {team.team_name?.charAt(0) || 'T'}
              </AvatarFallback>
            </Avatar>
            <div>
              <h1 className="text-3xl font-bold text-[#1C323E]">Teams</h1>
              <p className="text-slate-500 text-sm mt-1">{team.team_name}</p>
            </div>
          </div>
          <div className="flex gap-2">
            <Button 
              className="bg-[#0A39DF] hover:bg-[#0A39DF]/90 text-white"
              onClick={() => setShowInviteMemberDialog(true)}
            >
              <Mail className="w-4 h-4 mr-2" />
              Invite team member
            </Button>
            <Button 
              className="bg-yellow-400 hover:bg-yellow-500 text-slate-900 font-semibold"
              onClick={() => setShowAddHubDialog(true)}
            >
              <MapPin className="w-4 h-4 mr-2" />
              Create hub
            </Button>
          </div>
        </div>

        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="bg-white border-b border-slate-200 h-auto p-0 rounded-none w-full justify-start">
            <TabsTrigger 
              value="details" 
              className="data-[state=active]:border-b-2 data-[state=active]:border-[#0A39DF] rounded-none px-6 py-3 data-[state=active]:bg-transparent"
            >
              Details
            </TabsTrigger>
            <TabsTrigger 
              value="members" 
              className="data-[state=active]:border-b-2 data-[state=active]:border-[#0A39DF] rounded-none px-6 py-3 data-[state=active]:bg-transparent"
            >
              Team members 
              <Badge className="ml-2 bg-[#0A39DF] text-white hover:bg-[#0A39DF]">{members.length}</Badge>
            </TabsTrigger>
            <TabsTrigger 
              value="hubs" 
              className="data-[state=active]:border-b-2 data-[state=active]:border-[#0A39DF] rounded-none px-6 py-3 data-[state=active]:bg-transparent"
            >
              Hubs 
              <Badge variant="outline" className="ml-2">{hubs.length}</Badge>
            </TabsTrigger>
            <TabsTrigger 
              value="favorite" 
              className="data-[state=active]:border-b-2 data-[state=active]:border-[#0A39DF] rounded-none px-6 py-3 data-[state=active]:bg-transparent"
            >
              Favorite staff 
              <Badge variant="outline" className="ml-2">{team.favorite_staff_count || 0}</Badge>
            </TabsTrigger>
            <TabsTrigger 
              value="blocked" 
              className="data-[state=active]:border-b-2 data-[state=active]:border-[#0A39DF] rounded-none px-6 py-3 data-[state=active]:bg-transparent"
            >
              Blocked staff 
              <Badge variant="outline" className="ml-2">{team.blocked_staff_count || 0}</Badge>
            </TabsTrigger>
          </TabsList>

          {/* Details Tab */}
          <TabsContent value="details" className="mt-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* Company Logo */}
              <Card className="border-slate-200">
                <CardContent className="p-6">
                  <h3 className="font-semibold text-[#1C323E] mb-4">Company Logo</h3>
                  <div className="flex items-center justify-center">
                    <Avatar className="w-32 h-32 border-2 border-slate-200">
                      <AvatarImage src={team.company_logo} />
                      <AvatarFallback className="bg-gradient-to-br from-[#0A39DF] to-[#1C323E] text-white text-5xl font-bold">
                        {team.team_name?.charAt(0) || 'T'}
                      </AvatarFallback>
                    </Avatar>
                  </div>
                </CardContent>
              </Card>

              {/* Personal Info */}
              <Card className="border-slate-200">
                <CardContent className="p-6">
                  <h3 className="font-semibold text-[#1C323E] mb-4">Personal Info</h3>
                  <div className="space-y-3">
                    <div>
                      <Label className="text-xs text-slate-500">Full name:</Label>
                      <p className="font-semibold">{team.full_name || '-'}</p>
                    </div>
                    <div>
                      <Label className="text-xs text-slate-500">Email:</Label>
                      <p className="font-semibold">{team.email || '-'}</p>
                    </div>
                    <div>
                      <Label className="text-xs text-slate-500">Phone:</Label>
                      <p className="font-semibold">{team.phone || '-'}</p>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Contact Info */}
              <Card className="border-slate-200 md:col-span-2">
                <CardContent className="p-6">
                  <h3 className="font-semibold text-[#1C323E] mb-4">Contact Info</h3>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                      <Label className="text-xs text-slate-500">Address:</Label>
                      <p className="font-semibold">{team.address || '-'}</p>
                    </div>
                    <div>
                      <Label className="text-xs text-slate-500">City:</Label>
                      <p className="font-semibold">{team.city || '-'}</p>
                    </div>
                    <div>
                      <Label className="text-xs text-slate-500">ZIP Code:</Label>
                      <p className="font-semibold">{team.zip_code || '-'}</p>
                    </div>
                    {team.vendor_id && (
                      <div>
                        <Label className="text-xs text-slate-500">Vendor ID:</Label>
                        <p className="font-semibold">{team.vendor_id}</p>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            </div>

            <div className="flex justify-center mt-6">
              <Button variant="outline">
                <Edit className="w-4 h-4 mr-2" />
                Edit
              </Button>
            </div>
          </TabsContent>

          {/* Team Members Tab */}
          <TabsContent value="members" className="mt-6">
            <Card className="border-slate-200">
              <CardContent className="p-6">
                {/* Search */}
                <div className="mb-4">
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400" />
                    <Input
                      placeholder="Search"
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                      className="pl-10"
                    />
                  </div>
                </div>

                {/* Active / Deactivated Tabs */}
                <Tabs value={memberTab} onValueChange={setMemberTab} className="mb-4">
                  <TabsList className="bg-transparent border-b border-slate-200 h-auto p-0 rounded-none w-full justify-start">
                    <TabsTrigger 
                      value="active"
                      className="data-[state=active]:border-b-2 data-[state=active]:border-[#0A39DF] rounded-none px-4 py-2 data-[state=active]:bg-transparent"
                    >
                      Active 
                      <Badge className="ml-2 bg-[#0A39DF] text-white hover:bg-[#0A39DF]">{activeMembers.length}</Badge>
                    </TabsTrigger>
                    <TabsTrigger 
                      value="deactivated"
                      className="data-[state=active]:border-b-2 data-[state=active]:border-[#0A39DF] rounded-none px-4 py-2 data-[state=active]:bg-transparent"
                    >
                      Deactivated 
                      <Badge variant="outline" className="ml-2">{deactivatedMembers.length}</Badge>
                    </TabsTrigger>
                  </TabsList>
                </Tabs>

                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-12">#</TableHead>
                      <TableHead>Name</TableHead>
                      <TableHead>Title</TableHead>
                      <TableHead>Role</TableHead>
                      <TableHead>Department</TableHead>
                      <TableHead>Hub</TableHead>
                      <TableHead className="w-20">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredMembers.length > 0 ? (
                      filteredMembers.map((member, index) => (
                        <TableRow key={member.id}>
                          <TableCell className="font-medium">{index + 1}</TableCell>
                          <TableCell>
                            <div className="flex items-center gap-3">
                              <Avatar className="w-10 h-10">
                                <AvatarImage src={member.avatar_url} />
                                <AvatarFallback className="bg-[#0A39DF] text-white">
                                  {member.member_name?.charAt(0) || '?'}
                                </AvatarFallback>
                              </Avatar>
                              <div>
                                <p className="font-semibold">{member.member_name}</p>
                                <p className="text-xs text-slate-500">{member.email}</p>
                              </div>
                            </div>
                          </TableCell>
                          <TableCell>{member.title || '-'}</TableCell>
                          <TableCell>
                            <Badge variant="outline" className="capitalize">
                              {member.role}
                            </Badge>
                          </TableCell>
                          <TableCell>{member.department || 'No Department'}</TableCell>
                          <TableCell>{member.hub || 'No Hub'}</TableCell>
                          <TableCell>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => handleEditMember(member)}
                              className="hover:text-[#0A39DF] hover:bg-blue-50"
                            >
                              <Edit className="w-4 h-4" />
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))
                    ) : (
                      <TableRow>
                        <TableCell colSpan={7} className="text-center py-8 text-slate-500">
                          No members found
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>

                {filteredMembers.length > 0 && (
                  <div className="flex items-center justify-center gap-2 mt-4">
                    <p className="text-sm text-slate-500">1-{filteredMembers.length} of {filteredMembers.length}</p>
                    <div className="flex gap-1">
                      <Button variant="outline" size="icon" className="w-8 h-8">‹</Button>
                      <Button variant="outline" size="sm" className="w-8 h-8">1</Button>
                      <Button variant="outline" size="icon" className="w-8 h-8">›</Button>
                    </div>
                    <Select defaultValue="10">
                      <SelectTrigger className="w-24 h-8">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="10">10 / page</SelectItem>
                        <SelectItem value="25">25 / page</SelectItem>
                        <SelectItem value="50">50 / page</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* Hubs Tab */}
          <TabsContent value="hubs" className="mt-6">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {hubs.length > 0 ? (
                hubs.map((hub) => (
                  <Card key={hub.id} className="border-slate-200 hover:border-[#0A39DF] hover:shadow-lg transition-all">
                    <CardContent className="p-6">
                      <div className="flex items-start gap-3 mb-4">
                        <div className="w-12 h-12 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg flex items-center justify-center text-white">
                          <MapPin className="w-6 h-6" />
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <h3 className="font-bold text-lg text-[#1C323E]">{hub.hub_name}</h3>
                            <Badge className="bg-[#0A39DF] text-white">
                              {members.filter(m => m.hub === hub.hub_name).length} members
                            </Badge>
                          </div>
                          {hub.manager_name && (
                            <p className="text-sm text-slate-500">Manager: {hub.manager_name}</p>
                          )}
                        </div>
                      </div>
                      <div className="space-y-2 text-sm mb-4">
                        {hub.address && <p className="text-slate-600">{hub.address}</p>}
                        {hub.city && (
                          <p className="text-slate-600">
                            {hub.city}{hub.state ? `, ${hub.state}` : ''} {hub.zip_code}
                          </p>
                        )}
                        {hub.manager_email && (
                          <p className="text-slate-600">{hub.manager_email}</p>
                        )}
                      </div>
                      
                      {hub.departments && hub.departments.length > 0 && (
                        <div className="border-t pt-4 mt-4">
                          <p className="text-xs font-semibold text-slate-600 mb-2">DEPARTMENTS</p>
                          <div className="space-y-2">
                            {hub.departments.map((dept, idx) => (
                              <div key={idx} className="bg-slate-50 p-2 rounded text-xs">
                                <p className="font-semibold text-slate-900">{dept.department_name}</p>
                                {dept.cost_center && (
                                  <p className="text-slate-600">Cost Center: {dept.cost_center}</p>
                                )}
                                {dept.manager_name && (
                                  <p className="text-slate-600">Manager: {dept.manager_name}</p>
                                )}
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                      
                      <Button 
                        variant="outline" 
                        size="sm" 
                        className="w-full mt-4"
                        onClick={() => {
                          setSelectedHub(hub);
                          setShowAddDepartmentDialog(true);
                        }}
                      >
                        <Plus className="w-3 h-3 mr-2" />
                        Add Department
                      </Button>
                    </CardContent>
                  </Card>
                ))
              ) : (
                <Card className="border-slate-200 col-span-full">
                  <CardContent className="p-12 text-center">
                    <MapPin className="w-16 h-16 mx-auto text-slate-300 mb-4" />
                    <h3 className="text-xl font-semibold text-slate-700 mb-2">No Hubs Yet</h3>
                    <p className="text-slate-500 mb-6">Create your first hub location</p>
                    <Button className="bg-yellow-400 hover:bg-yellow-500 text-slate-900 font-semibold" onClick={() => setShowAddHubDialog(true)}>
                      <MapPin className="w-4 h-4 mr-2" />
                      Create First Hub
                    </Button>
                  </CardContent>
                </Card>
              )}
            </div>
          </TabsContent>

          {/* Favorite Staff Tab */}
          <TabsContent value="favorite" className="mt-6">
            <Card className="border-slate-200">
              <CardContent className="p-6">
                <div className="flex items-center justify-between mb-4">
                  <div className="relative flex-1 max-w-md">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400" />
                    <Input
                      placeholder="Search favorite staff..."
                      value={favoriteSearch}
                      onChange={(e) => setFavoriteSearch(e.target.value)}
                      className="pl-10"
                    />
                  </div>
                  <Button onClick={() => setShowAddFavoriteDialog(true)} className="bg-[#0A39DF]">
                    <Star className="w-4 h-4 mr-2" />
                    Add Favorite
                  </Button>
                </div>
                
                {team.favorite_staff && team.favorite_staff.length > 0 ? (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {team.favorite_staff.filter(f => 
                      !favoriteSearch || 
                      f.staff_name?.toLowerCase().includes(favoriteSearch.toLowerCase()) ||
                      f.position?.toLowerCase().includes(favoriteSearch.toLowerCase())
                    ).map((fav) => (
                      <Card key={fav.staff_id} className="border-amber-200 bg-amber-50">
                        <CardContent className="p-4">
                          <div className="flex items-start justify-between mb-3">
                            <div className="flex items-center gap-3">
                              <Avatar className="w-12 h-12 border-2 border-amber-300">
                                <AvatarFallback className="bg-amber-200 text-amber-700 font-bold">
                                  {fav.staff_name?.charAt(0)}
                                </AvatarFallback>
                              </Avatar>
                              <div>
                                <p className="font-bold text-slate-900">{fav.staff_name}</p>
                                <p className="text-xs text-slate-600">{fav.position}</p>
                              </div>
                            </div>
                            <Star className="w-5 h-5 text-amber-500 fill-amber-500" />
                          </div>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => removeFromFavorites(fav.staff_id)}
                            className="w-full border-amber-300 hover:bg-amber-100 text-xs"
                          >
                            Remove
                          </Button>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-12">
                    <Star className="w-16 h-16 mx-auto text-slate-300 mb-4" />
                    <h3 className="text-xl font-semibold text-slate-700 mb-2">No Favorite Staff</h3>
                    <p className="text-slate-500 mb-4">Mark staff as favorites to see them here</p>
                    <Button onClick={() => setShowAddFavoriteDialog(true)} className="bg-[#0A39DF]">
                      <Star className="w-4 h-4 mr-2" />
                      Add Your First Favorite
                    </Button>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* Blocked Staff Tab */}
          <TabsContent value="blocked" className="mt-6">
            <Card className="border-slate-200">
              <CardContent className="p-6">
                <div className="flex items-center justify-between mb-4">
                  <div className="relative flex-1 max-w-md">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400" />
                    <Input
                      placeholder="Search blocked staff..."
                      value={blockedSearch}
                      onChange={(e) => setBlockedSearch(e.target.value)}
                      className="pl-10"
                    />
                  </div>
                  <Button onClick={() => setShowAddBlockedDialog(true)} variant="outline" className="border-red-300 text-red-600 hover:bg-red-50">
                    <UserX className="w-4 h-4 mr-2" />
                    Block Staff
                  </Button>
                </div>
                
                {team.blocked_staff && team.blocked_staff.length > 0 ? (
                  <div className="space-y-3">
                    {team.blocked_staff.filter(b => 
                      !blockedSearch || 
                      b.staff_name?.toLowerCase().includes(blockedSearch.toLowerCase())
                    ).map((blocked) => (
                      <Card key={blocked.staff_id} className="border-red-200 bg-red-50">
                        <CardContent className="p-4">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-3">
                              <Avatar className="w-12 h-12 border-2 border-red-300">
                                <AvatarFallback className="bg-red-200 text-red-700 font-bold">
                                  {blocked.staff_name?.charAt(0)}
                                </AvatarFallback>
                              </Avatar>
                              <div className="flex-1">
                                <p className="font-bold text-slate-900">{blocked.staff_name}</p>
                                <p className="text-xs text-slate-600 mt-1"><strong>Reason:</strong> {blocked.reason || 'No reason provided'}</p>
                                <p className="text-[10px] text-slate-500 mt-1">Blocked {new Date(blocked.blocked_date).toLocaleDateString()}</p>
                              </div>
                            </div>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => removeFromBlocked(blocked.staff_id)}
                              className="border-red-300 hover:bg-red-100 text-red-600 text-xs"
                            >
                              Unblock
                            </Button>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-12">
                    <UserX className="w-16 h-16 mx-auto text-slate-300 mb-4" />
                    <h3 className="text-xl font-semibold text-slate-700 mb-2">No Blocked Staff</h3>
                    <p className="text-slate-500">Blocked staff will appear here</p>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>

        {/* Invite Member Dialog */}
        <Dialog open={showInviteMemberDialog} onOpenChange={setShowInviteMemberDialog}>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle className="text-xl font-bold">Invite team member</DialogTitle>
              <p className="text-sm text-slate-500 mt-2">
                At Instawork, every person has a role, each with its own level of access. <a href="#" className="text-[#0A39DF] hover:underline">Learn more</a>
              </p>
            </DialogHeader>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>First name</Label>
                <Input
                  value={inviteData.full_name.split(' ')[0] || ""}
                  onChange={(e) => {
                    const firstName = e.target.value;
                    const lastName = inviteData.full_name.split(' ').slice(1).join(' ');
                    setInviteData({ ...inviteData, full_name: `${firstName} ${lastName}`.trim() });
                  }}
                  placeholder=""
                />
              </div>
              <div>
                <Label>Last name</Label>
                <Input
                  value={inviteData.full_name.split(' ').slice(1).join(' ') || ""}
                  onChange={(e) => {
                    const firstName = inviteData.full_name.split(' ')[0] || "";
                    const lastName = e.target.value;
                    setInviteData({ ...inviteData, full_name: `${firstName} ${lastName}`.trim() });
                  }}
                  placeholder=""
                />
              </div>
              <div>
                <Label>Email</Label>
                <Input
                  type="email"
                  value={inviteData.email}
                  onChange={(e) => setInviteData({ ...inviteData, email: e.target.value })}
                  placeholder=""
                />
              </div>
              <div>
                <Label>Access level</Label>
                <Select value={inviteData.role} onValueChange={(value) => setInviteData({ ...inviteData, role: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="admin">Admin</SelectItem>
                    <SelectItem value="member">Member</SelectItem>
                    <SelectItem value="manager">Shift coordinator</SelectItem>
                    <SelectItem value="viewer">Booking shift coordinator</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              {/* These fields are no longer needed for invite, but are part of the mutation payload */}
              {/* Keeping hidden inputs or removing them depends on if the backend expects them */}
              {/* For now, they can remain in state and simply not be rendered in the UI */}
            </div>
            <DialogFooter className="mt-6">
              <Button variant="outline" onClick={() => setShowInviteMemberDialog(false)}>Cancel</Button>
              <Button 
                onClick={handleInviteMember} 
                className="bg-[#0A39DF] hover:bg-[#0A39DF]/90" 
                disabled={!inviteData.email || !inviteData.full_name || inviteMemberMutation.isPending}
              >
                {inviteMemberMutation.isPending ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    Sending invitation...
                  </>
                ) : (
                  "Send invitation"
                )}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Edit Member Dialog */}
        <Dialog open={showEditMemberDialog} onOpenChange={setShowEditMemberDialog}>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>Edit Team Member</DialogTitle>
            </DialogHeader>
            {editingMember && (
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>Full Name *</Label>
                  <Input
                    value={editingMember.member_name}
                    onChange={(e) => setEditingMember({ ...editingMember, member_name: e.target.value })}
                    placeholder="John Doe"
                  />
                </div>
                <div>
                  <Label>Email *</Label>
                  <Input
                    type="email"
                    value={editingMember.email}
                    onChange={(e) => setEditingMember({ ...editingMember, email: e.target.value })}
                    placeholder="john@example.com"
                  />
                </div>
                <div>
                  <Label>Phone</Label>
                  <Input
                    value={editingMember.phone || ""}
                    onChange={(e) => setEditingMember({ ...editingMember, phone: e.target.value })}
                    placeholder="+1 (555) 123-4567"
                  />
                </div>
                <div>
                  <Label>Title</Label>
                  <Input
                    value={editingMember.title || ""}
                    onChange={(e) => setEditingMember({ ...editingMember, title: e.target.value })}
                    placeholder="Manager"
                  />
                </div>
                <div>
                  <Label>Role</Label>
                  <Select value={editingMember.role} onValueChange={(value) => setEditingMember({ ...editingMember, role: value })}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="admin">Admin</SelectItem>
                      <SelectItem value="manager">Manager</SelectItem>
                      <SelectItem value="member">Member</SelectItem>
                      <SelectItem value="viewer">Viewer</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>Department</Label>
                  <Input
                    value={editingMember.department || ""}
                    onChange={(e) => setEditingMember({ ...editingMember, department: e.target.value })}
                    placeholder="Operations"
                  />
                </div>
                <div className="col-span-2">
                  <Label>Hub</Label>
                  <Select value={editingMember.hub || ""} onValueChange={(value) => setEditingMember({ ...editingMember, hub: value })}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select hub" />
                    </SelectTrigger>
                    <SelectContent>
                      {hubs.map((hub) => (
                        <SelectItem key={hub.id} value={hub.hub_name}>{hub.hub_name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            )}
            <DialogFooter>
              <Button variant="outline" onClick={() => setShowEditMemberDialog(false)}>Cancel</Button>
              <Button 
                onClick={handleUpdateMember} 
                className="bg-[#0A39DF]" 
                disabled={!editingMember?.member_name || !editingMember?.email || updateMemberMutation.isPending}
              >
                {updateMemberMutation.isPending ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    Updating...
                  </>
                ) : (
                  <>
                    <Edit className="w-4 h-4 mr-2" />
                    Update Member
                  </>
                )}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Add Hub Dialog */}
        <Dialog open={showAddHubDialog} onOpenChange={setShowAddHubDialog}>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>Create Hub</DialogTitle>
            </DialogHeader>
            <div className="grid grid-cols-2 gap-4">
              <div className="col-span-2">
                <Label>Hub Name *</Label>
                <Input
                  value={newHub.hub_name}
                  onChange={(e) => setNewHub({ ...newHub, hub_name: e.target.value })}
                  placeholder="BVG 300"
                />
              </div>
              <div className="col-span-2">
                <Label>Address</Label>
                <Input
                  value={newHub.address}
                  onChange={(e) => setNewHub({ ...newHub, address: e.target.value })}
                  placeholder="300 Bayview Dr, Mountain View, CA 94043"
                />
              </div>
              <div>
                <Label>City</Label>
                <Input
                  value={newHub.city}
                  onChange={(e) => setNewHub({ ...newHub, city: e.target.value })}
                  placeholder="Mountain View"
                />
              </div>
              <div>
                <Label>State</Label>
                <Input
                  value={newHub.state}
                  onChange={(e) => setNewHub({ ...newHub, state: e.target.value })}
                  placeholder="CA"
                />
              </div>
              <div>
                <Label>ZIP Code</Label>
                <Input
                  value={newHub.zip_code}
                  onChange={(e) => setNewHub({ ...newHub, zip_code: e.target.value })}
                  placeholder="94043"
                />
              </div>
              <div>
                <Label>Manager Name</Label>
                <Input
                  value={newHub.manager_name}
                  onChange={(e) => setNewHub({ ...newHub, manager_name: e.target.value })}
                  placeholder="Jane Smith"
                />
              </div>
              <div className="col-span-2">
                <Label>Manager Email</Label>
                <Input
                  type="email"
                  value={newHub.manager_email}
                  onChange={(e) => setNewHub({ ...newHub, manager_email: e.target.value })}
                  placeholder="jane@example.com"
                />
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setShowAddHubDialog(false)}>Cancel</Button>
              <Button onClick={handleAddHub} className="bg-yellow-400 hover:bg-yellow-500 text-slate-900" disabled={!newHub.hub_name}>
                Create Hub
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
        
        {/* Add Department Dialog */}
        <Dialog open={showAddDepartmentDialog} onOpenChange={setShowAddDepartmentDialog}>
          <DialogContent className="max-w-lg">
            <DialogHeader>
              <DialogTitle>Add Department to {selectedHub?.hub_name}</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <div>
                <Label>Department Name *</Label>
                <Input
                  value={newDepartment.department_name}
                  onChange={(e) => setNewDepartment({ ...newDepartment, department_name: e.target.value })}
                  placeholder="Catering FOH or Catering BOH"
                />
              </div>
              <div>
                <Label>Cost Center</Label>
                <Input
                  value={newDepartment.cost_center}
                  onChange={(e) => setNewDepartment({ ...newDepartment, cost_center: e.target.value })}
                  placeholder="CC-12345"
                />
              </div>
              <div>
                <Label>Department Manager</Label>
                <Input
                  value={newDepartment.manager_name}
                  onChange={(e) => setNewDepartment({ ...newDepartment, manager_name: e.target.value })}
                  placeholder="Manager name"
                />
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => {
                setShowAddDepartmentDialog(false);
                setNewDepartment({ department_name: "", cost_center: "", manager_name: "" });
              }}>Cancel</Button>
              <Button 
                onClick={async () => {
                  const updatedDepartments = [...(selectedHub.departments || []), newDepartment];
                  await base44.entities.TeamHub.update(selectedHub.id, {
                    departments: updatedDepartments
                  });
                  queryClient.invalidateQueries({ queryKey: ['team-hubs', teamId] });
                  setShowAddDepartmentDialog(false);
                  setNewDepartment({ department_name: "", cost_center: "", manager_name: "" });
                  toast({ title: "Department Added", description: "Department created successfully" });
                }}
                className="bg-[#0A39DF]"
                disabled={!newDepartment.department_name}
              >
                Add Department
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
        
        {/* Add Favorite Staff Dialog */}
        <Dialog open={showAddFavoriteDialog} onOpenChange={setShowAddFavoriteDialog}>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>Add Favorite Staff</DialogTitle>
            </DialogHeader>
            <div className="max-h-96 overflow-y-auto space-y-2">
              {allStaff.filter(s => !(team.favorite_staff || []).some(f => f.staff_id === s.id)).map((staff) => (
                <Card key={staff.id} className="cursor-pointer hover:bg-blue-50 transition-colors" onClick={() => addToFavorites(staff)}>
                  <CardContent className="p-4">
                    <div className="flex items-center gap-3">
                      <Avatar className="w-10 h-10">
                        <AvatarFallback className="bg-[#0A39DF] text-white">
                          {staff.employee_name?.charAt(0)}
                        </AvatarFallback>
                      </Avatar>
                      <div>
                        <p className="font-semibold">{staff.employee_name}</p>
                        <p className="text-xs text-slate-500">{staff.position}</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setShowAddFavoriteDialog(false)}>Cancel</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
        
        {/* Add Blocked Staff Dialog */}
        <Dialog open={showAddBlockedDialog} onOpenChange={setShowAddBlockedDialog}>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>Block Staff Member</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <div>
                <Label>Reason for blocking *</Label>
                <Input
                  value={blockReason}
                  onChange={(e) => setBlockReason(e.target.value)}
                  placeholder="Performance issues, policy violation, etc."
                />
              </div>
              <div className="max-h-64 overflow-y-auto space-y-2">
                {allStaff.filter(s => !(team.blocked_staff || []).some(b => b.staff_id === s.id)).map((staff) => (
                  <Card key={staff.id} className="cursor-pointer hover:bg-red-50 transition-colors" onClick={() => addToBlocked(staff)}>
                    <CardContent className="p-4">
                      <div className="flex items-center gap-3">
                        <Avatar className="w-10 h-10">
                          <AvatarFallback className="bg-slate-200 text-slate-700">
                            {staff.employee_name?.charAt(0)}
                          </AvatarFallback>
                        </Avatar>
                        <div>
                          <p className="font-semibold">{staff.employee_name}</p>
                          <p className="text-xs text-slate-500">{staff.position}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => {
                setShowAddBlockedDialog(false);
                setBlockReason("");
              }}>Cancel</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>
    </div>
  );
}